问题描述
我正在计算 NN 的成本函数.我对从 numpy.dot 得到的 (1,1) 答案做了一个 numpy.squeeze.然后我得到一个形状为 (0,1) 的 ndarray.
I'm calculating a cost function for a NN. I do a numpy.squeeze on a (1,1) answer that I get from numpy.dot. I then get an ndarray of shape (0,1).
什么是形状 () 的 ndarray,形状 (1,) 的 ndarray 与形状 (5) 中的一个有何不同?
What is an ndarray of shape () and how does an ndarray of shape (1,) differ from one of shape (5)?
推荐答案
- 形状为
(1, 1)
的 ndarray 类似于[[3]]
,就像一个 1x1 矩阵. - 形状为
(1,)
的 ndarray 类似于[3]
,就像大小为 1 的向量. - 形状为
()
的 ndarray,又名标量,类似于3
. - An ndarray of shape
(1, 1)
is something like[[3]]
, like a 1x1 matrix. - An ndarray of shape
(1,)
is something like[3]
, like a vector of size 1. - An ndarray of shape
()
, a.k.a a scalar, is something like3
.
区别很微妙,因为根据广播规则,标量和数组通常可以毫无问题地组合在一起,但是您不能索引标量,而您可以索引大小为 1 的向量或大小为 1x1 的矩阵.另一方面,标量通常可以像原始 Python 值一样使用,例如 int
或 float
.如果您不想使用标量,您可以将 axis
参数传递给 np.squeeze
以确保某些维度不被挤压或使用 np.atleast_1d
以确保无论你pass 至少有一个维度.您还可以使用 检查某些内容是否为标量np.isscalar
.
The difference is subtle because due to broadcasting rules scalars and arrays can usually be combined without problem, but you cannot index a scalar, while you can index a vector of size 1 or a matrix of size 1x1. On the other hand, scalars can generally be used like primitive Python values such as int
or float
. If you don't want to have a scalar you can either pass an axis
parameter to np.squeeze
to make sure that some dimension is not squeezed or use np.atleast_1d
to make sure that whatever you pass has at least one dimension. You can also check if something is a scalar with np.isscalar
.
这篇关于np.squeeze 从形状 (1,1) 之后返回的形状 () ndarray 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!