使用Java代码编写逻辑回归预测算法
时间: 2023-10-04 19:05:54 浏览: 72
下面是使用Java代码编写逻辑回归预测算法的示例:
1. 定义LogisticRegression类
```
public class LogisticRegression {
private double[] weights;
public LogisticRegression(int numFeatures) {
weights = new double[numFeatures];
}
public double predict(double[] features) {
double score = 0.0;
for (int i = 0; i < weights.length; i++) {
score += weights[i] * features[i];
}
double prob = 1.0 / (1.0 + Math.exp(-score));
return prob;
}
public void train(double[][] features, int[] labels, double learningRate, int numIterations) {
for (int iter = 0; iter < numIterations; iter++) {
for (int i = 0; i < features.length; i++) {
double[] x = features[i];
int y = labels[i];
double prob = predict(x);
for (int j = 0; j < weights.length; j++) {
weights[j] += learningRate * (y - prob) * x[j];
}
}
}
}
}
```
2. 调用LogisticRegression类进行训练和预测
```
public static void main(String[] args) {
// 训练数据
double[][] features = {{1.0, 2.0}, {2.0, 3.0}, {3.0, 4.0}, {4.0, 5.0}, {5.0, 6.0}};
int[] labels = {0, 0, 1, 1, 1};
// 创建逻辑回归模型
LogisticRegression lr = new LogisticRegression(2);
// 训练模型
lr.train(features, labels, 0.01, 100);
// 预测新数据
double[] x = {6.0, 7.0};
double prob = lr.predict(x);
System.out.println("预测概率为:" + prob);
}
```