gpt4 book ai didi

java.lang.IllegalArgumentException : Matrix inner dimensions must agree 异常

转载 作者:行者123 更新时间:2023-11-29 04:20:50 26 4
gpt4 key购买 nike

这是我的代码:

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);”这一行遇到了一个异常(exception)错误消息几乎就是问题所在。尺寸是否存在某种问题?两个都有21个item,不知道怎么回事。

最佳答案

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

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();

关于java.lang.IllegalArgumentException : Matrix inner dimensions must agree 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com