1{-# LANGUAGE DataKinds #-}
3{-# LANGUAGE TypeFamilies #-}
4{-# LANGUAGE TypeOperators #-}
5{-# LANGUAGE FlexibleContexts #-}
6{-# LANGUAGE ScopedTypeVariables #-}
7{-# LANGUAGE RankNTypes #-}
9module Grenade.Utils.OneHot (
17import qualified Control.Monad.Random as MR
19import Data.List ( group, sort )
21import Data.Map ( Map )
22import qualified Data.Map as M
26import Data.Vector ( Vector )
27import qualified Data.Vector as V
28import qualified Data.Vector.Storable as VS
30import Numeric.LinearAlgebra ( maxIndex )
31import Numeric.LinearAlgebra.Devel
32import Numeric.LinearAlgebra.Static
35import Grenade.Core.Shape
37-- | From an int which is hot, create a 1D Shape
38-- with one index hot (1) with the rest 0.
39-- Rerurns Nothing if the hot number is larger
40-- than the length of the vector.
41oneHot :: forall n. (KnownNat n)
42 => Int -> Maybe (S ('D1 n))
44 let len = fromIntegral $ natVal (Proxy :: Proxy n)
47 fmap S1D . create $ runSTVector $ do
48 vec <- newVector 0 len
53-- | Create a one hot map from any enumerable.
54-- Returns a map, and the ordered list for the reverse transformation
55hotMap :: (Ord a, KnownNat n) => Proxy n -> [a] -> Either String (Map a Int, Vector a)
57 let len = fromIntegral $ natVal n
58 uniq = [ c | (c:_) <- group $ sort as]
62 Right (M.fromList $ zip uniq [0..], V.fromList uniq)
64 Left ("Couldn't create hotMap of size " ++ show len ++ " from vector with " ++ show hotl ++ " unique characters")
66-- | From a map and value, create a 1D Shape
67-- with one index hot (1) with the rest 0.
68-- Rerurns Nothing if the hot number is larger
69-- than the length of the vector or the map
70-- doesn't contain the value.
71makeHot :: forall a n. (Ord a, KnownNat n)
72 => Map a Int -> a -> Maybe (S ('D1 n))
75 let len = fromIntegral $ natVal (Proxy :: Proxy n)
78 fmap S1D . create $ runSTVector $ do
79 vec <- newVector 0 len
84unHot :: forall a n. KnownNat n
85 => Vector a -> S ('D1 n) -> Maybe a
88 $ maxIndex (extract xs)
90sample :: forall a n m. (KnownNat n, MR.MonadRandom m)
91 => Double -> Vector a -> S ('D1 n) -> m a
92sample temperature v (S1D xs) = do
93 ix <- MR.fromList . zip [0..] . fmap (toRational . exp . (/ temperature) . log) . VS.toList . extract $ xs
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list