8

我想使用 haskell 的向量库有效地操作矩阵(完整或稀疏)。

这是一个矩阵类型

import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V

data Link a = Full (V.Vector (U.Vector a))
    | Sparse (V.Vector (U.Vector (Int,a)))

type Vector a = U.Vector a

如您所见,矩阵是未装箱向量的向量。现在,我想做一个向量和矩阵之间的点积。通过组合 sum、zip 和 map 来实现相当简单。

但是如果我这样做,因为我正在映射矩阵的行,结果是一个装箱的向量,即使它可以被取消装箱。

propagateS output (Field src) (Full weights) = V.map (sum out) weights
    where out     = U.map output src
          sum s w = U.sum $ zipWithFull (*) w s

propagateS output (Field src) (Sparse weights) = V.map (sum out) weights
    where out     = U.map output src
          sum s w = U.sum $ zipWithSparse (*) w s

zipWithFull = U.zipWith

zipWithSparse f x y = U.map f' x
    where f' (i,v) = f v (y U.! i)

如何有效地获得未装箱的矢量?

4

1 回答 1

1

我不知道你的Field类型是什么,所以我不太明白第二个片段。

但是,如果您将矩阵表示为盒装向量,您的中间结果将是盒装向量。如果您想获得未装箱的结果,则需要使用 . 显式转换类型U.fromList . V.toList。这是密集矩阵类型的示例(为简洁起见,我省略了稀疏情况):

import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V

-- assuming row-major order
data Matrix a = Full (V.Vector (U.Vector a))

type Vector a = U.Vector a

-- matrix to vector dot product
dot :: (U.Unbox a, Num a) => (Matrix a) -> (Vector a) -> (Vector a)
(Full rows) `dot` x =
  let mx = V.map (vdot x) rows
  in U.fromList . V.toList $ mx  -- unboxing, O(n)

-- vector to vector dot product
vdot :: (U.Unbox a, Num a) => Vector a -> Vector a -> a
vdot x y = U.sum $ U.zipWith (*) x y

instance (Show a, U.Unbox a) => Show (Matrix a) where
  show (Full rows) = show $ V.toList $ V.map U.toList rows

showV = show . U.toList

main =
  let m = Full $ V.fromList $ map U.fromList ([[1,2],[3,4]] :: [[Int]])
      x = U.fromList ([5,6] :: [Int])
      mx = m `dot` x
  in putStrLn $ (show m) ++ " × " ++ (showV x) ++ " = " ++ (showV mx)

输出:

 [[1,2],[3,4]] × [5,6] = [17,39]

我不确定这种方法的性能。将整个矩阵存储为单个未装箱向量并根据存储模型通过索引访问元素可能要好得多。这样你就不需要装箱的向量了。

还可以查看新的repa库及其index操作。

于 2010-05-04T17:49:45.370 回答