x=x[class_id] 在 NumPy 数组上使用时有何作用
What does x=x[class_id] do when used on NumPy arrays
我正在学习 Python 并正在解决机器学习问题。
class_ids=np.arange(self.x.shape[0])
np.random.shuffle(class_ids)
self.x=self.x[class_ids]
这是 NumPy 中的随机播放函数,但我不明白 self.x=self.x[class_ids]
是什么意思。因为我认为它把数组的值赋给了一个变量。
假设self.x
是一个numpy数组:
class_ids
是一维 numpy 数组,在表达式中用作 integer array index:x[class_ids]
。因为前一行打乱 class_ids
,x[class_ids]
计算结果为 self.x
按行打乱。
赋值 self.x=self.x[class_ids]
将打乱后的数组赋值给 self.x
打乱 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
即可实现同样的效果,因为文档字符串明确提到:
This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same.
>>> np.random.shuffle(x)
>>> x
array([[5, 5],
[3, 3],
[1, 1],
[2, 2],
[4, 4]])
>>> 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]])
我正在学习 Python 并正在解决机器学习问题。
class_ids=np.arange(self.x.shape[0])
np.random.shuffle(class_ids)
self.x=self.x[class_ids]
这是 NumPy 中的随机播放函数,但我不明白 self.x=self.x[class_ids]
是什么意思。因为我认为它把数组的值赋给了一个变量。
假设self.x
是一个numpy数组:
class_ids
是一维 numpy 数组,在表达式中用作 integer array index:x[class_ids]
。因为前一行打乱 class_ids
,x[class_ids]
计算结果为 self.x
按行打乱。
赋值 self.x=self.x[class_ids]
将打乱后的数组赋值给 self.x
打乱 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
即可实现同样的效果,因为文档字符串明确提到:
This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same.
>>> np.random.shuffle(x)
>>> x
array([[5, 5],
[3, 3],
[1, 1],
[2, 2],
[4, 4]])
>>> 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]])