From: John Benediktsson Date: Sun, 30 Jan 2022 21:20:47 +0000 (-0800) Subject: tensors: simplify using map-sum X-Git-Tag: 0.99~1599 X-Git-Url: https://gitweb.factorcode.org/gitweb.cgi?p=factor.git;a=commitdiff_plain;h=958e80cebf2f2ac69714f2ca81cd2552024de8ca tensors: simplify using map-sum --- diff --git a/extra/tensors/tensors.factor b/extra/tensors/tensors.factor index 578bcd2e8e..ef2bc0ae70 100644 --- a/extra/tensors/tensors.factor +++ b/extra/tensors/tensors.factor @@ -57,7 +57,7 @@ PRIVATE> ! Construct a tensor with vec { 0 1 2 ... } and reshape to the desired shape : naturals ( shape -- tensor ) - check-shape [ ] [ product [0..b) >float-array ] bi ; + check-shape dup product [0..b) >float-array ; ! Construct a tensor without initializing its values : (tensor) ( shape -- tensor ) @@ -76,8 +76,7 @@ PRIVATE> ! Flatten the tensor so that it is only one-dimensional : flatten ( tensor -- tensor ) - dup shape>> - product { } 1sequence >>shape ; + dup shape>> product { } 1sequence >>shape ; ! outputs the number of dimensions of a tensor : dims ( tensor -- n ) @@ -294,7 +293,7 @@ METHOD: t% { number tensor } [ >float ] dip [ mod ] with t-uop ; ! Sum together all elements in the tensor syntax:M: tensor sum vec>> 0 - [ simd-slice>> 0 [ sum + ] reduce ] + [ simd-slice>> [ sum ] map-sum ] [ end-slice>> sum ] bi + ; > 0 :: final-vstack-shape ( seq -- shape ) ! Compute the new second-to-last dimension seq first dims 2 - :> vdim - seq 0 [ shape>> vdim swap nth + ] reduce + seq [ shape>> vdim swap nth ] map-sum ! Combine it to create the new shape seq first shape>> clone :> new-shape vdim new-shape set-nth @@ -421,7 +420,7 @@ PRIVATE> ! Compute the final shape [ ! Compute the first dimension - [ 0 [ shape>> first + ] reduce 1array ] + [ [ shape>> first ] map-sum 1array ] ! Compute the other dimensions [ first shape>> rest ] bi append ]