如何将Weka Instances类属性值水平存储以统计分类标签出现次数
问题根因
你当前代码每次遍历单条样本时,都会在texted()方法内创建新的HashMap,仅统计当前单条样本的类标签,自然每个标签统计结果都是1。
修正实现
这里给两种可行方案:
方案1:按需求先拼接所有标签再统计
先把所有类标签拼接成一个空格分隔的长字符串,再调用你原有的词频统计逻辑,代码修改如下:
public class testDistributionClass { public static Instances loadData(String location) { try { return DataSource.read(location); } catch (Exception e) { System.err.println("Failed to load data from: " + location); e.printStackTrace(); return null; } } HashMap<String, Integer> texted(String tex) { HashMap<String, Integer> counts = new HashMap<String, Integer>(); for (String word : tex.split(" ")) { if (!counts.containsKey(word)) counts.put(word, 0); counts.put(word, counts.get(word) + 1); } counts.forEach((string, integer) -> System.out.printf("amount of \"%s\": %d\n", string, integer)); return counts; } public static void main(String[] args) throws Exception { String test1 = "D:/Week 1/Arsenal_test.arff"; Instances test = testDistributionClass.loadData(test1); test.setClassIndex(test.numAttributes()-1); Classifier testModel = (Classifier)new NaiveBayes(); testModel.buildClassifier(test); testDistributionClass splitWords = new testDistributionClass(); // 新增:拼接所有类标签的StringBuilder StringBuilder allLabels = new StringBuilder(); for(int i = 0; i<test.numInstances();i++) { String trueClassLabel = test.instance(i).toString(test.classIndex()); // 拼接标签,末尾加空格分隔 allLabels.append(trueClassLabel).append(" "); } // 循环结束后统一统计 System.out.println(splitWords.texted(allLabels.toString())); } }
方案2:更高效的直接统计(无需拼接字符串)
省略字符串拼接、切割步骤,直接用全局HashMap统计标签出现次数,性能更好:
public class testDistributionClass { public static Instances loadData(String location) { try { return DataSource.read(location); } catch (Exception e) { System.err.println("Failed to load data from: " + location); e.printStackTrace(); return null; } } public static void main(String[] args) throws Exception { String test1 = "D:/Week 1/Arsenal_test.arff"; Instances test = testDistributionClass.loadData(test1); test.setClassIndex(test.numAttributes()-1); Classifier testModel = (Classifier)new NaiveBayes(); testModel.buildClassifier(test); HashMap<String, Integer> labelCounts = new HashMap<>(); for(int i = 0; i<test.numInstances();i++) { String trueClassLabel = test.instance(i).toString(test.classIndex()); // 直接统计 labelCounts.put(trueClassLabel, labelCounts.getOrDefault(trueClassLabel, 0)+1); } // 输出结果 labelCounts.forEach((label, count) -> System.out.printf("amount of \"%s\": %d\n", label, count)); System.out.println(labelCounts); } }
两种方案都可以得到你需要的聚合统计结果,比如输出{Win=7, Loss=5, Draw=2}这类聚合值。
内容的提问来源于stack exchange,提问作者Stackbeans
相关产品推荐
相关产品推荐

