gpt4 book ai didi

java - Weka 决策树 Java 到列表

转载 作者:行者123 更新时间:2023-11-30 08:20:22 24 4
gpt4 key购买 nike

我想制作一个决策树并将其分解为列表(name、sign、val)。我用这段代码做了树:

        //Get File
BufferedReader reader = new BufferedReader(new FileReader(PATH + "TempArffFile.arff"));

//Get the data
Instances data = new Instances(reader);
reader.close();

//Setting class attribute
data.setClassIndex(data.numAttributes() - 1);

//Make tree
J48 tree = new J48();
String[] options = new String[1];
options[0] = "-U";
tree.setOptions(options);
tree.buildClassifier(data);

//Print tree
System.out.println(tree);

现在我需要将它分解为数组,我该怎么做?

例子:我得到这棵树:

title <= 1: bad (4.0)
title > 1
| positionMatch <= 1
| | countryCode <= 1: good (3.0/1.0)
| | countryCode > 1: bad (8.0/3.0)
| positionMatch > 1: good (4.0/1.0)

所以我想从那棵树中得到 4 个列表:

  • title(<= 1) -> bad
  • title(> 1) -> position(<= 1) -> countryCode(<= 1) -> good
  • title(> 1) -> position(<= 1) -> countryCode(> 1) -> bad
  • title(> 1) -> position(> 1) -> good

我该怎么做?

最佳答案

不是很好,但也许比什么都没有好...也许它会给你一个想法。

    public static void split(String tree){

String[] lines = tree.split("\n");
List<List<String>> lists = new ArrayList<List<String>>();
for(String line : lines){
List<String> temp = new ArrayList<String>();
while(line.indexOf("|") != -1){
temp.add("|");
line = line.replaceFirst("\\|", "");
}
temp.add(line.trim());
lists.add(temp);
}

for(int i = 0; i < 3; i++){
lists.remove(0);
}
for(int i = 0; i < 4; i++){
lists.remove(lists.size()-1);
}
List<String> substitutes = new ArrayList<String>();

for(List<String> list : lists){
for(int i = 0; i < list.size(); i++){
if(!list.get(i).contains(":") && !list.get(i).equals("|") && !substitutes.contains(list.get(i))){
substitutes.add(list.get(i));
}
}
}
for(List<String> list : lists){
for(int i = 0; i < list.size(); i++){
if(list.get(i).equals("|")){
list.set(i, substitutes.get(i));
}
}
}
StringBuilder sb = new StringBuilder();
for(List<String> list : lists){
String line = "";
for(String s : list){
line = line+" "+s;
}
if(line.endsWith(")")){
sb.append(line+"\n");
}
}
System.out.println(sb.toString());
}

输入

J48 未修剪树

花瓣宽度 <= 0.6:鸢尾花 (50.0)

花瓣宽度 > 0.6

|花瓣宽度 <= 1.7

| | petallength <= 4.9: Iris-versicolor (48.0/1.0)

| |花瓣长度 > 4.9

| | |花瓣宽度 <= 1.5:Iris-virginica (3.0)

| | | petalwidth > 1.5: Iris-versicolor (3.0/1.0)

| petalwidth > 1.7: Iris-virginica (46.0/1.0)

叶子数:5

树的大小:9

输出:

花瓣宽度 <= 0.6:鸢尾花 (50.0)

petalwidth > 0.6 petalwidth <= 1.7 petallength <= 4.9: Iris-versicolor (48.0/1.0)

petalwidth > 0.6 petalwidth <= 1.7 petallength > 4.9 petalwidth <= 1.5: Iris-virginica (3.0)

petalwidth > 0.6 petalwidth <= 1.7 petallength > 4.9 petalwidth > 1.5: Iris-versicolor (3.0/1.0)

花瓣宽度 > 0.6 花瓣宽度 > 1.7:Iris-virginica (46.0/1.0)

关于java - Weka 决策树 Java 到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26123480/

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