HomeContact

.NET 7 and Machine Learning with ML.NET Unleashing the Power of AI in Your Applications

By Shady Nagy
Published in dotnet
April 21, 2023
2 min read
.NET 7 and Machine Learning with ML.NET Unleashing the Power of AI in Your Applications

Table Of Contents

01
Introduction
02
Introduction to ML.NET
03
Example: Predicting House Prices with ML.NET
04
Further Reading
05
Conclusion:
06
Feedback and Questions

Introduction

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.

Introduction to ML.NET

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.

  • Ease of use: ML.NET provides a simple API that abstracts complex machine learning concepts, making it easy for .NET developers to get started with ML.
  • Built for .NET: ML.NET is designed specifically for .NET developers, integrating seamlessly with familiar .NET tools, libraries, and frameworks.
  • Custom models: Build custom machine learning models tailored to your specific application requirements, without relying on pre-built models or cloud-based services.
  • Cross-platform: ML.NET runs on Windows, Linux, and macOS, enabling you to develop and deploy ML models across various platforms.

Example: Predicting House Prices with ML.NET

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:

  • .NET 7 SDK installed
  • Visual Studio 2022 or Visual Studio Code with C# extension

Step 1: Creating a New .NET 7 Console Application Create a new .NET 7 console application using the following command:

dotnet new console -n HousePricePredictor
cd HousePricePredictor

Step 2: Installing ML.NET NuGet Packages Install the necessary ML.NET NuGet packages using the following commands:

dotnet add package Microsoft.ML
dotnet 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,Price
1500,3,Uptown,300000
1800,4,Downtown,400000
2100,4,Uptown,550000
2400,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 MLContext
var context = new MLContext();
// Read the data from the CSV file
var data = context.Data.LoadFromTextFile<HouseData>("houseData.csv", separatorChar: ',');
// Split the data into training and testing sets
var tt = context.Data.TrainTestSplit(data);
// Define the pipeline
var 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 model
var model = pipeline.Fit(tt.TrainSet);
// Evaluate the model
var 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 model
context.Model.Save(model, tt.TrainSet.Schema, "HousePriceModel.zip");
// Load the model and make predictions
var 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.##}");
}
}
}

Further Reading

For more in-depth information about ML.NET and machine learning with .NET 7, consider exploring the following resources:

  1. ML.NET Documentation Dive into the official documentation to learn more about ML.NET, its features, and how to use it in your applications.

  2. Getting Started with ML.NET Follow step-by-step guides and tutorials to get started with machine learning using ML.NET.

  3. .NET 7 Release Notes Explore the new features and improvements introduced in .NET 7, including enhancements related to machine learning.

Conclusion:

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.

Feedback and Questions

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:

  1. Email: shady@shadynagy.com
  2. Twitter: @ShadyNagy_
  3. LinkedIn: Shady Nagy
  4. GitHub: ShadyNagy

Tags

#.NET7#MachineLearning#MLNET#PredictiveModeling#CSharp#DataScience#CrossPlatform#VisualStudio2022#AIApplications#Microsoft

Share


Previous Article
.NET 7 Exciting New Features and Improvements for Modern Web Development
Shady Nagy

Shady Nagy

Software Innovation Architect

Topics

AI
Angular
dotnet
GatsbyJS
Github
Linux
MS SQL
Oracle

Related Posts

Getting Started with NDepend A Comprehensive Guide to Boosting Code Quality
Getting Started with NDepend A Comprehensive Guide to Boosting Code Quality
July 03, 2024
4 min

Quick Links

Contact Us

Social Media