TypeError: Input ‘y‘ of ‘Sub‘ Op has type int32 that does not match type float32 of argument ‘x‘.

这是我在用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)

再运行可以看到不再报错:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值