Tricks and Tips

“Automatic” Reshaping

>>> a = np.arange(30)
>>> a.shape = 2,-1,3  # -1 means "whatever is needed"
>>> a.shape
(2, 5, 3)
>>> a
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11],
        [12, 13, 14]],
       [[15, 16, 17],
        [18, 19, 20],
        [21, 22, 23],
        [24, 25, 26],
        [27, 28, 29]]])
>>> let a = 30 |> [0..] :: Vector Z
>>> toBlocksEvery 5 3 (reshape 3 a) -- emulate depth with lists
[[(5><3)
 [  0,  1,  2
 ,  3,  4,  5
 ,  6,  7,  8
 ,  9, 10, 11
 , 12, 13, 14 ]],[(5><3)
 [ 15, 16, 17
 , 18, 19, 20
 , 21, 22, 23
 , 24, 25, 26
 , 27, 28, 29 ]]]

Vector Stacking

x = np.arange(0,10,2)                     # x=([0,2,4,6,8])
y = np.arange(5)                          # y=([0,1,2,3,4])
m = np.vstack([x,y])                      # m=([[0,2,4,6,8],
                                          #     [0,1,2,3,4]])
xy = np.hstack([x,y])                     # xy =([0,2,4,6,8,0,1,2,3,4])
>>> let x = fromList [0,2..10-2] :: Vector Z
>>> x
[0,2,4,6,8]
>>> let y = 5 |> [0..] :: Vector Z
>>> y
[0,1,2,3,4]
>>> let m = fromRows [x,y]
>>> m
(2><5)
 [ 0, 2, 4, 6, 8
 , 0, 1, 2, 3, 4 ]
>>> let xy = vjoin [x,y]
>>> xy
[0,2,4,6,8,0,1,2,3,4]

Histograms

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> # Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2
>>> mu, sigma = 2, 0.5
>>> v = np.random.normal(mu,sigma,10000)
>>> # Plot a normalized histogram with 50 bins
>>> plt.hist(v, bins=50, normed=1)       # matplotlib version (plot)
>>> plt.show()
>>> # Compute the histogram with numpy and then plot it
>>> (n, bins) = np.histogram(v, bins=50, normed=True)  # NumPy version (no plot)
>>> plt.plot(.5*(bins[1:]+bins[:-1]), n)
>>> plt.show()
>>> let (mu, sigma) = (2, 0.5)
>>> (mu, sigma)
(2,0.5)
>>> import Numeric.LinearAlgebra.HMatrix (Seed, RandDist(..), gaussianSample, rand)
>>> let rand' seed mu sigma c = mu + sigma * (randomVector seed Gaussian c)
>>> let v = rand' 1 mu sigma 10000
>>> :{
normedhist :: Vector R -> Int -> Vector R
normedhist vec numbins = accum bins (+) (fmap go (toList vec))
                         where
                           bins = konst 0 numbins
                           (lo, hi) = (minElement vec, maxElement vec)
                           delt = (hi-lo) / fromIntegral numbins
                           valscale val = min (numbins-1) (floor ((val-lo) / delt))
                           go val = (valscale val, 1 / fromIntegral (size vec))
:}

>>> let hist = normedhist v 50
>>> disp 2 (scalar (sumElements hist))
1x1
1.00
>>> let bins = linspace 50 (minElement v, maxElement v)