Scala 中逐元素矩阵乘法

Element by Element Matrix Multiplication in Scala

我有一个输入 mllib matrix 喜欢,

matrix1: org.apache.spark.mllib.linalg.Matrix =
1.0  0.0  2.0  1.0
0.0  3.0  1.0  1.0
2.0  1.0  0.0  0.0

matrix1 的维度是 3*4。 我需要逐个元素 matrix 与另一个矩阵相乘,以便两个矩阵的维度在所有情况下都相同。让我们假设我有另一个名为 matrix2 like

的矩阵
matrix2: org.apache.spark.mllib.linalg.Matrix =
3.0  0.0  2.0  1.0
1.0  9.0  5.0  1.0
2.0  5.0  0.0  0.0

尺寸3*4 我的结果矩阵应该是,

result: org.apache.spark.mllib.linalg.Matrix =
3.0  0.0   4.0  1.0
0.0  27.0  5.0  1.0
4.0  5.0   0.0  0.0

我如何在 Scala 中实现这一点? (注意:spark mllib 的内置函数 multiply 按照精确矩阵乘法工作。)

下面是一种方法。在这里,我们逐列迭代矩阵并找到它们的元素乘法。该解决方案假定两个矩阵具有相同的维度。
首先让我们创建问题中给出的测试矩阵。

//creating example matrix as per the question
val m1: Matrix = new DenseMatrix(3, 4, Array(1.0, 0.0, 2.0, 0.0, 3.0, 1.0, 2.0, 1.0, 0.0, 1.0, 1.0, 0.0))
val m2: Matrix = new DenseMatrix(3, 4, Array(3.0, 1.0, 2.0, 0.0, 9.0, 5.0, 2.0, 5.0, 0.0, 1.0, 1.0, 0.0))

现在让我们定义一个函数,它需要两个 Matrix 和 returns 它们的元素乘法。

//define a function to calculate element wise multiplication
def elemWiseMultiply(m1: Matrix, m2: Matrix): Matrix = {
  val arr = new ArrayBuffer[Array[Double]]()
  val m1Itr = m1.colIter //operate on each columns
  val m2Itr = m2.colIter
  while (m1Itr.hasNext)
    //zip both the columns and then multiple element by element
    arr += m1Itr.next.toArray.zip(m2Itr.next.toArray).map { case (a, b) => a * b }
  //return the resultant matrix
  new DenseMatrix(m1.numRows, m1.numCols, arr.flatten.toArray)
}

然后您可以调用此函数进行元素乘法运算。

//call the function to m1 and m2
elemWiseMultiply(m1, m2)

//output
//3.0  0.0   4.0  1.0
//0.0  27.0  5.0  1.0
//4.0  5.0   0.0  0.0