如何将计算列添加到 IDataView,然后作为功能包括在内

How to add calculated column into IDataView, and then included as a feature

我在 csv 文件中有一些数据:

Survived    Pclass  Sex Age
0           3   male    22
1           1   female  38
1           3   male    26
1           1   female  35
...

我使用以下方法加载数据:

context.Data.LoadFromTextFile(path: dataPath,...);

加载数据后,我需要添加计算列 AgeName,以便:

if (Age < 18)
    AgeName ="Child"
else if(Age < 55)
    AgeNAme = "Man"
else
    AgeNAme = "Grandpa"

ML.NET 中是否有内置方法来添加列,还是我需要手动实现?

我想您会想要使用 CustomMapping 转换。

下面是一个示例。首先,一些输入和输出 类:

class InputData
{
    public int Age { get; set; }
}

class CustomMappingOutput
{
    public string AgeName { get; set; }
}

class TransformedData
{
    public int Age { get; set; }

    public string AgeName { get; set; }
}

然后,在ML.NET程序中:

MLContext mlContext = new MLContext();

var samples = new List<InputData>
{
    new InputData { Age = 16 },
    new InputData { Age = 35 },
    new InputData { Age = 60 },
    new InputData { Age = 28 },
};

var data = mlContext.Data.LoadFromEnumerable(samples);

Action<InputData, CustomMappingOutput> mapping =
    (input, output) =>
    {
        if (input.Age < 18)
        {
            output.AgeName = "Child";
        }
        else if (input.Age < 55)
        {
            output.AgeName = "Man";
        }
        else
        {
            output.AgeName = "Grandpa";
        }
    };

var pipeline = mlContext.Transforms.CustomMapping(mapping, contractName: null);

var transformer = pipeline.Fit(data);
var transformedData = transformer.Transform(data);

var dataEnumerable = mlContext.Data.CreateEnumerable<TransformedData>(transformedData, reuseRowObject: true);

foreach (var row in dataEnumerable)
{
    Console.WriteLine($"{row.Age}\t {row.AgeName}");
}