
Machine learning (ML) is becoming increasingly important in modern software development, enabling applications to learn from data and make intelligent decisions. With ML.NET, .NET developers can harness the power of machine learning within their applications without needing expertise in Python or other ML frameworks. In this blog post, we will explore ML.NET and demonstrate how to build machine learning models using .NET 7 by walking through an example step by step.
ML.NET is an open-source, cross-platform machine learning framework developed by Microsoft. It allows .NET developers to build custom machine learning models using C# or F# without requiring expertise in ML.
In this example, we will demonstrate how to build a machine learning model using ML.NET to predict house prices based on various features such as square footage, number of bedrooms, and location.
Prerequisites:
Step 1: Creating a New .NET 7 Console Application Create a new .NET 7 console application using the following command:
dotnet new console -n HousePricePredictorcd HousePricePredictor
Step 2: Installing ML.NET NuGet Packages Install the necessary ML.NET NuGet packages using the following commands:
dotnet add package Microsoft.MLdotnet add package Microsoft.ML.AutoML
Step 3: Adding Data Model Classes
Create a new file called HouseData.cs and add the following code to define the input and output data models:
using Microsoft.ML.Data;public class HouseData{[LoadColumn(0)] public float SquareFeet;[LoadColumn(1)] public float NumberOfBedrooms;[LoadColumn(2)] public string Location;[LoadColumn(3)] public float Price;}public class HousePricePrediction{[ColumnName("Score")]public float Price;}
Step 4: Preparing and Loading Data
Create a sample CSV data file named houseData.csv with the following content:
SquareFeet,NumberOfBedrooms,Location,Price1500,3,Uptown,3000001800,4,Downtown,4000002100,4,Uptown,5500002400,5,Downtown,600000
Step 5: Building and Training the Model
Update the Program.cs file with the following code to build and train the model:
using System;using System.Linq;using Microsoft.ML;using Microsoft.ML.AutoML;namespace HousePricePredictor{class Program{static void Main(string[] args){// Initialize MLContextvar context = new MLContext();// Read the data from the CSV filevar data = context.Data.LoadFromTextFile<HouseData>("houseData.csv", separatorChar: ',');// Split the data into training and testing setsvar tt = context.Data.TrainTestSplit(data);// Define the pipelinevar pipeline = context.Transforms.Categorical.OneHotEncoding("LocationEncoded", "Location").Append(context.Transforms.Concatenate("Features", "SquareFeet", "NumberOfBedrooms", "LocationEncoded")).Append(context.Transforms.NormalizeMinMax("Features")).Append(context.Transforms.CopyColumns("Label", "Price")).Append(context.Transforms.Regression.Trainers.SdcaNonCalibrated()).Append(context.Transforms.CopyColumns("Score", "Label")).AppendCacheCheckpoint(context);// Train the modelvar model = pipeline.Fit(tt.TrainSet);// Evaluate the modelvar predictions = model.Transform(tt.TestSet);var metrics = context.Regression.Evaluate(predictions);Console.WriteLine($"R-squared: {metrics.RSquared:0.##}");Console.WriteLine($"Mean Absolute Error: {metrics.MeanAbsoluteError:0.##}");Console.WriteLine($"Mean Squared Error: {metrics.MeanSquaredError:0.##}");Console.WriteLine($"Root Mean Squared Error: {metrics.RootMeanSquaredError:0.##}");// Save the modelcontext.Model.Save(model, tt.TrainSet.Schema, "HousePriceModel.zip");// Load the model and make predictionsvar loadedModel = context.Model.Load("HousePriceModel.zip", out var modelSchema);var predictionEngine = context.Model.CreatePredictionEngine<HouseData, HousePricePrediction>(loadedModel);var newHouse = new HouseData { SquareFeet = 2000, NumberOfBedrooms = 3, Location = "Uptown" };var predictedPrice = predictionEngine.Predict(newHouse);Console.WriteLine($"Predicted price for the new house: {predictedPrice.Price:0.##}");}}}
For more in-depth information about ML.NET and machine learning with .NET 7, consider exploring the following resources:
ML.NET Documentation Dive into the official documentation to learn more about ML.NET, its features, and how to use it in your applications.
Getting Started with ML.NET Follow step-by-step guides and tutorials to get started with machine learning using ML.NET.
.NET 7 Release Notes Explore the new features and improvements introduced in .NET 7, including enhancements related to machine learning.
ML.NET offers a powerful and accessible way for .NET developers to harness the power of machine learning in their applications. In this example, we demonstrated how to build, train, and evaluate a machine learning model using ML.NET and .NET 7. This example can be a starting point for further exploration and experimentation with ML.NET, allowing you to build more advanced and complex models for various applications.
We’d love to hear your feedback on this tutorial! If you have any questions or suggestions for improvement, please don’t hesitate to reach out. You can leave a comment below, or you can contact us through the following channels:
Quick Links
Legal Stuff



