ML.NET (Microsoft.ML) - 02: Linear Regression in ML.NET in C#


Saturday, June 6, 2026    |    2 views

 Linear Regression in C# is a machine learning/statistical technique used to predict a numeric value based on one or more input variables.

 y = mx + b 

predictedSalary = (slope × yearsExperience) + intercept

 Where:

 y = predicted value 

 x = input feature  (yearsExperience)

 m = slope (weight)   (slope)

 b = intercept (bias) (intercept)


using System;

class Program
{
     static void Main()
    {
  // y = mx + b
  double m = 5000; // slope
  double b = 30000; // intercept

  double yearsExperience = 5;

  double predictedSalary
       = (m * yearsExperience) + b;

  Console.WriteLine($"Predicted
                Salary: {predictedSalary}");
    }
}


 using System;

 This line imports the System namespace, which contains basic C# classes like Console. Without it, we couldn’t use Console.WriteLine.


 class Program

 Defines a class named Program (standard in C#).


 static void Main()

 Main is the entry point of the program — where execution starts.


 // y = mx + b
double m = 5000; // slope
double b = 30000; // intercept

 The comment y = mx + b is the linear equation formula:

 y = predicted value (salary)

 x = input (years of experience)

 m = slope (how much y changes for each unit change in x)

 b = intercept (value of y when x = 0)


 double m = 5000;

 m is the slope. Here, it means each extra year of experience increases salary by 5000.

 double b = 30000;

 b is the intercept. Here, it means even with 0 years of experience, salary starts at 30,000.


 double yearsExperience = 5;

 We want to predict the salary for someone with 5 years of experience.

 This is our x value in the equation y = mx + b.


 double predictedSalary = (m * yearsExperience) + b;

 This applies the linear equation:

 y = m ⋅ x + b


 Step by step:

 Multiply slope by input: 5000∗5=25000

 Add intercept: 25000+30000=55000

 So, predictedSalary becomes 55000.


 Console.WriteLine($"Predicted Salary: {predictedSalary}");

 This prints the result to the console.

 $"..." is string interpolation, allowing us to insert variables directly.

 Output:

 Predicted Salary: 55000


For More Details Youtube Video Link : 

https://youtube.com/live/Xz2Y1RJyrsE


Post Comments
748285