TypeError:“ Mul”操作的输入“ y”的类型为float32,与参数“ x”的int64类型不匹配

阿卡沙巴利

此代码后,我得到categoricalfocalloss中的错误,即时消息没有收到wheret64错误

def categorical_focal_loss(gamma=2., alpha=.25):
    def categorical_focal_loss_fixed(y_true, y_pred):
        y_pred /= K.sum(y_pred, axis=-1, keepdims=True)
        epsilon = K.epsilon()
        y_pred = K.clip(y_pred, epsilon, 1. - epsilon)
        y_pred = tf.cast(y_pred, dtype= tf.float32)
        cross_entropy = -y_true * K.log(y_pred)
        loss = alpha * K.pow(1 - y_pred, gamma) * cross_entropy
        return K.sum(loss, axis=1)
    return categorical_focal_loss_fixed

此代码中的模型描述,在损失类别中使用了焦点损失

    with strategy.scope():
        ef7 =tf.keras.Sequential()
        ef7.add(enet)
        ef7.add(tf.keras.layers.MaxPooling2D())
        ef7.add(tf.keras.layers.Conv2D(4096,3,padding='same'))
        ef7.add(tf.keras.layers.BatchNormalization())
        ef7.add(tf.keras.layers.ReLU())
        ef7.add(tf.keras.layers.GlobalAveragePooling2D())
        ef7.add(tf.keras.layers.Dropout(0.35))
        ef7.add(tf.keras.layers.Flatten())
    
        ef7.add(tf.keras.layers.Dense(2048,activation='relu'))
        ef7.add(tf.keras.layers.BatchNormalization())
        ef7.add(tf.keras.layers.LeakyReLU())
        ef7.add(tf.keras.layers.Dropout(0.35))
    
        ef7.add(tf.keras.layers.Dense(1024,activation='relu'))
        ef7.add(tf.keras.layers.BatchNormalization())
        ef7.add(tf.keras.layers.LeakyReLU())
        ef7.add(tf.keras.layers.Dropout(0.25))
        ef7.add(tf.keras.layers.Dense(3,activation='softmax'))
        ef7.compile(
                    optimizer=tf.optimizers.Adam(lr=0.0001),
                    loss=categorical_focal_loss(gamma=2., alpha=.25),
                    metrics=['categorical_accuracy',
                            tf.keras.metrics.Recall(),
                            tf.keras.metrics.Precision(),   
                            tf.keras.metrics.AUC(),
                            tfa.metrics.F1Score(num_classes=3, average="macro")
                           ])

在模型中,我在运行此模型时使用了分类焦点损失,在训练数据集中,我没有明白如何恢复原状

    h7=ef7.fit(
    train_dataset,
    steps_per_epoch=train_labels.shape[0] // BATCH_SIZE,
    callbacks=[lr_callback],
    epochs=EPOCHS)

错误被提及如下

        Epoch 1/20
    
    ```Epoch 00001: LearningRateScheduler reducing learning rate to 1e-05.```
    ---------------------------------------------------------------------------
    >TypeError                                 Traceback (most recent call last)
    <ipython-input-133-d27eee469b2b> in <module>()
          3     steps_per_epoch=train_labels.shape[0] // BATCH_SIZE,
          4     callbacks=[lr_callback],
    ----> 5     epochs=EPOCHS)
    
    9 frames
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
        975           except Exception as e:  # pylint:disable=broad-except
        976             if hasattr(e, "ag_error_metadata"):
    --> 977               raise e.ag_error_metadata.to_exception(e)
        978             else:
        979               raise
    
    TypeError: in user code:
    
        >/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:805 train_function  *
            >return step_function(self, iterator)
        ><ipython-input-68-de42355e464e>:7 categorical_focal_loss_fixed  *
            cross_entropy = -y_true * K.log(y_pred)
        >/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:1180 binary_op_wrapper
            >raise e
        >/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:1164 binary_op_wrapper
            >return func(x, y, name=name)
        >/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:1496 _mul_dispatch
            >return multiply(x, y, name=name)
        >/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
            return target(*args, **kwargs)
        >/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:518 multiply
            >return gen_math_ops.mul(x, y, name)
        >/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_math_ops.py:6078 mul
         >   "Mul", x=x, y=y, name=name)
        >/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:558 _apply_op_helper
         >   inferred_from[input_arg.type_attr]))
    
        >TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type int64 of argument 'x'.```

豆袋猫

错误指向以下代码行:

cross_entropy = -y_true * K.log(y_pred)

并从math_ops.pytensorflow包中的乘法函数抛出深入研究该文件,我找到了有关参数要求的摘要。

 Args:
    x: A Tensor. Must be one of the following types: `bfloat16`,
      `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`,
      `int16`, `int32`, `int64`, `complex64`, `complex128`.
    y: A `Tensor`. Must have the same type as `x`.
    name: A name for the operation (optional).
  Returns:
  A `Tensor`.  Has the same type as `x`.
  Raises:
   * InvalidArgumentError: When `x` and `y` have incompatible shapes or types

回顾错误

TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type int64 of argument 'x'.```

这意味着-y_trueis'x'K.log(y_pred)is 'y'要执行此操作,您必须将-y_true其强制转换为float32或K.log(y_pred)强制转换为int64或将它们都强制转换为任何其他类型,只要它们匹配即可。

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TypeError:“ float32”类型的对象不可JSON序列化

TypeError:内置操作的错误参数类型

TensorFlow TypeError:传递给参数输入的值的数据类型为uint8不在允许值列表中:float16,float32

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

如何修复MatMul Op的float64类型与float32 TypeError类型不匹配?

尝试将可选的Int64分配给字典键时,类型“ Int64”和“ _”不匹配

在Tensorflow tf.nn.nce_loss中获取TypeError:'Mul'Op的输入'y'具有类型float32与参数'x'的int32类型不匹配

TypeError:“ MatMul”操作的输入“ b”的类型为float32,与参数“ a”的int32类型不匹配

TypeError:“ float”类型的参数不可迭代

Word2Vec教程:Tensorflow TypeError:输入“ Mul”的“ y” Op的类型为float32,与参数“ x”的int32类型不匹配

TypeError:'MatMul'Op的输入'b'具有类型float32与参数'a'的int32类型不匹配-即使在转换后

TypeError:传递给参数'indices'的值的数据类型float32不在允许的值列表中:int32,int64

“ TypeError:“ ResourceApplyAdagradDA”操作的输入“ global_step”的类型为int32的类型与预期的int64类型不匹配。” 这是什么错误?

错误:传递给参数“输入”的值的DataType int64不在允许的值列表中:float16,bfloat16,float32,float64?

Mxnet数据类型为float64,但一直说它是float32

TypeError:int64类型的对象不可JSON序列化

理解Keras错误:TypeError:传递给参数'shape'的值的DataType float32不在允许的值列表中:int32,int64

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

TypeError:获取参数12434120.0具有无效的类型<class'numpy.float32'>,必须为字符串或Tensor。(在Tensorflow中)

TypeError:+ =:Python 3中不支持的操作数类型为“ float”和“ NoneType”

TypeError:DataType float32 for attr 'Tindices' 不在允许值列表中:int32、int64

Tensorflow TypeError: 'Switch' Op 的输入 'pred' 的类型 float32 与预期的 bool 类型不匹配

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

'MatMul' Op 的输入 'b' 的类型 float32 与参数 'a' 的类型 float64 不匹配

类型错误:传递给参数“输入”的值的数据类型 int64 不在允许值列表中:float16、bfloat16、float32、float64

'Equal' Op 的输入 'y' 的类型 bool 与参数 'x' 的 float32 类型不匹配

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

類型錯誤:“Sub”Op 的輸入“y”的類型為 float32,與參數“x”的類型 int64 不匹配

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