【问题标题】:Error when getting features from tensorflow-dataset从 tensorflow-dataset 获取特征时出错
【发布时间】:2023-04-05 10:09:01
【问题描述】:

尝试加载 Caltech tensorflow-dataset 时出现错误。我正在使用tensorflow-datasets GitHub中的标准代码

错误是这样的:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot batch tensors with different shapes in component 0. First element had shape [204,300,3] and element 1 had shape [153,300,3]. [Op:IteratorGetNextSync]

错误指向for features in ds_train.take(1)这一行

代码:

ds_train, ds_test = tfds.load(name="caltech101", split=["train", "test"])

ds_train = ds_train.shuffle(1000).batch(128).prefetch(10)
for features in ds_train.take(1):
    image, label = features["image"], features["label"]

【问题讨论】:

  • 调用tfds.load后运行print(ds_train.output_shapes)的结果是什么?
  • {'image': TensorShape([Dimension(None), Dimension(None), Dimension(3)]), 'image/file_name': TensorShape([]), 'label': TensorShape([])}
  • 如果你在ds_train = ds_train.shuffle(1000).batch(128).prefetch(10)之后放置同一行会打印什么?
  • {'image': TensorShape([Dimension(None), Dimension(None), Dimension(None), Dimension(3)]), 'image/file_name': TensorShape([Dimension(None)]), 'label': TensorShape([Dimension(None)])}
  • 您是否可能在没有先清除 python 环境的情况下不小心运行了两次ds_train = ds_train.shuffle(1000).batch(128).prefetch(10) 行?从输出中可以看出,tfds.load 没有预批处理数据(它不应该),但是您的错误消息显示代码正在尝试批处理整个数据集而不是单个样本。如果您重新启动 python 解释器并运行显示它们的行,中间没有任何其他内容,问题是否仍然存在?

标签: python python-3.x tensorflow runtime-error tensorflow-datasets


【解决方案1】:

问题来自数据集包含可变大小的图像这一事实(请参阅数据集描述here)。 Tensorflow 只能批量处理具有相同形状的事物,因此您首先需要将图像重塑为常见形状(例如,网络的输入形状)或相应地填充它们。

如果要调整大小,请使用tf.image.resize_images:

def preprocess(features, label):
  features['image'] = tf.image.resize_images(features['image'], YOUR_TARGET_SIZE)
  # Other possible transformations needed (e.g., converting to float, normalizing to [0,1]
  return features, label

如果您想填充,请使用tf.image.pad_to_bounding_box(只需在上面的preprocess 函数中替换它并根据需要调整参数)。 通常,对于我所知道的大多数网络,都会使用调整大小。

最后,在数据集上映射函数:

ds_train = (ds_train
            .map(prepocess)
            .shuffle(1000)
            .batch(128)
            .prefetch(10))

注意:错误代码中的可变形状来自shuffle调用。

【讨论】:

  • 啊,谢谢。我认为没有简单的方法来重塑或填充?
  • 当然有!让我补充一下答案
  • 非常感谢 :)
猜你喜欢
  • 2020-11-13
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 2018-03-28
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
相关资源
最近更新 更多