Tensorflow Keras自定义损失函数:ValueError:没有为任何变量提供梯度
我有以下自定义tf函数:Tensorflow Keras自定义损失函数:ValueError:没有为任何变量提供梯度,tensorflow,keras,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,
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:没有为任何变量提供梯度。显然,它的某些部分是不可微的,但我不知道如何解决它。感谢您的帮助
工作示例:
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)