【问题标题】:Tensorflow2 Error : Can't convert Python sequence with mixed types to TensorTensorflow2 错误:无法将混合类型的 Python 序列转换为张量
【发布时间】:2021-07-15 03:46:01
【问题描述】:

为了学习图像分类问题,我想使用 tf.data.Dataset 类加载数据。

input_X 值是一个包含文件路径的列表。
前任。 [/path/to/image1.jpg, /path/to/image2.jpg, ...]

input_Y 值是与 input_X 匹配的标签名称列表。
前任。 ['cat', 'cat', 'dog', ...]

我想使用tf.data.Dataset.from_generator 函数和我的生成器函数加载数据。

下面是我的generator代码:

def get_generator(self, dataset, full_path, category_names, input_shape):
    images = dataset[0]
    labels = dataset[1]
    ih, iw = input_shape[0:2]

    images = self.attach_fullpath(images, full_path)
    for data in zip(images, labels):
        imagename, labelname = data

        image = cv2.imread(imagename)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image = tf.image.resize(image, [ih, iw])
        image = tf.cast(image, tf.float32)
        image = image / 255.0

        label = tf.one_hot(category_names.index(labelname), depth=len(category_names))
        label = tf.cast(label, tf.float32)

    yield (image, label)

如果我执行next(generator),我会得到以下输出:

# X data
tf.Tensor(
[[[0.31978127 0.20193568 0.20587036]
  [0.33178368 0.21166316 0.20612068]
  [0.34334144 0.2161987  0.19959025]
  ...
  [0.42936707 0.2707099  0.1780539 ]
  [0.41268054 0.26256576 0.16227722]
  [0.4328849  0.28778687 0.18582608]]], shape=(299, 299, 3), dtype=float32)

# Y data
tf.Tensor([0. 0. 1.], shape=(3,), dtype=float32)

在定义了这个生成器之后,我使用tf.data.Dataset.from_generator函数定义了数据集如下:

dataset = tf.data.Dataset.from_generator(self.get_generator, 
                                         (tf.float32, tf.float32),
                                         args=(train_data, 
                                               self.full_path, 
                                               ['omelette', 'pizza', 'samosa'], 
                                               (299, 299, 3)))
dataset = dataset.batch(8)

这里的full_path值是输入的完整路径的一部分,使图片的路径成为绝对路径。

而且,train_data[0] 是上述图片的路径列表,
train_data[1] 是与上述图像路径匹配的标签名称列表。

但是,我收到了以下错误:

Can't convert Python sequence with mixed types to Tensor.

我该如何解决这个错误?

【问题讨论】:

    标签: python tensorflow tensorflow-datasets


    【解决方案1】:

    我查看了 tensorflow 文档 - 我以前没有使用过 from_generator 的完整披露者。我相信生成器应该产生张量。您可能希望对目标“y”标签进行 1-of-k 编码(例如,“cat”为 0,“dog”为 1),并强制执行某种排序以将文件路径与相应的图像匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 2022-01-03
      • 1970-01-01
      • 2021-02-22
      • 2021-01-05
      • 2018-09-24
      • 1970-01-01
      相关资源
      最近更新 更多