gpt4 book ai didi

python - numpy Zeros 如何实现参数形状?

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:58 25 4
gpt4 key购买 nike

我想要实现类似的函数,并且想要接受传递给 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]])

关于python - numpy Zeros 如何实现参数形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com