gpt4 book ai didi

arrays - 拆箱、(稀疏)矩阵和 haskell 向量库

转载 作者:行者123 更新时间:2023-12-04 08:53:37 25 4
gpt4 key购买 nike

我想使用 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)

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

最佳答案

我不知道你的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手术。

关于arrays - 拆箱、(稀疏)矩阵和 haskell 向量库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2737961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com