【发布时间】:2017-01-31 23:55:44
【问题描述】:
我有一个程序可以训练具有 2 类分类结果的算法,然后针对未标记的数据集运行并写出预测(2 类中的每一个的概率)。
针对该程序运行的所有数据集都将具有与结果相同的 2 个类。考虑到这一点,我运行了预测并使用了一些事后统计数据来确定哪一列结果描述了哪个结果,然后对它们进行硬编码:
public class runPredictions {
public static void runPredictions(ArrayList al2) throws IOException, Exception{
// Retrieve objects
Instances newTest = (Instances) al2.get(0);
Classifier clf = (Classifier) al2.get(1);
// Print status
System.out.println("Generating predictions...");
// create copy
Instances labeled = new Instances(newTest);
BufferedWriter outFile = new BufferedWriter(new FileWriter("silverbullet_rro_output.csv"));
StringBuilder builder = new StringBuilder();
builder.append("Prob_Retain"+","+"Prob_Attrite"+"\n");
for (int i = 0; i < labeled.size(); i++)
{
double[] clsLabel = clf.distributionForInstance(newTest.instance(i));
for(int j=0;j<2;j++){
builder.append(clsLabel[j]+"");
if(j < clsLabel.length - 1)
builder.append(",");
}
builder.append("\n");
}
outFile.write(builder.toString());//save the string representation
System.out.println("Output file written.");
System.out.println("Completed successfully!");
outFile.close();
}
}
问题在于,2 列中的哪一列描述了 2 个结果类别中的哪一个是不固定的。这似乎与哪个类别首先出现在训练数据集中有关,这完全是任意的。所以当这个程序使用其他数据集时,硬编码的标签是向后的。
所以,我需要一种更好的方法来标记它们,但是查看 Classifier 和 distributionForInstance 的文档并没有发现任何有用的信息。
更新:
我想出了如何将它打印到屏幕上(感谢this),但仍然无法将其写入 csv:
for (int i = 0; i < labeled.size(); i++)
{
// Discreet prediction
double predictionIndex =
clf.classifyInstance(newTest.instance(i));
// Get the predicted class label from the predictionIndex.
String predictedClassLabel =
newTest.classAttribute().value((int) predictionIndex);
// Get the prediction probability distribution.
double[] predictionDistribution =
clf.distributionForInstance(newTest.instance(i));
// Print out the true predicted label, and the distribution
System.out.printf("%5d: predicted=%-10s, distribution=",
i, predictedClassLabel);
// Loop over all the prediction labels in the distribution.
for (int predictionDistributionIndex = 0;
predictionDistributionIndex < predictionDistribution.length;
predictionDistributionIndex++)
{
// Get this distribution index's class label.
String predictionDistributionIndexAsClassLabel =
newTest.classAttribute().value(
predictionDistributionIndex);
// Get the probability.
double predictionProbability =
predictionDistribution[predictionDistributionIndex];
System.out.printf("[%10s : %6.3f]",
predictionDistributionIndexAsClassLabel,
predictionProbability );
// Attempt to write to CSV
builder.append(i+","+predictedClassLabel+","+
predictionDistributionIndexAsClassLabel+","+predictionProbability);
//.charAt(0)+','+predictionProbability.charAt(0));
}
System.out.printf("\n");
builder.append("\n");
【问题讨论】: