如何将计算所得的列添加到IDataView,然后作为功能部件包含

时间:2019-06-15 17:48:48

标签: ml.net

我在一个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中是否有内置方法以添加列,还是我需要手动实现它?

1 个答案:

答案 0 :(得分:0)

我想您可能想使用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}");
}