理解 NumPy 数组及其他数据结构的维度信息
在 Python(尤其是使用 NumPy 库时),shape 是一个描述数组维度的重要属性。它返回一个元组(tuple),表示每个维度的大小。
例如,一个 3 行 4 列的二维数组,其 shape 为 (3, 4)。
shape = ()[1, 2, 3],shape = (3,)shape = (2, 3)shape = (224, 224, 3)import numpy as np
# 创建不同维度的数组
scalar = np.array(42)
vector = np.array([1, 2, 3, 4])
matrix = np.array([[1, 2], [3, 4], [5, 6]])
tensor = np.random.rand(2, 3, 4)
print("标量 shape:", scalar.shape) # ()
print("向量 shape:", vector.shape) # (4,)
print("矩阵 shape:", matrix.shape) # (3, 2)
print("张量 shape:", tensor.shape) # (2, 3, 4)
理解 shape 对以下任务至关重要:
你可以使用 .reshape() 改变数组形状(元素总数不变):
arr = np.array([1, 2, 3, 4, 5, 6])
print(arr.shape) # (6,)
reshaped = arr.reshape(2, 3)
print(reshaped.shape) # (2, 3)
print(reshaped)
# [[1 2 3]
# [4 5 6]]