![](/img/trans.png)
[英]How to efficiently resize a numpy array to a given shape, padding with zeros if necessary?
[英]How does numpy zeros implement the parameter shape?
我想實現類似的功能,並希望接受傳遞給numpy.ones
的數組或數字。
具體來說,我想這樣做:
def halfs(shape):
shape = numpy.concatenate([2], shape)
return 0.5 * numpy.ones(shape)
輸入/輸出對示例:
# 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]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.