gpt4 book ai didi

Java/处理如何使用点积进行矩阵乘法

转载 作者:太空宇宙 更新时间:2023-11-04 10:28:40 25 4
gpt4 key购买 nike

你好,我正在使用处理(witch本质上只是Java),我想要一个非常简单的矩阵类来帮助我处理我的神经网络。

它工作正常,但“矩阵乘法”部分实际上不起作用。

我知道我的代码是错误的,但我似乎找不到修复方法。

类(class)的开始是这样的:

class Matrix {

int rows;
int cols;
double[][] matrix;

Matrix(int rows_ , int cols_ ) {
rows = rows_;
cols = cols_;

// set size of matrix
matrix = new double[rows][cols];

// fill with 0s
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = 0;
}
}
}

错误的部分在这里:

Matrix Matrix_Multipication(Matrix b) {

// Create new Matrix for the result
Matrix c = new Matrix(b.cols,rows);

// check if not number of cols is number of rows of b
if (cols != b.rows) {
return c;
}
// Compute
for(int i=0; i< c.cols; i++){
for(int j=0; j< c.rows; j++){
for(int k=0; k< rows; k++){
c.matrix[i][j] = c.matrix[i][j] + matrix[i][k] * b.matrix[k][j]; // here is the error
}
}
}
// return new matrix
return c;
}

错误是:

ArrayIndexOutOfBoundsExcpetion : 1

只有当列大小为一时,我才会收到此错误:

Matrix m1 = new Matrix(2,3);
Matrix m2 = new Matrix(3,1); // here the 1
Matrix m3 = m1.Matrix_Multipication(m2); // apply Matrix_Multipication

我认为也许构造函数也是错误的,但我不知道它是如何错误的。

您还可以向我展示矩阵库,以及如果您找不到任何错误,我如何安装它们。

ps:我做了研究,但没有发现任何东西。我尝试编写自己版本的神经网络库形式“The-Coding-Train”https://www.youtube.com/watch?v=NgZAIkDcPkI&list=PLRqwX-V7Uu6Y7MdSCaIfsxc561QI0U0Tb&index=8 .

请告诉我这个问题和这段代码需要改进什么。

最佳答案

您交换了行和列。

构造函数中的第一个参数是行,第二个参数是列:

Matrix c = new Matrix(rows,b.cols);

由于该矩阵是行主阶矩阵,因此控制变量 i必须从 = 0 运行至< c.rows和控制变量j来自= 0< c.cols :

for(int i=0; i< c.rows; i++){
for(int j=0; j< c.cols; j++){
for(int k=0; k< rows; k++){
c.matrix[i][j] = c.matrix[i][j] + matrix[i][k] * b.matrix[k][j];
}
}
}

关于Java/处理如何使用点积进行矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50305851/

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