1 这里先创建个对象aaa
class AAA {
//名字和年龄为x,成绩为y
String name;
Sting age;
String performance;
}
2定义方法
class aaa{
public static Instances getData(List<AAA> personList) {
/**
* 1.创建数据格式
*/
//创建两个数值型
Attribute num1 = new Attribute("num1");
Attribute num2 = new Attribute("num2");
Attribute result = new Attribute("result");
//创建一个relation关系
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(num1);
attributes.add(num2);
attributes.add(result);
//把创建的格式应用在数据集中
//如果知道数据有多少行,就可以不用0
Instances dataset = new Instances("Test-dataset", attributes, 0);
for (AAA aaa : personList) {
double[] values = new double[dataset.numAttributes()];
//2为y,其他为x,(根据自己需要创建多个X)
values[0] = aaa.name
values[1] = aaa.age
values[2] = aaa.performance
dataset.add(new DenseInstance(1.0, values));
}
return dataset;
}
}
3 打印
Instances data = getData(list);
if (data.classIndex() == -1) {
data.setClassIndex(data.numAttributes() - 1);
}
// 构建模型
LinearRegression lr = new LinearRegression();
lr.buildClassifier(data);
List<Double> v = new ArrayList<>();
// 输出回归系数
double[] coefficients = lr.coefficients();
for (int i = 0; i < coefficients.length; i++) {
String name = "";
if (i == coefficients.length - 1) {
name = "常量";
} else if (i == coefficients.length - 2) {
name = "因变量";
} else {
name = data.attribute(i).name();
}
double b = coefficients[i];
v.add(b);
System.out.println(vin+" " + name + ": " + b);
}