np.random.permutation()函数和np.shuffle()函数的使用

这篇博客介绍了在Python中如何使用np.random.permutation()和np.shuffle()函数进行随机排列。前者用于返回数组的一个排列,而后者直接在原数组上进行就地打乱。对于多维数组,permuation()会按维度打乱,而shuffle()则直接混合所有元素。通过示例展示了如何保持数据间的对应关系,并提供了针对一维和二维数组的代码示例。

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]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值