类型错误:预期为 float32,而是得到了类型为 'str' 的 'auto'

匿名我

我正在尝试使用 Keras 的函数式 API 来处理多个输入,并使用自定义损失函数 RMSLE。下面是我的代码:

import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras import backend as K
from tensorflow.keras.losses import MeanSquaredLogarithmicError

def rmsle(y_true, y_pred):
  return K.sqrt(MeanSquaredLogarithmicError(y_true, y_pred))

def build_model():

  i_language = Input(shape=(1,))
  i_year = Input(shape=(1,))
  i_abstract = Input(shape=(100,))

  input = concatenate([i_language, i_year, i_abstract])
  x = Dense(64)(input)
  x = Dense(1, activation='softmax')(x)

  model = Model(inputs=[i_language, i_year, i_abstract], outputs=x)
  model.compile(optimizer = 'adam', loss = rmsle)

  return model

model = build_model()

x1 = np.random.randint(3, size=(100, 1)).astype('float32')
x2 = np.random.randint(59, size=(100, 1)).astype('float32')
x3 = np.random.randn(100, 100)

y = np.random.rand(100,1)

model.fit([x1,x2,x3], y)

其中 x1,x2,x3 都是样本输入,y 是样本输出。但是,他的最后一行 model.fit()抛出了错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-33-66ea59ad4aed> in <module>()
      5 y = np.random.rand(100,1)
      6 
----> 7 model.fit([x1,x2,x3], y)

9 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    984           except Exception as e:  # pylint:disable=broad-except
    985             if hasattr(e, "ag_error_metadata"):
--> 986               raise e.ag_error_metadata.to_exception(e)
    987             else:
    988               raise

TypeError: in user code:

    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:855 train_function  *
        return step_function(self, iterator)
    <ipython-input-17-6a742f71a83b>:2 rmsle  *
        return K.sqrt(MeanSquaredLogarithmicError(y_true, y_pred))
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/losses.py:506 __init__  **
        mean_squared_logarithmic_error, name=name, reduction=reduction)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/losses.py:241 __init__
        super(LossFunctionWrapper, self).__init__(reduction=reduction, name=name)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/losses.py:102 __init__
        losses_utils.ReductionV2.validate(reduction)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/utils/losses_utils.py:76 validate
        if key not in cls.all():
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper
        return target(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/math_ops.py:1800 tensor_equals
        self, other = maybe_promote_tensors(self, other)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/math_ops.py:1202 maybe_promote_tensors
        ops.convert_to_tensor(tensor, dtype, name="x"))
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/profiler/trace.py:163 wrapped
        return func(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py:1566 convert_to_tensor
        ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py:339 _constant_tensor_conversion_function
        return constant(v, dtype=dtype, name=name)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py:265 constant
        allow_broadcast=True)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py:283 _constant_impl
        allow_broadcast=allow_broadcast))
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_util.py:457 make_tensor_proto
        _AssertCompatible(values, dtype)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_util.py:337 _AssertCompatible
        (dtype.name, repr(mismatch), type(mismatch).__name__))

    TypeError: Expected float32, got 'auto' of type 'str' instead.

我以前没有遇到过这个错误,不明白发生了什么。有人可以帮我摆脱这个错误吗?

玛丽亚姆·巴赫拉米

用以下方法重新补偿您的自定义损失:

def rmsle(y_true, y_pred):
  msle = MeanSquaredLogarithmicError()
  return K.sqrt(msle(y_true, y_pred))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Pycharm预期类型'optional [bytes]'改为'str'

TypeError:Fetch参数的类型类型为float32,必须为字符串或Tensor

类型的非法开始,<identifier>预期为“;” 预期错误

django-“类型错误。预期的pk值,收到了str”错误

错误:(116)错误:类型为[ResourceType]的预期资源

预期的类型为“ str”,取而代之的是“ CharField”

mypy错误:分配中的类型不兼容(表达式的类型为“ List [str]”,变量的类型为“ str”)

'字符串'具有错误的类型(预期的str,得到了spacy.tokens.doc.Doc)

类型错误:序列项0:预期的str实例,找到了段落

RuntimeError:预期的标量类型为Long,但找到了Float

重用类型为auto的变量

TypeError:“ ReadFile”操作的输入“ filename”的类型为float32,与预期的字符串类型不匹配

预期“属性”为字符串类型,而是找到了类型对象-Dynamoose

VSCode MyPy错误:“ ioctl”具有不兼容的类型“ my_struct”;预期为“ Union [int,str]”

未捕获的错误:预期值为'FutureOr <UserCredentialJsImpl>',但是得到的类型为'MemoryInfo'

Rust错误预期类型为()的类型为(i32,i32)

fluter错误预期值为'Map <dynamic,dynamic>'类型的值,但得到了'List <dynamic>'类型的值之一

当函数只能返回str时,mypy抱怨返回值类型不兼容(得到“ Optional [str]”,预期为“ str”)

错误:预期为类型,得到了分配器

Pycharm:预期类型为“ Integral”,取而代之的是“ str”

Python:类型错误:预期的 str、bytes 或 bytearray,而不是 int

类型错误:应为 float32,得到 () 类型为“complex”

休息调用给出错误:类型不正确。预期pk值,收到str

类型错误:预期的 str、bytes 或 os.PathLike 对象,而不是方法

类型错误:预期的 str、bytes 或 os.PathLike 对象,而不是 FileStorage 不断弹出

Python 类自值错误,预期类型“str”得到了 Tuple[str],而 azure ClientSecretCredential

mypy(错误):赋值中的类型不兼容(表达式类型为“Dict[<nothing>, <nothing>]”,目标类型为“List[str]”)

类型错误:无法使用这些类型为 str 的索引器 [stuff] 对 DatetimeIndex 进行位置索引

面对这个错误:-TypeError:不支持的操作数类型为-:'str'和'float'?