在 numpy 中,向量
[
1
2
3
]
\begin{bmatrix} 1\\2\\3\end{bmatrix}
⎣⎡123⎦⎤ 和
[
1
2
3
]
\begin{bmatrix} 1&2&3\end{bmatrix}
[123] 的 shape 是相同的,都是 (3,)
,如果想要得到 (3,1)
或者 (1,3)
的 shape,需要使用 reshape 方法。如果 想得到 (3,1)
,调用 a.reshape(-1, 1)
或者 np.reshape(a, (-1,1))
,如果想得到 (1,3)
,调用 a.reshape(-1,3)
或者 np.reshape(a, (-1,3))
。如下表格所示:
(3,1) | (1,3) | |
---|---|---|
ndarray | a.reshape(-1,1) | a.reshape(-1,3) |
numpy | np.reshape(a,(-1,1)) | np.reshape(a,(-1,3)) |
-1 的意思是,确定列数后,行数由 总数 / 列数 确定,如果 a 有 n 个元素,列为 3,则行数 = n / 3。
reshape 进行维度的转换
a = np.array([1,2,3])
print(a.shape)
(3,)
b = a.reshape(-1,1)
print(b.shape)
(3, 1)
squeeze 方法则相反,将一个 shape 为 (n, 1)
或者 (1,n,1,...,1)
的 ndarray,转化为shape 为 (n,)
的 ndarray
把shape中为1的维度去掉
a = np.array([[1],[2],[3]])
print(a.shape)
(3, 1)
b = np.squeeze(a)
print(b.shape)
(3,)