开发者

How does numpy zeros implement the parameter shape?

I want to implement a similar function, and want to accept an array or number that I pass to numpy.ones.

Specifically, I want to do this:

def halfs(shape):
    shape = numpy.concatenate([2], shape)
    return 0.5 * numpy.ones(shape)

Example input-output pairs:

# default
In [5]: beta_jeffreys()
Out[5]: array([-0.5, -0.5])

# scalar
In [5]: beta_jeffreys(3)
Out[3]: 
array([[-0.5, -0.5, -0.5],
       [-0.5, -0.5, -0.5]])

# vector (1)
In [3]: beta_jeffreys((3,))
Out[3]: 
array([[-0.5, -0.5, -0.5],
       [-0.开发者_开发技巧5, -0.5, -0.5]])

# vector (2)
In [7]: beta_jeffreys((2,3))
Out[7]: 
array([[[-0.5, -0.5, -0.5],
        [-0.5, -0.5, -0.5]],

       [[-0.5, -0.5, -0.5],
        [-0.5, -0.5, -0.5]]])


def halfs(shape=()):
    if isinstance(shape, tuple):
        return 0.5 * numpy.ones((2,) + shape)
    else:
        return 0.5 * numpy.ones((2, shape))



a = numpy.arange(5)
# array([0, 1, 2, 3, 4])


halfs(a.shape)
#array([[ 0.5,  0.5,  0.5,  0.5,  0.5],
#       [ 0.5,  0.5,  0.5,  0.5,  0.5]])

halfs(3)
#array([[ 0.5,  0.5,  0.5],
#       [ 0.5,  0.5,  0.5]])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜