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