【问题标题】:Breeze change DenseMatrix using vector decompositionBreeze 使用向量分解改变 DenseMatrix
【发布时间】:2015-05-29 20:27:44
【问题描述】:

下面的代码生成一个 0-1 矩阵,改变每一奇数行并组成一个新矩阵。我想使用foldLeft 连接向量,但得到Not all matrices have the same number of columns,可能是因为foldLeft 的零(或单位)元素是一个未知大小的空向量。

import breeze.linalg._
import breeze.stats.distributions._
object ZeroOneMatrix {
  def main(args: Array[String]) {
    val n = 4
    val m = DenseMatrix.rand[Int](n, n, rand = Rand.randInt(2))
    println(m)

    // vs is of type Vector[DenseVector[Int]]
    val vs = for (r <- 0 until n)
      yield {
        if (r % 2 == 1)
          m(r, ::).t map (e => (e + 1) % 2)
        else m(r, ::).t
      }
    println(vs)

    // compose matrix back from the list of vectors vs
    val f = (vs foldLeft DenseVector[Int]().asDenseMatrix)(
        (mat, v) => DenseMatrix.vertcat(v.asDenseMatrix, mat))
    println(f)
  }
}

如何解决?还有为什么在不进行转接的情况下不能在m(r, ::) 上调用map?理想情况下,我会将所选向量映射到新向量,然后使用DenseMatrix.horzcat 构建矩阵。

不对整个矩阵使用map函数的原因是某些行不会被改变。

【问题讨论】:

    标签: scala scala-breeze


    【解决方案1】:

    你说得对,为什么它不起作用。为什么不直接使用reduce?或:DenseVector.vertcat(vs:_*)

    Map:Breeze 赋予列向量特权,而行向量缺少很多功能。一般来说,您应该养成使用列而不是行的习惯。

    【讨论】:

    • 感谢您的提示。当我使用reduce 时,它说matDenseVector 而需要DenseMatrix,所以我转换mat.asDenseMatrix 然后它在v.asDenseMatrix 上失败,需要DenseVector :)
    • DenseVector.vertcat(vs:_*) 不起作用,因为我最后需要一个矩阵,这给了我一个连接向量。我正在做的是通过更改其中的一些行将矩阵从一种状态转换为另一种状态。而且我不想改变矩阵并通过使用map以功能样式实现它。
    • 关于仅将map 应用于列。这是为什么?矩阵是对称的,行应该被视为列。将行乘以常数并减去它们是高斯​​消元算法的基础,该算法将矩阵简化为实体矩阵。
    • 最终解决方案 - DenseMatrix.vertcat(vs:_*)
    • 啊,所以,mat(*, ::).map( ) 应该做你想做的事。 DenseVectors 有一个形状,它是一个列向量(因为 Breeze 是列主要的),我从来没有真正充实它的转置。我开始了,但需要一段时间。
    猜你喜欢
    • 1970-01-01
    • 2014-06-05
    • 2018-06-20
    • 2014-02-12
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    相关资源
    最近更新 更多