ML.NET 绘制 K 均值聚类结果?

ML.NET plotting K-means clustering results?

我正在无监督集群场景中试验 ML.NET。我的起始数据少于 30 条记录,TSV 文件中有 5 个特征,例如(当然标签会被忽略):

Label   S1   S2   S3   S4   S5
alpha   0.274167987321712   0.483359746434231   0.0855784469096672   0.297939778129952   0.0332805071315372
beta   0.378208470054279   0.405409549510871   0.162317151706584   0.292342604802355   0.0551994848048085
...

我的起点是 iris tutorial,一个 K 均值聚类的样本。在我的例子中,我想要 3 个集群。正如我刚刚学习的那样,一旦创建了模型,我想用它来将聚类数据添加到原始文件副本中的每条记录,这样我就可以检查它们并绘制散点图。

我从这个训练代码开始(比如 MyModel 是代表其模型的 POCO class,具有 S1-S5 的属性):

// load data
MLContext mlContext = new MLContext(seed: 0);
IDataView dataView = mlContext.Data.LoadFromTextFile<MyModel>
    (dataPath, hasHeader: true, separatorChar: '\t');

// train model
const string featuresColumnName = "Features";
EstimatorChain<ClusteringPredictionTransformer<KMeansModelParameters>>
    pipeline = mlContext.Transforms
    .Concatenate(featuresColumnName, "S1", "S2", "S3", "S4", "S5")
    .Append(mlContext.Clustering.Trainers.KMeans(featuresColumnName,
    numberOfClusters: 3));

TransformerChain<ClusteringPredictionTransformer<KMeansModelParameters>>
    model = pipeline.Fit(dataView);

// save model
using (FileStream fileStream = new FileStream(modelPath,
    FileMode.Create, FileAccess.Write, FileShare.Write))
{
    mlContext.Model.Save(model, dataView.Schema, fileStream);
}

然后,我加载保存的模型,从原始数据中读取每条记录,并获取其集群 ID。这听起来有点令人费解,但我的学习目的是在玩之前检查结果。结果应与质心坐标和点坐标一起保存在新文件中。

然而,这个 API 似乎不够透明,无法轻松访问质心;我只找到了一个post,它比较旧,而且它的代码不再编译。我宁愿用它作为通过反射恢复数据的提示,但这是一个 hack。

此外,我不确定框架提供的数据的细节。我可以看到每个质心都有 3 个向量(在示例代码中命名为 cx cy cz),每个向量有 5 个元素(我认为这 5 个特征按它们的串联输入顺序排列,即从 S1 到 S5);此外,每个预测提供 3 倍距离 (dx dy dz)。如果这些假设没问题,我可以像这样为每条记录分配一个簇 ID:

// for each record in the original data
foreach (MyModel record in csvReader.GetRecords<MyModel>())
{
    // get its cluster ID
    MyPrediction prediction = predictor.Predict(record);

    // get the centroids just once, as of course they are the same
    // for all the records referring their distances to them
    if (cx == null)
    {
        // get centroids (via reflection...):
        // https://github.com/dotnet/machinelearning/blob/master/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Clustering/KMeansWithOptions.cs#L49
        // https://social.msdn.microsoft.com/Forums/azure/en-US/c09171c0-d9c8-4426-83a9-36ed72a32fe7/kmeans-output-centroids-and-cluster-size?forum=MachineLearning
        VBuffer<float>[] centroids = default;
        var last = ((TransformerChain<ITransformer>)model)
            .LastTransformer;
        KMeansModelParameters kparams = (KMeansModelParameters)
            last.GetType().GetProperty("Model").GetValue(last);
        kparams.GetClusterCentroids(ref centroids, out int k);
        cx = centroids[0].GetValues().ToArray();
        cy = centroids[1].GetValues().ToArray();
        cz = centroids[2].GetValues().ToArray();
    }

    float dx = prediction.Distances[0];
    float dy = prediction.Distances[1];
    float dz = prediction.Distances[2];
    // ... calculate and save full details for the record ...
}

鉴于这种情况,我想我可以通过以下方式获取有关预训练模型中每个记录位置的所有详细信息:

在这种情况下,我可以将这些数据绘制成 3D 散点图。然而,我对 ML.NET 完全陌生,因此我不确定这些假设,而且很可能我走错了路。谁能指出我正确的方向?

我只是自己弄明白了 - 进行了一些挖掘,所以对于那些感兴趣的人来说,这里有一些有用的信息:

现在可以通过

从拟合模型中检索质心
VBuffer<float>[] centroids = default;
var modelParams = trainedModel.Model;
modelParams.GetClusterCentroids(ref centroids, out var k);

然而,文档 here 具有令人讨厌的误导性,因为他们声称的质心 "coordinates" 不是坐标,而是集群特征列的平均值。

根据您的管道,如果像我一样您有 700 个特征列和六个 t运行 形成步骤,这可能会使它们变得毫无用处。据我所知(如果我错了,请纠正我!)没有办法将质心转换成笛卡尔坐标来绘制图表。

但我们仍然可以使用它们。

我最终做的是在我的数据上训练我的模型后,我 运行 通过模型的预测功能我所有的数据。这给了我到所有其他集群质心的预测集群 ID 和欧几里得距离。

使用预测的集群 ID 和集群的质心均值,您可以将数据点的特征映射到均值上,以根据预测的集群获得数据行的 "weighted value"。基本上,一个质心将包含它包含特定列 0.6533、另一列 0.211 和另一列 0 的信息。通过 运行 你的数据点特征,让我们说 ( 5, 3, 1 ),通过质心你会得到 ( 3.2665, 0.633, 0 )。这是包含在预测集群中的数据行的表示。

然而,这仍然只是一行数据 - 为了将它们转换为点图的笛卡尔坐标,我只是将前半部分的总和用作 X,将后半部分的总和用作 Y。对于示例数据坐标为 ( 3.8995, 0 )

这样做我们终于可以得到漂亮的图表了

这是一个基本完整的代码示例:


VBuffer<float>[] centroids = default;
var modelParams = trainedModel.Model;
modelParams.GetClusterCentroids(ref centroids, out var k);

// extract from the VBuffer for ease
var cleanCentroids = Enumerable.Range(1, 5).ToDictionary(x => (uint)x, x =>
{
    var values = centroids[x - 1].GetValues().ToArray();
    return values;
});



var points = new Dictionary<uint, List<(double X, double Y)>>();
foreach (var dp in featuresDataset)
{
    var prediction = predictor.Predict(dp);

    var weightedCentroid = cleanCentroids[prediction.PredictedClusterId].Zip(dp.Features, (x, y) => x * y);
    var point = (X: weightedCentroid.Take(weightedCentroid.Count() / 2).Sum(), Y: weightedCentroid.Skip(weightedCentroid.Count() / 2).Sum());

     if (!points.ContainsKey(prediction.PredictedClusterId))
         points[prediction.PredictedClusterId] = new List<(double X, double Y)>();
     points[prediction.PredictedClusterId].Add(point);


}

其中 featuresDataset 是一个对象数组,其中包含提供给 kmeans 训练器的特征列。有关示例,请参见上面的 Microsoft 文档 link - featuresDataset 在他们的示例中将是 testData