用keras以TensorFlow作为后端重写相对熵函数,报错。。。
def KL(y_true, y_pred):weights = K.sum(K.cast(K.argmax(y_true, axis=1)*K.log(K.argmax(y_true, axis=1)/K.argmax(y_pred, axis=1)),dtype='float32'))return weights* losses.categorical_crossentropy(y_true, y_pred)
报错:
ValueError: Tensor conversion requested dtype int64 for Tensor with dtype float64: 'Tensor("loss/a
原因是因为:K.log(K.argmax(y_true, axis=1)/K.argmax(y_pred, axis=1))
进行log
计算时得到的数为‘float64’
,而K.argmax(y_true, axis=1)
得到的结果为int64
,所以将K.argmax(y_true, axis=1)
改为K.cast(K.argmax(y_true, axis=1),dtype='float64')
将int64
转变为‘float64’
正确代码为:相对熵函数
def KL(y_true, y_pred):weights = K.sum(K.cast(K.cast(K.argmax(y_true, axis=1),dtype='float64')*K.log(K.argmax(y_true, axis=1)/K.argmax(y_pred, axis=1)),dtype='float32'))return weights* losses.categorical_crossentropy(y_true, y_pred)