栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/286123.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号