【发布时间】:2019-09-17 06:50:15
【问题描述】:
我正在使用定制的批处理生成器来尝试解决在使用标准 model.fit() 函数时形状不兼容的问题(BroadcastGradientArgs 错误),因为训练数据中最后一个批处理的大小很小。我使用提到的批处理生成器here 和 model.fit_generator() 函数:
class Generator(Sequence):
# Class is a dataset wrapper for better training performance
def __init__(self, x_set, y_set, batch_size=256):
self.x, self.y = x_set, y_set
self.batch_size = batch_size
self.indices = np.arange(self.x.shape[0])
def __len__(self):
return math.floor(self.x.shape[0] / self.batch_size)
def __getitem__(self, idx):
inds = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size] #Line A
batch_x = self.x[inds]
batch_y = self.y[inds]
return batch_x, batch_y
def on_epoch_end(self):
np.random.shuffle(self.indices)
但如果最后一批的大小小于提供的批量大小,它似乎会丢弃最后一批。如何更新它以包含最后一批并(例如)用一些重复的样本扩展它?
另外,不知何故,我不明白“A 线”的工作原理!
更新: 这是我在模型中使用生成器的方式:
# dummy model
input_1 = Input(shape=(None,))
...
dense_1 = Dense(10, activation='relu')(input_1)
output_1 = Dense(1, activation='sigmoid')(dense_1)
model = Model(input_1, output_1)
print(model.summary())
#Compile and fit_generator
model.compile(optimizer='adam', loss='binary_crossentropy')
train_data_gen = Generator(x1_train, y_train, batch_size)
test_data_gen = Generator(x1_test, y_test, batch_size)
model.fit_generator(generator=train_data_gen, validation_data = test_data_gen, epochs=epochs, shuffle=False, verbose=1)
loss, accuracy = model.evaluate_generator(generator=test_data_gen)
print('Test Loss: %0.5f Accuracy: %0.5f' % (loss, accuracy))
【问题讨论】:
标签: python keras deep-learning generator