【问题标题】:Why am I having this error? TypeError: Failed to convert object of type <class 'tensorflow.python.keras.losses.BinaryCrossentropy'> to Tensor为什么我有这个错误? TypeError:无法将 <class 'tensorflow.python.keras.losses.BinaryCrossentropy'> 类型的对象转换为张量
【发布时间】:2020-09-28 19:12:10
【问题描述】:

我正在 Google Colab 上练习密集神经网络,在执行 model.fit 时出现此错误。

这是整个代码:

我从 Google 驱动器导入了我的数据,并能够将数据传递给 panda。

import functools

import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras

from google.colab import drive

drive.mount('/content/drive')
train_file_path =  "/content/drive/My Drive/Colab Notebooks/1111_train.csv"
test_file_path  =  "/content/drive/My Drive/Colab Notebooks/1111_test.csv"

df_train = pd.read_csv(train_file_path)
df_test = pd.read_csv(test_file_path)

然后我切片以创建张量切片

train_target = df_train.pop('22')
test_target = df_test.pop('22')

train_dataset = tf.data.Dataset.from_tensor_slices((df_train.values, train_target.values))
test_dataset = tf.data.Dataset.from_tensor_slices((df_test.values, test_target.values))


在这之后,我建立了我的模型

model = tf.keras.Sequential([
    tf.keras.layers.Dense(22, activation='relu'),
    tf.keras.layers.Dense(10, activation='relu'),
    tf.keras.layers.Dense(1)])

model.compile(optimizer='adam',
                loss = tf.keras.losses.BinaryCrossentropy,
                metrics=['accuracy'])

model.fit(train_dataset, epochs=15)

这是运行 model.fit 时的全部错误消息。

WARNING:tensorflow:Layer dense_6 is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2.  The layer has dtype float32 because it's dtype defaults to floatx.

If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.

To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-d6feee4cfcc8> in <module>()
----> 1 model.fit(train_dataset, epochs=15)

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

TypeError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:533 train_step  **
        y, y_pred, sample_weight, regularization_losses=self.losses)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/compile_utils.py:205 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:145 __call__
        losses, sample_weight, reduction=self._get_reduction())
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/utils/losses_utils.py:104 compute_weighted_loss
        losses = ops.convert_to_tensor_v2(losses)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:1283 convert_to_tensor_v2
        as_ref=False)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:1341 convert_to_tensor
        ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py:321 _constant_tensor_conversion_function
        return constant(v, dtype=dtype, name=name)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py:262 constant
        allow_broadcast=True)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py:300 _constant_impl
        allow_broadcast=allow_broadcast))
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor_util.py:547 make_tensor_proto
        "supported type." % (type(values), values))

    TypeError: Failed to convert object of type <class 'tensorflow.python.keras.losses.BinaryCrossentropy'> to Tensor. Contents: <tensorflow.python.keras.losses.BinaryCrossentropy object at 0x7f76215279b0>. Consider casting elements to a supported type.

【问题讨论】:

  • 你错过了括号... tf.keras.losses.BinaryCrossentropy()

标签: python pandas tensorflow keras deep-learning


【解决方案1】:

没关系。我找到了解决办法。

我只是改变了model.compile上的损失函数

model.compile(optimizer='adam',
                loss = tf.keras.losses.binary_crossentropy,
                metrics=['accuracy'])

【讨论】:

    【解决方案2】:

    或者你可以试试这个

    model.compile(optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy'])
    

    Tensorflow 对象--->

    print(type(tf.keras.losses.BinaryCrossentropy()))
    # <class 'tensorflow.python.keras.losses.BinaryCrossentropy'>
    
    print(type(tf.keras.losses.BinaryCrossentropy))
    # <class 'type'>
    

    定义是什么意思,代码错误?

    当你调用loss函数末尾没有'()'时;它是一个可能出生的未出生或未调用的类,它是一个“类型”。

    如您所知,对象是 Python 中最重要的东西。一切都有一个类型,因此;类型是类中最重要的东西。

    对象 = 上帝 = 宇宙 > 地球 > PC > Python >= python3.6 >

    对象 >= 类型 >= 类 > 方法 > 函数

    print(tf.keras.losses.BinaryCrossentropy().__class__)
    # <class 'tensorflow.python.keras.losses.BinaryCrossentropy'>
    
    print(tf.keras.losses.BinaryCrossentropy.__class__)
    # <class 'type'>
    

    但是我们可以在未调用的类中独立使用函数,也可以在调用该类后使用函数(如果存在)。注意这里的方法>函数

    class Foo:
        def foo(self):
            a = 5
            return a
    
    print(type(Foo.foo))
    # <class 'function'>
    
    print(type(Foo().foo))
    # <class 'method'>
    

    如果在函数末尾添加'()',则返回此函数的结果

    print(type(Foo().foo()))
    # <class 'int'>
    

    【讨论】:

    • 那是我的问题。调用fit()时,使用tf.keras.losses.LOSS()还是tf.keras.losses.LOSS无所谓; TF 为您服务。然而,当我对生成器使用完全相同的代码时,我得到了异常。添加()解决了这个问题。谢谢!
    【解决方案3】:

    对我来说,我收到了类似的错误,问题是在一行我使用了损失而没有设置必要的两个参数,即:真实标签y_real 和预测y_pred

    解决方案是通过调用损失函数并传递两个参数来计算损失,然后使用计算值。

    换句话说,这是解决错误之前的代码:

    grads = tape.gradient (train_loss, model.trainable_variables)
    

    这是解决问题后的代码:

    loss = train_loss(y, predictions)
    grads = tape.gradient (loss, model.trainable_variables)
    

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多