dotnet / dotnet/samples

An executing problem about the ML_NET Code At [samples/machine-learning/tutorials /TaxiFarePrediction/]

Open
#6,974 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
3.7k
Forks
5.1k
Avg merge
9h 11m
Merged PRs (30d)
1

Description

### System information
- OS version/distro: Windows 10
- .NET Version (eg., dotnet --info): .NET8.0

### STEP1
I created project [ **TaxiFarePrediction.Console** ] with net8.0 ;
it has codefile **GlobalUsings.cs**
```c#
global using Microsoft.ML;
global using Microsoft.ML.Data;
```
created code file **Program.cs**
```C#
TaxiFarePrediction.CreateAndRunPrediction.Execute();
```

### STEP2
Then I created a shared project [ **TaxiFarePrediction.Shared** ]
created code file **CreateAndRunPrediction.cs** which is almostly same as the codefile : https://github.com/dotnet/samples/tree/main/machine-learning/tutorials/TaxiFarePrediction/Program.cs

**CreateAndRunPrediction.cs** :
```c#
namespace TaxiFarePrediction
{
public class CreateAndRunPrediction
{
//
static readonly string _trainDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "taxi-fare-train.csv");
static readonly string _testDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "taxi-fare-test.csv");
static readonly string _modelPath = Path.Combine(Environment.CurrentDirectory, "Data", "Model.zip");
//

public static void Execute( )
{
Console.WriteLine(Environment.CurrentDirectory);

//
MLContext mlContext = new MLContext(seed: 0);
//

//
var model = Train(mlContext, _trainDataPath);
//

//
Evaluate(mlContext, model);
//

//
TestSinglePrediction(mlContext, model);
//
}

public static ITransformer Train(MLContext mlContext, string dataPath)
{
//
IDataView dataView = mlContext.Data.LoadFromTextFile(dataPath, hasHeader: true, separatorChar: ',');
//

//
var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: "FareAmount")
//
//
.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "VendorIdEncoded", inputColumnName: "VendorId"))
.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "RateCodeEncoded", inputColumnName: "RateCode"))
.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "PaymentTypeEncoded", inputColumnName: "PaymentType"))
//
//
.Append(mlContext.Transforms.Concatenate("Features", "VendorIdEncoded", "RateCodeEncoded", "PassengerCount", "TripDistance", "PaymentTypeEncoded"))
//
//
.Append(mlContext.Regression.Trainers.FastTree());
//

Console.WriteLine("=============== Create and Train the Model ===============");

//
var model = pipeline.Fit(dataView);
//

Console.WriteLine("=============== End of training ===============");
Console.WriteLine();
//
return model;
//
}

private static void Evaluate(MLContext mlContext, ITransformer model)
{
//
IDataView dataView = mlContext.Data.LoadFromTextFile(_testDataPath, hasHeader: true, separatorChar: ',');
//

//
var predictions = model.Transform(dataView);
//
//
var metrics = mlContext.Regression.Evaluate(predictions, "Label", "Score");
//

Console.WriteLine();
Console.WriteLine($"*************************************************");
Console.WriteLine($"* Model quality metrics evaluation ");
Console.WriteLine($"*------------------------------------------------");
//
Console.WriteLine($"* RSquared Score: {metrics.RSquared:0.##}");
//
//
Console.WriteLine($"* Root Mean Squared Error: {metrics.RootMeanSquaredError:#.##}");
//
Console.WriteLine($"*************************************************");
}

private static void TestSinglePrediction(MLContext mlContext, ITransformer model)
{
//Prediction test
// Create prediction function and make prediction.
//
var predictionFunction = mlContext.Model.CreatePredictionEngine(model);
//
//Sample:
//vendor_id,rate_code,passenger_count,trip_time_in_secs,trip_distance,payment_type,fare_amount
//VTS,1,1,1140,3.75,CRD,15.5
//
var taxiTripSample = new TaxiTrip()
{
VendorId = "VTS",
RateCode = "1",
PassengerCount = 1,
TripTime = 1140,
TripDistance = 3.75f,
PaymentType = "CRD",
FareAmount = 0 // To predict. Actual/Observed = 15.5
};
//
//
var prediction = predictionFunction.Predict(taxiTripSample);
//
//
Console.WriteLine($"**********************************************************************");
Console.WriteLine($"Predicted fare: {prediction.FareAmount:0.####}, actual fare: 15.5");
Console.WriteLine($"**********************************************************************");
//
}
}
}
```
TaxiTrip.cs
```c#
namespace TaxiFarePrediction;
public class TaxiTrip
{
[LoadColumn(0)]
public string VendorId;

[LoadColumn(1)]
public string RateCode;

[LoadColumn(2)]
public float PassengerCount;

[LoadColumn(3)]
public float TripTime;

[LoadColumn(4)]
public float TripDistance;

[LoadColumn(5)]
public string PaymentType;

[LoadColumn(6)]
public float FareAmount;
}

public class TaxiTripFarePrediction
{
[ColumnName("Score")]
public float FareAmount;
}
```
### STEP3
project **TaxiFarePrediction.Console** reference the project **TaxiFarePrediction.Shared**

### STEP4 error happen
When I built and executed the project **TaxiFarePrediction.Console** , a problem happend at the code :
> var predictionFunction = mlContext.Model.CreatePredictionEngine(model);

AND the error infomation shows:

```
System.Reflection.TargetInvocationException:“Exception has been thrown by the target of an invocation.”

PlatformNotSupportedException: Dynamic code generation is not supported on this platform.

System.Reflection.Emit.AssemblyBuilder.ThrowDynamicCodeNotSupported()
System.Reflection.Emit.AssemblyBuilder.EnsureDynamicCodeSupported()
System.Reflection.Emit.DynamicMethod.Init(string, System.Reflection.MethodAttributes, System.Reflection.CallingConventions, System.Type, System.Type[], System.Type, System.Reflection.Module, bool, bool)
System.Reflection.Emit.DynamicMethod.DynamicMethod(string, System.Type, System.Type[], System.Type, bool)
Microsoft.ML.ApiUtils.GeneratePeek(System.Reflection.FieldInfo, System.Reflection.Emit.OpCode)
System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(object, System.Span, System.Reflection.BindingFlags)

```

otherwise, if I put all code files into the project **TaxiFarePrediction.Console** , the code would be smooth ;
SO, what's the problem about PlatformNotSupportedException , maybe my project structrue would cause some problem ?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.