【python】从数组随机取数据

在神经网络中,经常会用到批量样本训练。我们需要从数组随机取数据,主要有以下几种方法:

1、np.random.shuffle:将原数组打乱


import numpy as np
 
array = np.random.randint(1,100,size=10)
#[63 32 80 33 61 45 28 55 39 80]
batch_size=5
print(array[0:batch_size])
#[63 32 80 33 61]
np.random.shuffle(rand_arr)
print(array[0:batch_size])
#[33 45 80 28 55]

#另一种写法
# rand_arr = np.arange(array.shape[0])
# np.random.shuffle(rand_arr)
# print(array[rand_arr[0:batch_size]]) 
# np.random.shuffle(rand_arr)
# print(array[rand_arr[0:5]])

2、np.random.choice:生成乱序的序号,从数据中取出(不改变原始序列)

import numpy as np
 
array = np.random.randint(1,100,size=10)
#[63 32 80 33 61 45 28 55 39 80]
batch_size=5
slice=np.random.choice(array.shape[0],batch_size)
print(array[slice])

这种方法其实就是生成输定数量的在某个范围内的随机数:

1、随机取多个数,random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。

import random
[random.randint(0,100) for _ in range(10)]

2、在固定列表中随机去多个数,random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。(这里的适用对象是列表类型的数据)

a=[0,1,2,3,4,5,6,7,8,9]
random.sample(a, 5)

 

  • 9
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值