检查 numpy 数组形状是否为 (),如果是,则重塑为 (1,)

Check numpy array shape is () and if so reshape to (1,)

我有一个函数可以 return 单个值作为 numpy 数组:

print(yhat, yhat.shape)
Output: 0.9337081 ()

如何检查 numpy 数组形状是否为 (),如果是则将其重塑为 (1,)?因此得到:

yhat = np.array([0.9337081])

您已经通过打印 yhat.shape 来验证其形状等于 ()。如果要重塑 numpy 数组,请使用 reshape.

>>> yhat = np.array(0.9337081)
>>> yhat.shape
()
>>> yhat.shape == ()
True
>>> yhat = yhat.reshape(-1,)
>>> yhat.shape
(1,)
>>> yhat
array([0.9337081])