0

I'm new to numpy and I must be doing something stupid here, but all I want is to generate an array of 4-dimention probability distributions. I don't understand why my vectorised function is returning this weird object which claims to be of type np.ndarray but doesn't print like one. Also, it returns error when I call self.inputSpace[:,0].

Here's the entire content of test.py:

import numpy as np

def generateDist(i,j,k):
    return np.squeeze(np.array([i*j,i*(1-j),(1-i)*k,(1-i)*(1-k)]))

generateDist = np.vectorize(generateDist,otypes=[np.ndarray])

class distributionSpace():
    def __init__(self):
        self.grid = 3 # set to 3 for simplicity
        self.inputSpace = np.array([])

    def generateDistribution(self):
        alpha = np.linspace(0.,1.,self.grid)
        beta = np.linspace(0.,1.,self.grid)
        gamma = np.linspace(0.,1.,self.grid)
        i , j , k = np.meshgrid(alpha,beta,gamma)
        i = np.squeeze(i.flatten())
        j = np.squeeze(j.flatten())
        k = np.squeeze(k.flatten())
        self.inputSpace = generateDist(i,j,k)
        print(self.inputSpace)
        return self

if __name__ == '__main__':
    distributionSpace().generateDistribution()

And here's the result I got:

$ python3 test.py 
[array([ 0.,  0.,  0.,  1.]) array([ 0. ,  0. ,  0.5,  0.5])
 array([ 0.,  0.,  1.,  0.]) array([ 0. ,  0.5,  0. ,  0.5])
 array([ 0.  ,  0.5 ,  0.25,  0.25]) array([ 0. ,  0.5,  0.5,  0. ])
 array([ 0.,  1.,  0.,  0.]) array([ 0.,  1.,  0.,  0.])
 array([ 0.,  1.,  0.,  0.]) array([ 0.,  0.,  0.,  1.])
 array([ 0. ,  0. ,  0.5,  0.5]) array([ 0.,  0.,  1.,  0.])
 array([ 0.25,  0.25,  0.  ,  0.5 ]) array([ 0.25,  0.25,  0.25,  0.25])
 array([ 0.25,  0.25,  0.5 ,  0.  ]) array([ 0.5,  0.5,  0. ,  0. ])
 array([ 0.5,  0.5,  0. ,  0. ]) array([ 0.5,  0.5,  0. ,  0. ])
 array([ 0.,  0.,  0.,  1.]) array([ 0. ,  0. ,  0.5,  0.5])
 array([ 0.,  0.,  1.,  0.]) array([ 0.5,  0. ,  0. ,  0.5])
 array([ 0.5 ,  0.  ,  0.25,  0.25]) array([ 0.5,  0. ,  0.5,  0. ])
 array([ 1.,  0.,  0.,  0.]) array([ 1.,  0.,  0.,  0.])
 array([ 1.,  0.,  0.,  0.])]
lingxiao
  • 1,214
  • 17
  • 33
  • possible duplicate of [Using Numpy Vectorize on Functions that Return Vectors](http://stackoverflow.com/questions/3379301/using-numpy-vectorize-on-functions-that-return-vectors) – tmdavison Sep 08 '15 at 15:00

1 Answers1

0

Found an answer here for people who are searching : Using Numpy Vectorize on Functions that Return Vectors

tl;dr:

self.inputSpace = np.array(generateDist(i,j,k).tolist())
Community
  • 1
  • 1
lingxiao
  • 1,214
  • 17
  • 33
  • 1
    it might be worth reading the second answer there too: that `np.vectorize` is just a convenience funciton, so is not really that useful to use here, as you are feeding it a `numpy` array, and expecting one in return. Since `vectorize` will not speed up your code, you might want to just rewrite your function to do what you require without using `vectorize` – tmdavison Sep 08 '15 at 15:01