java 随机森林算法代码
时间: 2023-09-19 22:12:22 浏览: 50
下面是一个简单的Java随机森林算法的实现代码示例:
```
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class RandomForest {
private List<DecisionTree> forest;
private int numTrees;
private int maxDepth;
private int minLeafSize;
private int numFeatures;
public RandomForest(int numTrees, int maxDepth, int minLeafSize, int numFeatures) {
this.numTrees = numTrees;
this.maxDepth = maxDepth;
this.minLeafSize = minLeafSize;
this.numFeatures = numFeatures;
this.forest = new ArrayList<DecisionTree>();
}
public void train(List<DataPoint> data) {
int numDataPoints = data.size();
for (int i = 0; i < numTrees; i++) {
// Randomly select a subset of features
List<Integer> featureIndices = new ArrayList<Integer>();
for (int j = 0; j < numFeatures; j++) {
featureIndices.add(j);
}
Collections.shuffle(featureIndices);
featureIndices = featureIndices.subList(0, numFeatures);
// Randomly select a subset of data points
List<DataPoint> subset = new ArrayList<DataPoint>();
for (int j = 0; j < numDataPoints; j++) {
int index = new Random().nextInt(numDataPoints);
subset.add(data.get(index));
}
// Build a decision tree using the selected features and data points
DecisionTree tree = new DecisionTree(maxDepth, minLeafSize, featureIndices);
tree.train(subset);
forest.add(tree);
}
}
public int predict(DataPoint data) {
int numTrees = forest.size();
int[] predictions = new int[numTrees];
for (int i = 0; i < numTrees; i++) {
predictions[i] = forest.get(i).predict(data);
}
// Return the mode of the predictions
int mode = predictions[0];
int maxCount = 0;
for (int i = 0; i < numTrees; i++) {
int count = 0;
for (int j = 0; j < numTrees; j++) {
if (predictions[j] == predictions[i]) {
count++;
}
}
if (count > maxCount) {
mode = predictions[i];
maxCount = count;
}
}
return mode;
}
}
```
请注意,上述代码中的 `DataPoint` 和 `DecisionTree` 类并未给出,因此你需要根据自己的数据结构实现它们。此外,这个实现仅作为参考,你可以根据自己的需求进行修改和改进。