作为一个更大项目的组成部分,我正在编写一个小的二维卷积模型,用于在MNIST数据集上训练神经网络。
我的(经典)工作流程如下:
- 加载数据集并将其转换为
np array
- 将数据集拆分为训练集和验证集
- 重塑(
X_train.reshape(X.shape[0], 28, 28, 1)
)和独热编码(keras.utils.to_categorical(y_train, 10)
) - 获取模型
- 基于数据训练模型,并保存它
我的训练函数定义如下:
def train(model, X_train, y_train, X_val, y_val): model.fit_generator( generator=get_next_batch(X_train, y_train), steps_per_epoch=200, epochs=EPOCHS, validation_data=get_next_batch(X_val, y_val), validation_steps=len(X_val) ) return model
我使用的生成器如下:
def get_next_batch(X, y): # 将包含图像和标签 X_batch = np.zeros((BATCH_SIZE, 28, 28, 1)) y_batch = np.zeros((BATCH_SIZE, 10)) while True: for i in range(0, BATCH_SIZE): random_index = np.random.randint(len(X)) X_batch[i] = X[random_index] y_batch[i] = y[random_index] yield X_batch, y_batch
目前它确实能进行训练,但在最后几步时会卡住:
Using TensorFlow backend.Epoch 1/32018-04-18 19:25:08.170609: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA199/200 [============================>.] - ETA: 0s - loss:
而如果我不使用任何生成器:
def train(model, X_train, y_train, X_val, y_val): model.fit( X_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS, verbose=1, validation_data=(X_val, y_val) ) return model
它能完美运行。
显然我的get_next_batch
方法有问题,但我找不出原因。
任何帮助都将不胜感激!
回答:
问题在于你在生成器函数中创建了一个巨大的验证集。看看这些参数是如何传递的…
validation_data=get_next_batch(X_val, y_val), validation_steps=len(X_val)
假设你的BATCH_SIZE是1,000。那么你将拉取1,000张图像,并运行1,000次。
因此1,000 x 1,000 = 1,000,000。这就是通过你的网络运行的图像数量,这将花费很长时间。你可以将步骤改为评论中提到的静态数字,我只是认为一个解释会帮助你更好地理解这个问题。