[Python] numpy中的随机打乱数据方法np.random.shuffle解读

2025 0
Honkers 2023-5-13 14:11:51 | 显示全部楼层 |阅读模式
目录

    numpy随机打乱数据方法np.random.shufflenumpy随机生成数据问题
      用numpy.random模块来生成随机数组用random模块自己构造
    总结


numpy随机打乱数据方法np.random.shuffle

import numpy as np
#实验可得每次shuffle后数据都被打乱,这个方法可以在机器学习训练
#的时候在每个epoch结束后将数据重新洗牌进入下一个epoch的学习
num = np.arange(20)
print(num)
np.random.shuffle(num)
print(num)
num1 = np.arange(20)
print(num1)
np.random.shuffle(num1)
print(num1)
np.random.shuffle(num1)
print(num1)
#打印输出:
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
[ 1  5 19  9 14  2 12  3  6 18  4  8 16  0 10 17 13  7 15 11]
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
[ 2  4 13 14 11 17  9 19  5 12 15  7 18 16  3 10  1  8  0  6]
[ 8 11 13  6 19  7  9 12  4  3 10 14 15  2  1  0 17 18 16  5]

numpy随机生成数据问题


用numpy.random模块来生成随机数组

1.np.random.rand 用于生成[0.0, 1.0)之间的随机浮点数, 当没有参数时,返回一个随机浮点数,当有一个参数时,返回该参数长度大小的一维随机浮点数数组,参数建议是整数型。
import numpy as np
np.random.rand(8)
output [ 0.55958421 0.97358761 0.77753246 0.28072869 0.18467794 0.85755336
0.03976048 0.08161713]
2、np.random.randn这个函数返回一个样本,具有标准正态分布。
np.random.randn(8)
output [ 0.5512808 1.32780895 -0.95738756 0.93710414 -2.0854875 -0.5100787 n 0.40982079 -1.235186 ]
3、np.random.randint(low[, high, size]) 返回随机的整数,位于半开区间 [low, high)。
np.random.randint(10,size=10)
output [3 3 8 7 3 2 6 2 3 6]
4、random_integers(low[, high, size]) 返回随机的整数,位于闭区间 [low, high]。
np.random.random_integers(5)
output = 4
5、 np.random.shuffle(x) 类似洗牌,打乱顺序;np.random.permutation(x)返回一个随机排列.
arr = np.arange(10)
np.random.shuffle(arr)
print(arr)
np.random.permutation(10)
output[1 7 5 2 9 4 3 6 0 8 ]
array([1,7,4,3,0,9,2,5,8,6])

用random模块自己构造

1、random.randint(low, hight) -> 返回一个位于[low,hight]之间的整数。
该函数接受两个参数,这两个参数必须是整数(或者小数位是0的浮点数),并且第一个参数必须不大于第二个参数
import random
random.randint(1,10)
random.randint(1.0,10.0)2、random.random() -> 不接受参数,返回一个[0.0, 1.0)之间的浮点数
random.random()3、random.randrange(start, stop, step) -> 返回以start开始,stop结束,step为步长的列表中的随机整数,同样,三个参数均为整数(或者小数位为0),若start大于stop时 ,setp必须为负数.step不能是0
random.randrange(1,100,2) #返回[1,100]之间的奇数
random.randrange(100,1,-2) #返回[100,1]之间的偶数
总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持中国红客联盟。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

荣誉红客

关注
  • 4007
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行