【问题标题】:Java/Processing how to do Matrix Multipication with the dot productJava /处理如何使用点积进行矩阵乘法
【发布时间】:2018-05-12 11:43:34
【问题描述】:

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

它工作正常,但“矩阵乘法”部分并没有真正工作。

我知道我的代码有问题,但我似乎找不到修复方法。

课程的开头是这样的:

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。

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

【问题讨论】:

  • 为什么不使用现有的 java 线性代数库。有几个:lessthanoptimal.github.io/Java-Matrix-Benchmark
  • 我想了解它是如何工作的,但我已经尝试过“Jama”,但我不知道如何安装它们......
  • 你能帮我安装 Jama 这个库吗?用于加工。这对我来说是一个有效的答案。

标签: java matrix processing linear-algebra


【解决方案1】:

您将行交换为列。

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

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

由于矩阵是行主阶矩阵,控制变量i 必须从= 0 运行到&lt; c.rows,控制变量j 从= 0 运行到&lt; 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]; 
        }
    }
}

【讨论】:

  • 是的,我自己发现我吃了一些东西,现在我有了答案,但仍然感谢其他人可能有同样的问题:D
【解决方案2】:

第一个索引表示行。但是你迭代直到 c.cols。 第二个索引是列。但是你迭代直到 c.rows。 只需交换它们即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多