我在寻找在TensorFlow中正确实现next_batch
的方法。我的训练数据是train_X=10000x50
,其中10000是样本数量,50是特征向量的数量,train_Y=10000x1
。我使用了128的批次大小。这是我在训练过程中获取训练批次的函数
def next_batch(num, data, labels): ''' 返回总共`num`个随机样本和标签。 ''' idx = np.arange(0 , data.shape[0]) np.random.shuffle(idx) idx = idx[:num] data_shuffle = [data[ i,:] for i in idx] labels_shuffle = [labels[ i] for i in idx] return np.asarray(data_shuffle), np.asarray(labels_shuffle)n_samples = 10000batch_size =128with tf.Session() as sess:sess.run(init)n_batches = int(n_samples / batch_size)for i in range(n_epochs): for j in range(n_batches): X_batch, Y_batch = next_batch(batch_size,train_X,train_Y)
使用上述函数,我发现shuffle
函数在每个批次都被调用,这不是我们想要的行为。我们必须在再次洗牌之前扫描训练数据中所有已洗牌的元素以开始新的epoch。我的理解正确吗?如何在TensorFlow中修复这个问题?谢谢
回答:
一个解决方案是使用生成器来生成你的批次,以便跟踪采样状态(洗牌索引列表和你在该列表中的当前位置)。
请看下面的解决方案,你可以在此基础上构建。
def next_batch(num, data, labels): ''' 返回最多`num`个随机样本和标签。 注意:最后一个批次的大小将是len(data) % num ''' num_el = data.shape[0] while True: # 或者你可能有的任何条件 idx = np.arange(0 , num_el) np.random.shuffle(idx) current_idx = 0 while current_idx < num_el: batch_idx = idx[current_idx:current_idx+num] current_idx += num data_shuffle = [data[ i,:] for i in batch_idx] labels_shuffle = [labels[ i] for i in batch_idx] yield np.asarray(data_shuffle), np.asarray(labels_shuffle)n_samples = 10000batch_size =128with tf.Session() as sess: sess.run(init) n_batches = int(n_samples / batch_size) next_batch_gen = next_batch(batch_size, train_X, train_Y) for i in range(n_epochs): for j in range(n_batches): X_batch, Y_batch = next(next_batch_gen) print(Y_batch)