lehins / massiv

Efficient Haskell Arrays featuring Parallel computation
BSD 3-Clause "New" or "Revised" License
384 stars 23 forks source link

Add vector to matrix (and similar operations) #113

Open justinlovinger opened 3 years ago

justinlovinger commented 3 years ago

For example:

[ [ 0 1 2 ]
  [ 3 4 5 ] ]
+
  [ 0 1 2 ]
=
[ [ 0 2 4 ]
  [ 3 5 7 ] ]

I frequently need operations like this when writing machine learning code.

Related: https://github.com/lehins/massiv/issues/60.

ukari commented 3 years ago

for reference:

broadcastPointwiseAdd :: (Numeric r e, Mutable r Ix2 e, Manifest r Ix1 e) => Array r Ix2 e -> Array r Ix1 e -> Array r Ix2 e
broadcastPointwiseAdd m v = m !+! (compute . Massiv.transpose . expandWithin Dim1 (fst . unconsSz . size $ m) const $ v)

test :: IO ()
test = do
  let w = compute $ resize' (Sz (2 :. 3)) (0 ... 5) :: Array U Ix2 Int
  let b = compute (0 ... 2) :: Array U Ix1 Int
  print w
  print b
  print $ w `broadcastPointwiseAdd` b
  pure ()
λ> test
Array U Seq (Sz (2 :. 3))
  [ [ 0, 1, 2 ]
  , [ 3, 4, 5 ]
  ]
Array U Seq (Sz1 3)
  [ 0, 1, 2 ]
Array U Seq (Sz (2 :. 3))
  [ [ 0, 2, 4 ]
  , [ 3, 5, 7 ]
  ]