Keras自定义损失函数:ValueError:没有为任何变量提供渐变

时间:2020-09-16 03:55:37

标签: tensorflow keras

我具有以下自定义tf函数:

import tensorflow as tf

@tf.function
def top10_accuracy_scorer(y_true, y_pred):

    values, indeces = tf.math.top_k(y_pred, 10)
    lab_indeces_tensor = tf.argmax(y_true,1)
    lab_indeces_tensor = tf.reshape(lab_indeces_tensor, 
                                    shape=(tf.shape(lab_indeces_tensor)[0],1))
    lab_indeces_tensor = tf.dtypes.cast(lab_indeces_tensor,dtype=tf.int32)
    equal_tensor = tf.equal(lab_indeces_tensor, indeces)
    
    sum_tensor = tf.reduce_sum(tf.cast(equal_tensor, tf.float32))
    top10_accuracy = sum_tensor/tf.cast(tf.shape(lab_indeces_tensor)[0], tf.float32)
    
    return top10_accuracy

它可以很好地用作模型中的指标,但是当我尝试将其用作损失函数时,出现错误:ValueError: No gradients provided for any variable。显然,它的某些部分是不可区分的,但是我无法弄清楚如何解决它。任何帮助表示赞赏。

工作示例:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

X_temp = np.random.uniform(0,1,(1000,100))
y_temp = np.random.uniform(0,1,(1000,10))
y_temp = np.argmax(y_temp, axis=1)
y_temp = tf.keras.utils.to_categorical(y_temp)

model = Sequential()
model.add(Dense(y_temp.shape[1], input_shape = (X_temp.shape[1],), activation='softmax'))
model.compile(optimizer='adam',
              loss=top10_accuracy_scorer,
              metrics=['accuracy'])
model.fit(X_temp, y_temp)

0 个答案:

没有答案