首先大家了解一下最小二乘回归,如下:
最小二乘法(又称最小平方法)是一种数学优化技术。它通过最小化误差的平方和寻找数据的最佳函数匹配。利用最小二乘法可以简便地求得未知的数据,并使得这些求得的数据与实际数据之间误差的平方和为最小。
考虑超定方程组(超定指未知数小于方程个数):
其中m代表有m个等式,n代表有 n 个未知数
最小二乘法其实初高中数学就有涉及,我们先看看它的python语言实现
def standRegres(xArr,yArr):
xMat = mat(xArr); yMat = mat(yArr).T
xTx = xMat.T*xMat
if linalg.det(xTx) == 0.0:
print("This matrix is singular, cannot do inverse")
return
ws = xTx.I * (xMat.T*yMat)
return ws
python实现比较简单,主要是一些矩阵操作,java实现如下:
public static double[] standRegres(DenseMatrix64F xArr,double[] yArr) {
DenseMatrix64F xMatT = new DenseMatrix64F(xArr.numCols,xArr.numRows);
CommonOps.transpose(xArr,xMatT);
DenseMatrix64F xTx = new DenseMatrix64F(xArr.numCols,xArr.numCols);
CommonOps.mult(xMatT,xArr, xTx);
CommonOps.invert(xTx);
double[] tmp = new double[xArr.numCols];
for(int j=0;j<xArr.numCols;j++) {
tmp[j] = 0;
}
for(int i=0;i<xArr.numCols;i++) {
for(int j=0;j<xArr.numRows;j++) {
tmp[i]+=xMatT.get(i,j)*yArr[j];
}
}
double[] ws = new double[xArr.numCols];
for(int j=0;j<xArr.numCols;j++) {
ws[j] = 0;
}
for(int i=0;i<xArr.numCols;i++) {
for(int j=0;j<xArr.numCols;j++) {
ws[i]+=xTx.get(i,j)*tmp[j];
}
}
return ws;
}
测试如下:
List<String> list = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader("D:\\machinelearninginaction-master\\Ch08\\ex0.txt"));
String s = null;
while((s = br.readLine())!=null){
list.add(s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
DenseMatrix64F dataMatIn = new DenseMatrix64F(list.size(),2);
double[] classLabels = new double[list.size()];
for(int i=0;i<list.size();i++) {
String[] items = list.get(i).split(" ");
dataMatIn.set(i, 0, Double.parseDouble(items[0]));
dataMatIn.set(i,1, Double.parseDouble(items[1]));
classLabels[i] = Double.parseDouble(items[2]);
}
double[] ws = standRegres(dataMatIn,classLabels);
System.out.println(ws[0]);
System.out.println(ws[1]);
结果正确