Breeze 使用向量分解改变 DenseMatrix
Breeze change DenseMatrix using vector decomposition
下面的代码生成一个 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)
}
}
如何修复?另外,为什么 map
不能在 m(r, ::)
上调用而不进行转换?理想情况下,我会将选定的向量映射到一个新向量中,然后使用 DenseMatrix.horzcat
构建矩阵。
不对整个矩阵使用 map
函数的原因是某些行不会更改。
关于为什么它不起作用,您是对的。为什么不直接使用 reduce
?或者:DenseVector.vertcat(vs:_*)
地图:Breeze 特权列向量,行向量缺少很多功能。一般来说,您应该养成使用列而不是行的习惯。
下面的代码生成一个 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)
}
}
如何修复?另外,为什么 map
不能在 m(r, ::)
上调用而不进行转换?理想情况下,我会将选定的向量映射到一个新向量中,然后使用 DenseMatrix.horzcat
构建矩阵。
不对整个矩阵使用 map
函数的原因是某些行不会更改。
关于为什么它不起作用,您是对的。为什么不直接使用 reduce
?或者:DenseVector.vertcat(vs:_*)
地图:Breeze 特权列向量,行向量缺少很多功能。一般来说,您应该养成使用列而不是行的习惯。