我有一个Keras模型,其输出包含3个类别(0, 1, 2):
model = Sequential() model.add(LSTM(100, input_shape=(n_time_steps,n_features))) model.add(Dropout(0.5)) model.add(Dense(100, activation='relu')) model.add(Dense(n_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
我希望评估模型在类别1和2上的精度,而不关心类别0。也就是说,如果模型在类别1和2上的误报数量最少,那么模型就是好的,我对类别0的表现并不在意。
如何在Keras中编写这样的度量标准?
回答:
创建一个函数,接受真实值和预测结果,并计算你的度量标准:
def false_positives(y_true, y_pred): negatives = 1 - y_true y_pred = K.cast(K.greater(y_pred, 0.5), K.floatx()) #round to 0 or 1 #如果不将y_pred四舍五入,它甚至可以作为损失函数使用 falsePositives = y_pred * negatives falsePositives1 = falsePositives[:,1] falsePositives2 = falsePositives[:,2] return something
使用 metrics = [false_positives]
,或 metrics=['accuracy', false_positives_1, false_positives_2]
等。