这是我有史以来第一个发布在StackOverflow上的问题,请耐心等待,让我知道我是否应该以某种方式改进我的问题:)
假设我要为每个类计算一个单独的指标值。是否可以在Keras的Tensorflow实现中使用自定义度量标准函数来输出非标量张量?例如:我有一个自定义指标函数balanced_accuracy_per_class
,它返回形状为(1, 4)
的张量,并将其馈送到compile
方法中,如下所示:
# Define some dummy data:
train_data = tf.constant([
[0.2, 0.5, 0.1, 0.0, 5.2, 6.3],
[0.4, 0.1, 0.8, 0.4, 6.4, 7.5],
])
train_labels = tf.constant([
[1., 0., 0., 0.],
[0., 1., 1., 0.],
])
val_data = tf.constant([
[0.3, 0.4, 0.2, 0.1, 2.2, 4.3],
[3.4, 3.1, 2.8, 1.4, 2.4, 5.5],
])
val_labels = tf.constant([
[0., 1., 0., 1.],
[1., 0., 0., 0.],
])
# Example dummy implementation.
def balanced_accuracy_per_class(y_true, y_pred):
return tf.constant([0.0, 0.2, 0.4, 0.6])
sgd = tf.keras.optimizers.SGD(lr=0.1, decay=0.000225, momentum=0.5)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(4, input_shape=(6, )))
model.add(tf.keras.layers.Activation('sigmoid'))
model.compile(optimizer='rmsprop',
loss='mse',
metrics=[balanced_accuracy_per_class])
model.fit(train_data, train_labels, epochs=3, steps_per_epoch=1)
evaluation_results = model.evaluate(val_data, val_labels, steps=1)
在培训和评估阶段,进度条都将度量输出为标量(具体为0.3):
Epoch 1/3
1/1 [==============================]-0s 81ms / step-损耗:0.2392-balance_accuracy_per_class: 0.3000
第2/3集
1/1 [==============================]-0s 0s / step-损失:0.2367-balance_accuracy_per_class: 0.3000
第3/3版
1/1 [==============================]-0s 997us / step-损耗:0.2350-balance_accuracy_per_class: 0.3000
1/1 [==============================]-0s 53ms / step-损耗:0.4557-balance_accuracy_per_class: 0.3000
我想实现的是model.evaluate
返回给定指标的数组而不是标量。
模型的evaluate function的文档字符串明确提到“标量或标量列表”,但也许我遗漏了什么?
谢谢!