【发布时间】:2018-04-18 17:39:05
【问题描述】:
作为一个更大项目的一部分,我正在编写一个小型卷积 2D 模型来在 MNIST 数据集上训练神经网络。
我的(经典)工作流程如下:
- 加载数据集并将其转换为
np array - 将数据集拆分为训练集和验证集
- 重塑 (
X_train.reshape(X.shape[0], 28, 28, 1)) 和 one_hot_encode (keras.utils.to_categorical(y_train, 10)) - 获取模型
- 根据数据训练并保存
我的 train 函数定义如下:
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):
# Will contains images and labels
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/3
2018-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 FMA
199/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_steps=2看看你是否可以通过那个阶段。 -
您绝对正确。
validation_steps的价值是多少?跟Keras2命名不同,不知道ot和nb_val_samples意思一样。 -
默认处理整个验证步骤。与训练集相比,您的验证集有多大?
-
80% 训练集
(48000, 10)和 20% 验证集(12000, 10)。 -
好吧,您可以耐心等待,也可以将它们设置为验证集大小的一半(我认为 6000 张图像应该足以让您逐个时期地进行估计以感受关于模型的进度)。
标签: python machine-learning keras generator mnist