理解 -1 在 Numpy Reshape 中的作用
在 Numpy 中,reshape() 方法允许对数组形状进行转换。使用 2D 数组时,可以使用 reshape(-1) 将它们重塑为 1D 数组。例如:
import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) a.reshape(-1) # Output: array([[1, 2, 3, 4, 5, 6, 7, 8]])
通常,array[-1]表示数组中的最后一个元素。然而,在 reshape(-1) 的上下文中,这具有不同的含义。
Reshape 中的 -1 参数
reshape(- 1) 用作通配符维度。这表明新形状的相应尺寸应自动确定。这是通过满足新形状必须与原始数组形状对齐并保留其线性维度的标准来完成的。
Numpy 允许在形状参数之一中使用 -1,从而能够指定未知维度。例如,(-1, 3) 或 (2, -1) 是有效形状,而 (-1, -1) 则不是。
重塑 (-1) 示例
考虑以下数组:
z = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) z.shape # (3, 4)
使用 (-1) 重塑:
z.reshape(-1) # Output: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # New shape: (12,)
使用 (-1, 1) 重塑(单一特征):
z.reshape(-1, 1) # Output: array([[ 1], [ 2], [ 3], [ 4], [ 5], [ 6], [ 7], [ 8], [ 9], [10], # [11], [12]]) # New shape: (12, 1)
使用 (-1, 2) 重塑(单行):
z.reshape(1, -1) # Output: array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]) # New shape: (1, 12)
使用 (2, -1) 重塑:
z.reshape(2, -1) # Output: array([[ 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12]]) # New shape: (2, 6)
使用 (3, -1) 重塑 (原始形状):
z.reshape(3, -1) # Output: array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # New shape: (3, 4)
注意,将两个维度指定为-1,即(-1, -1),会导致错误。
通过理解意义reshape() 中的 -1 时,开发人员可以有效地转换数组形状,以满足他们在 Numpy 中的特定数据处理需求。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3