Heart Disease Prediction In ASP.NET Core Using ML.NET

Problem

 
This problem is centered around developing an ASP.NET Core MVC Web application that will predict the presence of heart disease based on 14 attributes i.e age, sex, and cp etc. given by the user. To solve this problem, we will build an ML model that takes an input of 14 columns of data from the user, 13 are featured columns (also called independent variables) plus the 'Label' column which is what you want to predict, and in this case, is named 'num', which will tell us the predicted result. Here is the Traning Data downloaded from UCI ML Repository
 

Solution

 
To solve this problem, first, we will create an ASP.NET Core MVC Web application, then we will install prerequisite packages from NuGet manager, and then we will build an ML model for Heart Disease Prediction. Thereafter, we will train the model on existing data, and lastly, we'll consume the model in our ASP.NET Core application to predict if the heart disease is present for given data by the user.
 
Prerequisites
  • Visual Studio (I'm using VS2019)
  • .NET Core 2.1 or > 2.1 SDK
  • Basic understanding of ASP.NET MVC or ASP.NET Core MVC
Let's Start!
  • Open Visual Studio (I'm using 2019), click on "Create New Project" and select ASP.NET Core.

    Heart Disease Prediction In ASP.NET Core Using ML.NET

  • On the configuration of the new project window, select your project name and click on "Create".

    Heart Disease Prediction In ASP.NET Core Using ML.NET

  • Select Web Application (Model-View-Controller).

    Heart Disease Prediction In ASP.NET Core Using ML.NET

  • Open NuGet Package Manager Console and install the following packages.
    1. Install-Package Microsoft.ML  
    2. Install-Package Microsoft.ML.FastTree  
  • After package installation, right-click on the project and add new folders to make the project look good.
  • First, we need to define the data's structure mapped to the datasets to load (HeartTraining.tsv ) with a TextLoader. Create a folder name DataStructures inside ML Model folder and add the following data structure classes that will be used in Machine Learning model. Create two new classes name HeartData.cs and HeartPrediction.cs and add the following snippets one by one.
    1. using Microsoft.ML.Data;  
    2.   
    3. namespace Heart_Disease_Prediction.ML_Model.DataStructures  
    4. {  
    5.     public class HeartData  
    6.     {  
    7.         [LoadColumn(0)]  
    8.         public float Age { getset; }  
    9.         [LoadColumn(1)]  
    10.         public float Sex { getset; }  
    11.         [LoadColumn(2)]  
    12.         public float Cp { getset; }  
    13.         [LoadColumn(3)]  
    14.         public float TrestBps { getset; }  
    15.         [LoadColumn(4)]  
    16.         public float Chol { getset; }  
    17.         [LoadColumn(5)]  
    18.         public float Fbs { getset; }  
    19.         [LoadColumn(6)]  
    20.         public float RestEcg { getset; }  
    21.         [LoadColumn(7)]  
    22.         public float Thalac { getset; }  
    23.         [LoadColumn(8)]  
    24.         public float Exang { getset; }  
    25.         [LoadColumn(9)]  
    26.         public float OldPeak { getset; }  
    27.         [LoadColumn(10)]  
    28.         public float Slope { getset; }  
    29.         [LoadColumn(11)]  
    30.         public float Ca { getset; }  
    31.         [LoadColumn(12)]  
    32.         public float Thal { getset; }  
    33.         [LoadColumn(13)]  
    34.         public bool Label { getset; }  
    35.     }  
    36.   
    37. }   
  • Now, we need a class that will be used to show the heart disease prediction from the model.
    1. using Microsoft.ML.Data;    
    2.     
    3. namespace Heart_Disease_Prediction.ML_Model.DataStructures    
    4. {    
    5.     public class HeartPrediction    
    6.     {    
    7.         // ColumnName attribute is used to change the column name from    
    8.         // its default value, which is the name of the field.    
    9.         [ColumnName("PredictedLabel")]    
    10.         public bool Prediction;    
    11.     
    12.         // No need to specify ColumnName attribute, because the field    
    13.         // name "Probability" is the column name we want.    
    14.         public float Probability;    
    15.     
    16.         public float Score;    
    17.     }    
    18. }   
  • After creating a data structure, now we will build our ML.NET model. I've created a new class named MLModel. You need to create a new folder named Data inside ML Model folder and add the following data files that will be used to train our Machine Learning model. You can download them from here.

  • Create a new class named MLModel.cs and insert the following code into that.
    1. using Heart_Disease_Prediction.ML_Model.DataStructures;  
    2. using Microsoft.ML;  
    3. using System.IO;  
    4. using System.Linq;  
    5.   
    6. namespace Heart_Disease_Prediction.ML_Model  
    7. {  
    8.     public class MLModel  
    9.     {  
    10.         private readonly MLContext mlContext;  
    11.         private ITransformer trainedModel = null;  
    12.   
    13.         private static string BaseDatasetsRelativePath = @"../../../ML Model/Data";  
    14.         private static string TrainDataRelativePath = $"{BaseDatasetsRelativePath}/HeartTraining.csv";  
    15.   
    16.         private static string TrainDataPath = GetAbsolutePath(TrainDataRelativePath);  
    17.   
    18.         public MLModel()  
    19.         {  
    20.             mlContext = new MLContext();  
    21.         }  
    22.         public void Build()  
    23.         {  
    24.             // STEP 1: Common data loading configuration  
    25.             var trainingDataView = mlContext.Data.LoadFromTextFile<HeartData>(TrainDataPath, hasHeader: true, separatorChar: ';');  
    26.   
    27.             // STEP 2: Concatenate the features and set the training algorithm  
    28.             var pipeline = mlContext.Transforms.Concatenate("Features""Age""Sex""Cp""TrestBps""Chol""Fbs""RestEcg""Thalac""Exang""OldPeak""Slope""Ca""Thal")  
    29.                             .Append(mlContext.BinaryClassification.Trainers.FastTree(labelColumnName: "Label", featureColumnName: "Features"));  
    30.             trainedModel = pipeline.Fit(trainingDataView);  
    31.         }  
    32.         public HeartPrediction Consume(HeartData input)  
    33.         {  
    34.             var predictionEngine = mlContext.Model.CreatePredictionEngine<HeartData, HeartPrediction>(trainedModel);  
    35.             return predictionEngine.Predict(input);  
    36.         }  
    37.         private static string GetAbsolutePath(string relativePath)  
    38.         {  
    39.             FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);  
    40.             string assemblyFolderPath = _dataRoot.Directory.FullName;  
    41.   
    42.             string fullPath = Path.Combine(assemblyFolderPath, relativePath);  
    43.   
    44.             return fullPath;  
    45.   
    46.         }  
    47.     }  
    48. }  
  • In the above-given snippet, first, we have created an Estimator by concatenating the features into single 'features' column. Then, we chose our trainer/algorithm (I selected FastTree) to train the model with it.

  • To train the model, we have implemented in the Fit() method from the Estimator object. Note: The ML.NET works with data with a lazy loading approach.
  • After all this, your project would look like this.

    Heart Disease Prediction In ASP.NET Core Using ML.NET

  • Now, we need to add controller and views for user interaction. Make an empty controller named HeartDisease and insert the following snippet.
    1. using Microsoft.AspNetCore.Mvc;  
    2. using Heart_Disease_Prediction.ML_Model.DataStructures;  
    3. using Heart_Disease_Prediction.ML_Model;  
    4.   
    5. namespace Heart_Disease_Prediction.Controllers  
    6. {  
    7.     public class HeartDiseaseController : Controller  
    8.     {  
    9.         [HttpGet]  
    10.         public IActionResult Predict()  
    11.         {  
    12.             return View();  
    13.         }  
    14.         [HttpPost]  
    15.         public IActionResult Predict(HeartData input)  
    16.         {  
    17.             var model = new MLModel();  
    18.             model.Build();  
    19.             var result=model.Consume(input);  
    20.             ViewBag.HeartPrediction = result;  
    21.             return View();  
    22.         }  
    23.     }  
    24. }  
  • Now, we will create a view named Prediction inside HeartDisease folder under Views folder. Paste the following snippet into that.
    1. @model Heart_Disease_Prediction.ML_Model.DataStructures.HeartData  
    2.   
    3. @{  
    4.     ViewData["Title"] = "Heart Disease Prediction";  
    5. }  
    6.   
    7. <h1>Heart Disease Prediction in ASP.NET Core using ML.NET</h1>  
    8. <hr />  
    9. <div class="row">  
    10.     <form asp-action="Predict" class="col-md-8">  
    11.         <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
    12.         <div class="row">  
    13.             <div class="col-md-4">  
    14.                 <div class="row">  
    15.                     <div class="form-group col-md-6">  
    16.                         <label asp-for="Age" class="control-label"></label>  
    17.                         <input asp-for="Age" class="form-control" />  
    18.                         <span asp-validation-for="Age" class="text-danger"></span>  
    19.                     </div>  
    20.                     <div class="form-group col-md-6">  
    21.                         <label asp-for="Sex" class="control-label"></label>  
    22.                         <select asp-for="Sex" class="form-control">  
    23.                             <option value="1">Male</option>  
    24.                             <option value="0">Female</option>  
    25.                         </select>  
    26.                         <span asp-validation-for="Sex" class="text-danger"></span>  
    27.                     </div>  
    28.                 </div>  
    29.                   
    30.                 <div class="form-group">  
    31.                     <label asp-for="Cp" class="control-label"></label>  
    32.                     <select asp-for="Cp" class="form-control" >  
    33.                         <option value="1">typical angina</option>  
    34.                         <option value="2">atypical angina</option>  
    35.                         <option value="3">non-anginal pain</option>  
    36.                         <option value="4">asymptomatic</option>  
    37.                     </select>  
    38.                     <span asp-validation-for="Cp" class="text-danger"></span>  
    39.                 </div>  
    40.                 <div class="form-group">  
    41.                     <label asp-for="TrestBps" class="control-label"></label>  
    42.                     <input asp-for="TrestBps" class="form-control" />  
    43.                     <span asp-validation-for="TrestBps" class="text-danger"></span>  
    44.                 </div>  
    45.                 <div class="form-group">  
    46.                     <label asp-for="Chol" class="control-label"></label>  
    47.                     <input asp-for="Chol" class="form-control" />  
    48.                     <span asp-validation-for="Chol" class="text-danger"></span>  
    49.                 </div>  
    50.                   
    51.   
    52.             </div>  
    53.             <div class="col-md-4">  
    54.                   
    55.                 <div class="form-group">  
    56.                     <label asp-for="Fbs" class="control-label"></label>  
    57.                     <input asp-for="Fbs" class="form-control" />  
    58.                     <span asp-validation-for="Fbs" class="text-danger"></span>  
    59.                 </div>  
    60.                 <div class="form-group">  
    61.                     <label asp-for="RestEcg" class="control-label"></label>  
    62.                     <select asp-for="RestEcg" class="form-control" >  
    63.                         <option value="0">normal</option>  
    64.                         <option value="1">having ST-T wave abnormality</option>  
    65.                         <option value="2">showing probable or definite left ventricular hypertrophy by Estes' criteria</option>  
    66.                     </select>  
    67.                     <span asp-validation-for="RestEcg" class="text-danger"></span>  
    68.                 </div>  
    69.                 <div class="form-group">  
    70.                     <label asp-for="Thalac" class="control-label"></label>  
    71.                     <select asp-for="Thalac" class="form-control" >  
    72.                         <option value="3">normal</option>  
    73.                         <option value="6">fixed defect</option>  
    74.                         <option value="7">reversible defect</option>  
    75.                     </select>  
    76.                     <span asp-validation-for="Thalac" class="text-danger"></span>  
    77.                 </div>  
    78.                 <div class="form-group">  
    79.                     <label asp-for="Exang" class="control-label"></label>  
    80.                     <select asp-for="Exang" class="form-control" >  
    81.                         <option value="1">yes</option>  
    82.                         <option value="0">no</option>  
    83.                     </select>  
    84.                     <span asp-validation-for="Exang" class="text-danger"></span>  
    85.                 </div>  
    86.   
    87.             </div>  
    88.             <div class="col-md-4">  
    89.                   
    90.                 <div class="form-group">  
    91.                     <label asp-for="OldPeak" class="control-label"></label>  
    92.                     <input asp-for="OldPeak" class="form-control" />  
    93.                     <span asp-validation-for="OldPeak" class="text-danger"></span>  
    94.                 </div>  
    95.                 <div class="form-group">  
    96.                     <label asp-for="Slope" class="control-label"></label>  
    97.                     <select asp-for="Slope" class="form-control" >  
    98.                         <option value="1">upsloping</option>  
    99.                         <option value="2">flat</option>  
    100.                         <option value="3">downsloping</option>  
    101.                     </select>  
    102.                     <span asp-validation-for="Slope" class="text-danger"></span>  
    103.                 </div>  
    104.                 <div class="form-group">  
    105.                     <label asp-for="Ca" class="control-label"></label>  
    106.                     <input asp-for="Ca" class="form-control" />  
    107.                     <span asp-validation-for="Ca" class="text-danger"></span>  
    108.                 </div>  
    109.                 <div class="form-group">  
    110.                     <label asp-for="Thal" class="control-label"></label>  
    111.                     <input asp-for="Thal" class="form-control" />  
    112.                     <span asp-validation-for="Thal" class="text-danger"></span>  
    113.                 </div>  
    114.                 <div class="form-group">  
    115.                     <input type="submit" value="Predict" class="btn btn-primary" />  
    116.                 </div>  
    117.             </div>  
    118.         </div>  
    119.     </form>  
    120.     @if (ViewBag.HeartPrediction != null)  
    121.     {  
    122.         <div class="col-md-4">  
    123.             <h4>Prediction: @ViewBag.HeartPrediction.Prediction</h4>  
    124.             <h4>Probability: @ViewBag.HeartPrediction.Probability</h4>  
    125.             <h4>Score: @ViewBag.HeartPrediction.Score</h4>  
    126.         </div>  
    127.     }  
    128. </div>  
    129.   
    130. @section Scripts {  
    131.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
    132. }  
  • Now, all our implementation has been completed so let us try to build the application and run. You will see the following output screen.

    Heart Disease Prediction In ASP.NET Core Using ML.NET

  • Enter your data and click on the Predict button. The Heart Disease Prediction will be shown.

Demo

 
Heart Disease Prediction In ASP.NET Core Using ML.NET
 
Note 
In this article, we learned how to develop an ASP.NET Core MVC Web Application for Heart Disease Prediction and how to train, evaluate, and consume Heart Disease Prediction Machine Learning model in ASP.NET Core application.
 
For more information about dataset attributes description please checkout UCI ML Repository.
 
You can download the demo project from my GitHub repository heart disease prediction.


Similar Articles
Finchship
We Provide Web, Desktop and Mobile Apps Solution