翼度科技»论坛 编程开发 python 查看内容

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

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
numpy随机打乱数据方法np.random.shuffle
  1. import numpy as np
  2. #实验可得每次shuffle后数据都被打乱,这个方法可以在机器学习训练
  3. #的时候在每个epoch结束后将数据重新洗牌进入下一个epoch的学习
  4. num = np.arange(20)
  5. print(num)
  6. np.random.shuffle(num)
  7. print(num)
  8. num1 = np.arange(20)
  9. print(num1)
  10. np.random.shuffle(num1)
  11. print(num1)
  12. np.random.shuffle(num1)
  13. print(num1)
复制代码
  1. #打印输出:[ 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)之间的随机浮点数, 当没有参数时,返回一个随机浮点数,当有一个参数时,返回该参数长度大小的一维随机浮点数数组,参数建议是整数型。
  1. import numpy as np
  2. np.random.rand(8)
复制代码
  1. output [ 0.55958421 0.97358761 0.77753246 0.28072869 0.18467794 0.857553360.03976048 0.08161713]
复制代码
2、np.random.randn这个函数返回一个样本,具有标准正态分布。
  1. np.random.randn(8)
复制代码
  1. 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)。
  1. np.random.randint(10,size=10)
复制代码
  1. output [3 3 8 7 3 2 6 2 3 6]
复制代码
4、random_integers(low[, high, size]) 返回随机的整数,位于闭区间 [low, high]。
  1. np.random.random_integers(5)
复制代码
  1. output = 4
复制代码
5、 np.random.shuffle(x) 类似洗牌,打乱顺序;np.random.permutation(x)返回一个随机排列.
  1. arr = np.arange(10)
  2. np.random.shuffle(arr)
  3. print(arr)
  4. np.random.permutation(10)
复制代码
  1. 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的浮点数),并且第一个参数必须不大于第二个参数
  1. import random
  2. random.randint(1,10)
  3. random.randint(1.0,10.0)
复制代码
2、random.random() -> 不接受参数,返回一个[0.0, 1.0)之间的浮点数
  1. random.random()
复制代码
3、random.randrange(start, stop, step) -> 返回以start开始,stop结束,step为步长的列表中的随机整数,同样,三个参数均为整数(或者小数位为0),若start大于stop时 ,setp必须为负数.step不能是0
  1. random.randrange(1,100,2)  #返回[1,100]之间的奇数
  2. random.randrange(100,1,-2)  #返回[100,1]之间的偶数
复制代码
总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

来源:https://www.jb51.net/article/283833.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具