这是我的代码:

package algorithms;
import Jama.Matrix;
import java.io.File;
import java.util.Arrays;
public class ThetaGetter {
    //First column is one, second is price and third is BHK
    private static double[][] variables = {
        {1,1130,2},
        {1,1100,2},
        {1,2055,3},
        {1,1047,2},
        {1,1927,3},
        {1,2667,3},
        {1,1146,2},
        {1,2020,3},
        {1,1190,2},
        {1,2165,3},
        {1,1250,2},
        {1,1185,2},
        {1,2825,4},
        {1,1200,2},
        {1,1580,3},
        {1,3200,3},
        {1,715,1},
        {1,1270,2},
        {1,2403,3},
        {1,1465,3},
        {1,1345,2}
    };

    private static double[][] prices = {
        {69.65},
        {60},
        {115},
        {55},
        {140},
        {225},
        {76.78},
        {120},
        {73.11},
        {140},
        {56},
        {79.39},
        {161},
        {73.69},
        {80},
        {145},
        {34.87},
        {77.72},
        {165},
        {98},
        {82}
    };
    private static Matrix X = new Matrix(variables);
    private static Matrix y = new Matrix(prices);
    public static void main(String[] args) {
        File file = new File("theta.dat");
        if(file.exists()){
            System.out.println("Theta has already been calculated!");
            return;
        }
        //inverse(Tra(X)*X)*tra(X)*y
        Matrix transposeX = X.transpose();
        Matrix inverse = X.times(transposeX).inverse();
        System.out.println(y.getArray().length);
        System.out.println(X.getArray().length);
        Matrix test = inverse.times(transposeX);
        Matrix theta = test.times(y);
        System.out.println(Arrays.deepToString(theta.getArray()));
    }
}


该算法基本上尝试获取房屋价格,然后获取一些常数,然后将其用于猜测房屋价格。但是我在'Matrix theta = test.times(y);'行上遇到了异常。该错误消息几乎是问题所在。尺寸是否存在排序问题?他们两个都有21个项目,所以我不知道发生了什么。

最佳答案

您所犯的错误在于以下代码行:

Matrix inverse = X.times(transposeX).inverse();


您上面评论的公式是:

//inverse(Tra(X)*X)*tra(X)*y


但是您实际上在代码中计算的是:
(X * Tra(X)代替Tra(X)* X)

//inverse(X*Tra(X))*tra(X)*y


如果X的尺寸为(m,n),则


m =行数
n =列数


Y的维数为(m,1),使用上面使用的乘法,您将得到以下结果:

逆(X * Tra(X))* Tra(X)* Y =逆* Tra(X)* Y =结果* y

inverse((m,n)(n,m))(n,m)*(m,1)=(m,m)*(n,m)=>由于矩阵的内部尺寸而导致错误乘法必须相等

可以解决您问题的代码将替换以下行:

Matrix inverse = X.times(transposeX).inverse();




 Matrix inverse = transposeX.times(X).inverse();

10-02 03:58