如何在TensorFlow自定义数据集中正确实现next_batch?

我在寻找在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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注