gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:15:21 25 4
gpt4 key购买 nike

我正在无监督的集群场景中试验 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-means 聚类的样本。就我而言,我想要 3 个集群。正如我刚刚学习的那样,创建模型后,我想使用它将聚类数据添加到原始文件副本中的每个记录,以便我可以检查它们并绘制散点图。

我从这个训练代码开始(假设MyModel是代表其模型的POCO类,具有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 ,它相当旧,它的代码不再编译。我宁愿用它作为通过反射恢复数据的提示,但这是一个黑客。

此外,我不确定框架提供的数据的详细信息。我可以看到每个质心都有 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 ...
}

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

  • dxdydz 是距离。
  • cx[0] cy[0] cy[0] + 距离 (dx, dydz)应该是S1点的位置; cx[1] cy[1] cz[1] + S2位置的距离;依此类推直至 S5(cx[4] 等)。

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

最佳答案

我自己刚刚弄清楚了这一点 - 进行了一些挖掘,因此对于那些感兴趣的人来说,这里有一些很好的信息:

现在可以通过拟合模型立即检索质心

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

但是文档here令人烦恼地误导,因为他们声称的“坐标”质心不是坐标,而是集群特征列的平均值。

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

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

我最终做的是在根据数据训练模型后,我通过模型的预测函数运行所有数据。这给了我预测的簇 ID 和到所有其他簇质心的欧几里德距离。

使用预测的聚类 ID 和聚类的质心均值,您可以将数据点的特征映射到均值上,以根据预测的聚类获取数据行的“加权值”。基本上,质心将包含它包含某个列 0.6533、另一列 0.211 和另一列 0 的信息。通过运行数据点特征,比如说( 5, 3, 1 ),通过质心,您将得到( 3.2665, 0.633, 0)。这是预测簇中包含的数据行的表示。

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

这样做我们终于可以得到漂亮的图表enter image description here

这是一个大部分完整的代码示例:


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 文档链接以获取示例 - featuresDataset 在其示例中将是 testData

关于c# - ML.NET 绘制 K 均值聚类结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57449860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com