我正在为具有自定义指标的多类分类问题(4 个类)开发 Keras 模型。问题是我无法为此模型开发自定义指标。当我运行模型时,指标的值为空。
这是我的模型:
nb_classes = 4
model = Sequential()
model.add(LSTM(
units=50,
return_sequences=True,
input_shape=(20,18),
dropout=0.2,
recurrent_dropout=0.2
)
)
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(units=nb_classes,
activation='softmax'))
model.compile(loss="categorical_crossentropy",optimizer='adadelta')
history = model.fit(np.array(X_train), y_train,
validation_data=(np.array(X_test), y_test),
epochs=50,
batch_size=2,
callbacks=[model_metrics],
shuffle=False,
verbose=1)
这是如何model_metrics定义的:
class Metrics(Callback):
def on_train_begin(self, logs={}):
self.val_f1s = []
self.val_recalls = []
self.val_precisions = []
def on_epoch_end(self, epoch, logs={}):
val_predict = np.argmax((np.asarray(self.model.predict(self.validation_data[0]))).round(), axis=1)
val_targ = np.argmax(self.validation_data[1], axis=1)
_val_f1 = metrics.f1_score(val_targ, val_predict, average='weighted')
_val_recall = metrics.recall_score(val_targ, val_predict, average='weighted')
_val_precision = metrics.precision_score(val_targ, val_predict, average='weighted')
self.val_f1s.append(_val_f1)
self.val_recalls.append(_val_recall)
self.val_precisions.append(_val_precision)
print(" — val_f1: %f — val_precision: %f — val_recall %f".format(_val_f1, _val_precision, _val_recall))
return
model_metrics = Metrics()
你可以看到val_f1: %f — val_precision: %f — val_recall %f。没有度量值。为什么?我究竟做错了什么?
相关分类