简单的自定义Keras度量函数存在问题无法返回Argmax吗? [英] Trouble With Simple Custom Keras Metric Function Can't Return Argmax?

查看:144
本文介绍了简单的自定义Keras度量函数存在问题无法返回Argmax吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个自定义指标,并且我了解到在一个自定义函数中,所有东西都是张量,我需要使用特殊的后端函数.为了解决这个问题,我尝试了一个三类分类问题示例,在该示例中,我仅将argmax返回为自定义函数

I'd like to create a custom metric and I've learned that within a custom function everything is a tensor and I need to use the special backend functions. To wrap my head around this I tried a three class classification problem example where I simply return the argmax as the custom function

def custom(y_true, y_pred):
    return K.argmax(y_pred)

# Neural Network
model = models.Sequential()
model.add(keras.layers.Embedding(len(np.unique(X.values)), 4)) 
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation='relu'))
model.add(keras.layers.Dense(3, activation='softmax'))
model.compile(optimizer='rmsprop',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy', custom])

model.fit(X_train.values, y_train.values, epochs=4)

令我惊讶的是,我在输出中得到浮点值!

To my surprise I'm getting floating point values in the output!

Epoch 1/4
1023/1023 [==============================] - 0s 276us/step - loss: 0.3560 - acc: 0.3294 - custom: 1.1867
Epoch 2/4
1023/1023 [==============================] - 0s 52us/step - loss: 0.3368 - acc: 0.3343 - custom: 1.9687
Epoch 3/4
1023/1023 [==============================] - 0s 47us/step - loss: 0.3225 - acc: 0.3324 - custom: 1.9374
Epoch 4/4
1023/1023 [==============================] - 0s 47us/step - loss: 0.3173 - acc: 0.3275 - custom: 1.2825

这显然没有达到我的预期,我也不知道为什么

This clearly isn't doing what I expected and I don't know why

问题:为什么我的仅返回argmax的自定义指标没有返回表示argmax的整数向量,而是返回了浮点数?

PS:我修改了自定义功能以打印

PS: I modified the custom function to print

def custom(y_true, y_pred):
    x = K.argmax(y_pred)
    x = K.print_tensor(x, message="x is: ")
    return(x)

我得到这样的输出

Epoch 4/4
x is: [2 2 0...]
  32/1023 [..............................] - ETA: 0s - loss: 0.3113 - acc: 0.2500 - custom: 1.0000x is: [2 0 0...]
x is: [0 0 0...]
x is: [0 0 0...]
x is: [2 0 2...]

这又对我没有任何意义.有人知道引擎盖下发生了什么吗?

Which again isn't making any sense to me. Does anyone know what's happening under the hood?

推荐答案

argmax函数正常运行.对于每个批次,argmax返回一个整数.但是整个批次的度量函数的输出将是该批次的平均值. Keras 文档

argmax function is working correctly. For each batch argmax is returning an integer. But the output of the metric function for the whole batch will be mean of the batch. Keras documentation says

返回
单个张量值表示输出数组的平均值 所有数据点.

Returns
Single tensor value representing the mean of the output array across all datapoints.

因此,如果您的自定义指标函数返回某些批次的某些类值数组,则模型将计算这些值的平均值.

So if your custom metric function is returning some arrays of class values for certain batch, the model will calculate the average of these values.

这篇关于简单的自定义Keras度量函数存在问题无法返回Argmax吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆