Permutation:(一组事物可能的一种) 序列,排列,排列中的任一组数字或文字;
这个函数的使用来随机排列一个数组的,第一个例子如图1所示:

对多维数组来说,是多维随机打乱而不是1维,例如:
第一次运行结果(代码在左侧),如图2所示:

第二次运行结果(代码在左侧),如图3所示:

如果要利用次函数对输入数据X、Y进行随机排序,且要求随机排序后的X Y中的值保持原来的对应关系,可以这样处理:
permutation = list(np.random.permutation(m)) #m为样本数
shuffled_X = X[permutation]
shuffled_Y = Y[permutation].reshape((1,m))
图4中的代码是针对一维数组来说的,(图片中右侧为运行结果):

图5中的代码是针对二维数组来说的,(图片中右侧为运行结果):

代码示例:
# permutation()函数使用示例
def testPermutation():
print("==================打乱数组元素的顺序==================")
x = np.arange(10).reshape(5, 2)
print("原数组:")
print(x)
x_permutation = np.random.permutation(x)
print("打乱后的数组:")
print(x_permutation)
print("\n==================对应打乱2个数组元素的顺序==================")
print("原数组:")
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 0, 1, 0, 1, 0, 1, 0, 1, 0])
print(x)
print(y)
m = 10 # 元素个数
permutation_array = np.random.permutation(m) # <class 'numpy.ndarray'> [0 7 3 2 1 8 4 6 5 9]
permutation = list(permutation_array) # [0, 7, 3, 2, 1, 8, 4, 6, 5, 9]
shuffled_X = x[permutation]
shuffled_Y = y[permutation]
print("打乱后的数组:")
print(shuffled_X) # [0 7 3 2 1 8 4 6 5 9]
print(shuffled_Y) # [1 0 0 1 0 1 1 1 0 0]
运行结果:
**加粗样式**==================打乱数组元素的顺序==================
原数组:
[[0 1]
[2 3]
[4 5]
[6 7]
[8 9]]
打乱后的数组:
[[8 9]
[2 3]
[4 5]
[6 7]
[0 1]]
==================对应打乱2个数组元素的顺序==================
原数组:
[0 1 2 3 4 5 6 7 8 9]
[1 0 1 0 1 0 1 0 1 0]
打乱后的数组:
[5 7 4 9 8 0 3 1 2 6]
[0 0 1 0 1 1 0 0 1 1]
shuffle()函数使用示例:
shuffle() 方法将序列的所有元素随机排序
# shuffle函数使用示例:
def testShuffle():
list = [20, 16, 10, 5]
np.random.seed(12)
np.random.shuffle(list)
print("随机排序列表 : ", list)
np.random.seed(12)
np.random.shuffle(list)
print("随机排序列表 : ", list)
**运行结果:**
随机排序列表 : [20, 16, 10, 5]
随机排序列表 : [20, 16, 10, 5]
这篇博客介绍了在Python中如何使用np.random.permutation()和np.shuffle()函数进行随机排列。前者用于返回数组的一个排列,而后者直接在原数组上进行就地打乱。对于多维数组,permuation()会按维度打乱,而shuffle()则直接混合所有元素。通过示例展示了如何保持数据间的对应关系,并提供了针对一维和二维数组的代码示例。
1201

被折叠的 条评论
为什么被折叠?



