栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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) #  [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]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/739665.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号