【问题标题】:TypeError: Expected float32, got 'auto' of type 'str' insteadTypeError:预期的 float32,得到了 'str' 类型的 'auto'
【发布时间】:2021-10-14 17:55:03
【问题描述】:

我正在尝试使用 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.

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

【问题讨论】:

    标签: python numpy tensorflow keras deep-learning


    【解决方案1】:

    将您的自定义损失替换为:

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

    【讨论】:

      【解决方案2】:

      keras 手册的引用: “请注意,所有损失都可以通过类句柄和函数句柄获得。类句柄使您能够将配置参数传递给构造函数(例如 loss_fn = CategoricalCrossentropy(from_logits=True)),并且它们在使用时默认执行减少以独立的方式(请参阅下面的详细信息)。”

      [我也犯了同样的错误。]

      如果决定使用损失类 keras.losses.MeanSquaredLogarithmicError,则需要在模型中使用之前对其进行实例化。 另一方面,如果决定使用函数 keras.losses.mean_squared_logarithmic_error,它将被传递给模型本身。

      【讨论】:

        猜你喜欢
        • 2020-10-11
        • 2022-01-05
        • 1970-01-01
        • 2017-01-19
        • 2018-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多