【问题标题】:How to perform element-wise scalar operations on a vector with Scala Breeze?如何使用 Scala Breeze 对向量执行逐元素标量操作?
【发布时间】:2012-10-11 19:12:27
【问题描述】:

使用 Scalala,可以使用标量操作数对 Vector 执行元素操作。假设您有一个介于 0 和 1 之间的随机数向量,并且您想从 1 中减去每个值:

import breeze.linalg._

val x = DenseVector.rand(5)
val y = 1d :- x  //DOESN'T COMPILE: "value :- is not a member of Double"

与 Scalala 不同,Breeze 无法使用这种方法进行编译。您可以通过生成向量来解决此问题,但似乎应该有更好的方法。

val y = DenseVector.ones[Double](x.size) :- x

另一种解决方法是使用更易读的 mapValues 方法:

val y = x mapValues { 1 - _ }

使用 Breeze 完成此任务的正确方法是什么?

【问题讨论】:

  • 你不想写val y = -x + 1d

标签: scala scala-breeze scalala


【解决方案1】:

这是一个老问题,有点过时了。目前,使用breeze 1.0 和scala 2.11 现在支持这种语法:

import breeze.linalg._

val x = DenseVector.rand(5)
val y = 1d :- x 

输出:

import breeze.linalg._
x: breeze.linalg.DenseVector[Double] = DenseVector(0.8274425487378012, 0.11585689753323769, 0.9691257294006741, 0.15061939654911782, 0.8337942418593918)
warning: there was one deprecation warning; re-run with -deprecation for details
y: breeze.linalg.DenseVector[Double] = DenseVector(0.1725574512621988, 0.8841431024667623, 0.030874270599325904, 0.8493806034508822, 0.16620575814060823)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多