且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将ML.Net演示演示转换为F#?

更新时间:2023-12-02 16:58:04

您可能会在下面的 ML教程,使用Microsoft .ML 0.1.0(较新的版本可能会中断)。 IrisData IrisPrediction 类型定义都与使示例工作的代码有两个主要区别:

You may find below a working F# version of code for the ML tutorial, using Microsoft.ML 0.1.0 (might break with newer versions). Two major differences from your code that make the sample work are both within IrisData and IrisPredictiontype definitions:


  • 在F#中准确显示C#POCO,具有无参数构造函数和对字段的公共访问权限

  • 正确移植C# float 到F#,即 float32

  • Accurate presentation of C# POCO in F# having parameterless constructor and public access to the fields
  • Correct porting of C# float to F#, which is float32

这里是代码

open Microsoft.ML
open Microsoft.ML.Runtime.Api
open Microsoft.ML.Trainers
open Microsoft.ML.Transforms
open System

type IrisData() =
    [<Column("0")>]
    [<DefaultValue>]
    val mutable public SepalLength: float32
    [<DefaultValue>]
    [<Column("1")>]
    val mutable public SepalWidth: float32
    [<DefaultValue>]
    [<Column("2")>]
    val mutable public PetalLength:float32
    [<DefaultValue>]
    [<Column("3")>]
    val mutable public PetalWidth:float32
    [<DefaultValue>]
    [<Column("4")>]
    [<ColumnName("Label")>]
    val mutable public Label:string

type IrisPrediction() =
    [<ColumnName("PredictedLabel")>]
    [<DefaultValue>]
    val mutable public PredictedLabel : string

[<EntryPoint>]
let main argv =
    let pipeline = new LearningPipeline()
    let dataPath = "iris.data.txt"
    let a = IrisPrediction()
    pipeline.Add(new TextLoader<IrisData>(dataPath,separator = ","))
    pipeline.Add(new Dictionarizer("Label"))
    pipeline.Add(new ColumnConcatenator("Features", "SepalLength", "SepalWidth", "PetalLength", "PetalWidth"))
    pipeline.Add(new StochasticDualCoordinateAscentClassifier())
    pipeline.Add(new PredictedLabelColumnOriginalValueConverter(PredictedLabelColumn = "PredictedLabel") )    
    let model = pipeline.Train<IrisData, IrisPrediction>()

    let x = IrisData()
    x.SepalLength <- 3.3f
    x.SepalWidth <- 1.6f
    x.PetalLength <- 0.2f
    x.PetalWidth <- 5.1f
    let prediction = model.Predict(x)

    printfn "Predicted flower type is: %s"  prediction.PredictedLabel

    0

及其产生的输出:

Automatically adding a MinMax normalization transform, use 'norm=Warn' or 'norm=No' to turn this behavior off.
Using 4 threads to train.
Automatically choosing a check frequency of 4.
Auto-tuning parameters: maxIterations = 9996.
Auto-tuning parameters: L2 = 2.668802E-05.
Auto-tuning parameters: L1Threshold (L1/L2) = 0.
Using best model from iteration 892.
Not training a calibrator because it is not needed.
Predicted flower type is: Iris-virginica
Press any key to continue . . .