在Python我想打乱数据集的标签来生成噪声数据,但是我使用np.random.shuffle这个函数发现打乱仍有部分标签与打乱前相同,要怎么才能让每个样本的标签与打乱前都不同呢?
不知道你这个问题是否已经解决, 如果还没有解决的话:功能
给定一个数组或list,打乱顺序(同permutation)
接口
Docstring:
shuffle(x)
Modify a sequence in-place by shuffling its contents.
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.
Parameters
----------
x : array_like
The array or list to be shuffled.
Returns
-------
None
实例
In [32]: x = np.arange(1,7)
In [33]: x
Out[33]: array([1, 2, 3, 4, 5, 6])
In [34]: np.random.shuffle(x)
In [35]: x
Out[35]: array([4, 1, 6, 3, 5, 2])
我可以给出一个解决方案。在使用np.random.shuffle()打乱标签之前,我们可以首先生成一个随机排列数组,并将其用作索引来打乱数据集和标签。这样可以确保每个样本的标签与打乱前都不同。具体步骤如下:
1.从numpy导入random模块
2.生成一个随机排列的数组,该数组的长度与标签数组相同,其中元素为0到标签数组长度减1的整数序列的随机排列。可以使用random.permutation()方法来生成这个数组。
3.将生成的随机排列数组用作索引来打乱数据集和标签,可以使用numpy的fancy indexing功能。
这里是一个代码示例:
import numpy as np
# 假设标签数组为labels,数据集为dataset
# 生成随机排列的数组
idx = np.random.permutation(len(labels))
# 使用fancy indexing打乱数据集和标签
shuffled_dataset = dataset[idx]
shuffled_labels = labels[idx]
使用以上代码可以保证每个样本的标签与打乱前都不同。