【问题标题】:What does x=x[class_id] do when used on NumPy arraysx=x[class_id] 在 NumPy 数组上使用时有什么作用
【发布时间】:2018-02-01 18:37:41
【问题描述】:

我正在学习 Python 并解决机器学习问题。

class_ids=np.arange(self.x.shape[0])
np.random.shuffle(class_ids)
self.x=self.x[class_ids]

这是 NumPy 中的 shuffle 函数,但我无法理解 self.x=self.x[class_ids] 的含义。因为我认为它将数组的值赋予了一个变量。

【问题讨论】:

  • 在赋值语句前后打印self.x。它有什么作用?
  • 什么是self.x?你能展示它的初始化吗?
  • 代码的意图似乎是改组self.x,在这种情况下我假设np.random.shuffle(self.x)就足够了
  • 上面的代码是加载omniglot数据集的基本步骤,并尝试对其进行洗牌以进行训练或测试,而self.x是那些形状像self.x = np.reshape( self.x, newshape=(1622, 20, 28, 28, 1)) @PaulRooney

标签: python arrays numpy random shuffle


【解决方案1】:

洗牌self.x 的第一个维度是一种非常复杂的方法。例如:

>>> x = np.array([[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]])
>>> x
array([[1, 1],
       [2, 2],
       [3, 3],
       [4, 4],
       [5, 5]])

然后使用提到的方法

>>> class_ids=np.arange(x.shape[0])  # create an array [0, 1, 2, 3, 4]
>>> np.random.shuffle(class_ids)     # shuffle the array
>>> x[class_ids]                     # use integer array indexing to shuffle x
array([[5, 5],
       [3, 3],
       [1, 1],
       [4, 4],
       [2, 2]])

请注意,同样可以通过使用 np.random.shuffle 来实现,因为文档字符串明确提到:

此函数仅沿多维数组的第一个轴打乱数组。子数组的顺序改变了,但它们的内容保持不变。

>>> np.random.shuffle(x)
>>> x
array([[5, 5],
       [3, 3],
       [1, 1],
       [2, 2],
       [4, 4]])

或使用np.random.permutation:

>>> class_ids = np.random.permutation(x.shape[0])  # shuffle the first dimensions indices
>>> x[class_ids]
array([[2, 2],
       [4, 4],
       [3, 3],
       [5, 5],
       [1, 1]])

【讨论】:

    【解决方案2】:

    假设 self.x 是一个 numpy 数组:

    class_ids 是一维 numpy 数组,在表达式x[class_ids] 中用作integer array index。因为前一行洗牌了class_ids,所以x[class_ids] 计算结果为self.x 按行洗牌。 赋值self.x=self.x[class_ids]将洗牌后的数组赋值给self.x

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 2021-06-07
      • 1970-01-01
      • 2011-03-06
      相关资源
      最近更新 更多