当前位置: 代码迷 >> 综合 >> ValueError: Tensor conversion requested dtype int64 for Tensor with dtype float64: ‘Tensor(“loss/a
  详细解决方案

ValueError: Tensor conversion requested dtype int64 for Tensor with dtype float64: ‘Tensor(“loss/a

热度:90   发布时间:2023-12-18 02:52:13.0

用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)
  相关解决方案