这是我在用keras做神经网络自定义损失函数loss时遇到的问题,出现问题的代码如下:
import tensorflow as tf
from sklearn import datasets
import numpy as np
from keras import backend as K
x_train = datasets.load_iris().data
y_train = datasets.load_iris().target
np.random.seed(116)
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2())
])
def my_loss(y_true, y_pred):
return K.mean((y_pred - y_true), axis=-1)
model.compile(optimizer='adam',
loss=my_loss,
metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=500, validation_split=0.2, validation_freq=20)
print(model.predict(x_train)[0])
model.summary()
运行结果如下:
解决方案:
方案一:出现这个问题可能是因为tensorflow的版本为2.0及以上导致的,降低tensorflow的版本即可,在终端敲入:
pip install tensorflow==1.15
方案二:根据报错的内容可知,该错误是y_pred - y_true的数据类型不同导致的,y_pred的类型是float32,而y_true的类型是int32。对于上述代码来说,y_true是原先鸢尾花的分类数据,包含1、2、3,都是int32型的数据,因此只要将y_true转化为float32型的数据即可,具体操作时将下列代码片:
def my_loss(y_true, y_pred):
return K.mean((y_pred - y_true), axis=-1)
替换为:
def my_loss(y_true, y_pred):
y_true = tf.cast(y_true, dtype=tf.float32)
return K.mean((y_pred - y_true), axis=-1)
再运行可以看到不再报错: