上一篇介绍了如何取随机batch,这一篇介绍的方法是先随机打乱数据,再按顺序一个一个batch的取。
def shuffle_set(train_image, train_label, test_image, test_label):
train_row = range(len(train_label))
random.shuffle(train_row)
train_image = train_image[train_row]
train_label = train_label[train_row]
test_row = range(len(test_label))
random.shuffle(test_row)
test_image = test_image[test_row]
test_label = test_label[test_row]
return train_image, train_label, test_image, test_label
def get_batch(image, label, batch_size, now_batch, total_batch):
if now_batch < total_batch-1:
image_batch = image[now_batch*batch_size:(now_batch+1)*batch_size]
label_batch = label[now_batch*batch_size:(now_batch+1)*batch_size]
else:
image_batch = image[now_batch*batch_size:]
label_batch = label[now_batch*batch_size:]
return image_batch, label_batch
使用时在每个epoch开始时先调用shuffle_set函数打乱数据,再在每个batch时选取一个batch的数据训练。