dot 与 (1,n) 和 (n,1) 生成 (1,1) 数组:
In [1221]: x = np.ones((3,1))
In [1222]: xx = np.dot(x.T,x)
In [1223]: xx.shape
Out[1223]: (1, 1)
In [1224]: xx
Out[1224]: array([[ 3.]])
item 可用于从数组中提取该值:
Out[1227]: 3.0
In [1228]: type(_)
Out[1228]: float
您也可以通过索引选择项目,尽管type 会有所不同:
In [1229]: xx[0,0]
Out[1229]: 3.0
In [1230]: type(_)
Out[1230]: numpy.float64
对于许多用途,float 和 np.float64 之间的区别并不重要。
squeeze 删除所有尺寸为 1 的尺寸。在这种情况下,结果是一个 0d 数组。 item 仍然有效。使用正确大小的索引(即长度为 0 的元组)也可以使用索引:
In [1231]: xx0 = np.squeeze(xx)
In [1232]: xx0.shape
Out[1232]: ()
In [1233]: xx0.item()
Out[1233]: 3.0
In [1234]: xx0[()]
Out[1234]: 3.0
In [1235]: type(_)
Out[1235]: numpy.float64
np.float64 的类继承是:
In [1236]: _.__mro__
Out[1236]:
(numpy.float64,
numpy.floating,
numpy.inexact,
numpy.number,
numpy.generic,
float,
object)
所以isinstance float 仍然会返回 true
In [1237]: isinstance(xx0.item(),float)
Out[1237]: True
In [1238]: isinstance(xx0[()],float)
Out[1238]: True
In [1239]: isinstance(xx[0,0],float)
Out[1239]: True
我不会依赖于所有 numpy dtypes。