在神经网络中,经常会用到批量样本训练。我们需要从数组随机取数据,主要有以下几种方法:
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[slic

在神经网络训练中,从数组随机取样是常见的需求。本文介绍了两种方法:1. 使用`np.random.shuffle`直接打乱原数组并取前几个元素;2. 通过`np.random.choice`生成随机序号来获取数据,而不改变原始序列。同时,还提到了`random.randint`和`random.sample`在随机选取多个数中的应用。
最低0.47元/天 解锁文章

7731

被折叠的 条评论
为什么被折叠?



