【发布时间】:2015-05-30 01:11:38
【问题描述】:
我正在尝试将迭代函数转换为递归。 但是一旦我尝试这样做,它就会像无限循环一样连续运行。
这是我的迭代代码
private static Node buildModelTree(String[] args) {
// TODO Auto-generated method stub
String clsIndex = args[3];
splitted.add(currentsplit);
double entropy = 0;
int total_attributes = (Integer.parseInt(clsIndex));// class index
int split_size = splitted.size();
GainRatio gainObj = new GainRatio();
while (split_size > current_index) { //iterate through all distinct pair for building children
currentsplit = (SplitInfo) splitted.get(current_index);
System.out.println("After currentsplit --->" + currentsplit);
gainObj = new GainRatio();
int res = 0;
res = ToolRunner.run(new Configuration(),new CopyOfFunID3Driver(), args);
gainObj.getcount(current_index);
entropy = gainObj.currNodeEntophy();
clsIndex = gainObj.majorityLabel();
currentsplit.classIndex = clsIndex;
if (entropy != 0.0 && currentsplit.attr_index.size() != total_attributes) { //calculate gain ration
bestGain(total_attributes,entropy,gainObj);
} else {
//When entropy is zero build tree
Node branch = new Node();
String rule = "";
Gson gson = new Gson();
int temp_size = currentsplit.attr_index.size();
for (int val = 0; val < temp_size; val++) {
int g = 0;
g = (Integer) currentsplit.attr_index.get(val);
if (val == 0) {
rule = g + " " + currentsplit.attr_value.get(val);
//JSON
// branch.add(g, currentsplit.attr_value.get(val).toString(), new Node(currentsplit.classIndex, true));
} else {
rule = rule + " " + g + " "+ currentsplit.attr_value.get(val);
//branch.add(g, currentsplit.attr_value.get(val).toString(), buildModelTree(args));
}
}
rule = rule + " " + currentsplit.classIndex;
}
split_size = splitted.size();
current_index++;
}
}
我应该在哪里进行更改? 我正在尝试构建树。所以为了得到树结构,我试图让我的 id3 代码递归。 使用我当前的代码,我只得到输出为this,但我希望它为tree structure
请提出建议。
【问题讨论】:
-
once I tried to do that it is runnning continuously like an infinite loop,你试过什么? -
我已经在该代码中发表了评论。(branch.add(g, currentsplit.attr_value.get(val).toString(), buildModelTree(args));)
-
我的建议是“无处”进行更改。如果这是为了课堂作业,或者你想自己学习递归是如何工作的,好的。但在现实生活中,将迭代代码转换为递归代码几乎没有任何好处。