【问题标题】:ValueError: Shape must be rank 0 but is rank 1 for 'ReadFile' (op: 'ReadFile') with input shapes: [1]ValueError:形状必须为 0 级,但对于输入形状为“ReadFile”(操作:“ReadFile”)为 1 级:[1]
【发布时间】:2020-10-17 02:49:17
【问题描述】:

这是我的总体问题: 我正在尝试构建一个包含图像的 tf.data.Dataset。我正在从 csv 文件中读取 imageIds(文件名),以便能够将它们与同样在同一个 csv 文件中找到的相应标签相结合。 CSV-file Screenshot

df_imageIDs = pd.read_csv(file_labels,
                          usecols=["ImageId"])
df_imageIDs = df_imageIDs.apply(lambda ID: data_dir_train + ID, axis=1)
ds_filenames_images = tf.data.Dataset.from_tensor_slices(df_imageIDs.to_numpy())

在使用 pandas 读取图像 ID 并添加目录路径后,我使用方法 tf.read_file 将图像解码函数映射到我的数据集。这会引发错误。

def decode_image(file_path):
    img = tf.io.read_file(file_path)
    img = tf.image.decode_jpeg(img, channels=parameters["CHANNELS"])
    img = tf.image.convert_image_dtype(img, tf.float32)
    img = tf.image.resize(img, (parameters["IMAGE_HEIGHT"], parameters["IMAGE_WIDTH"]))
    return img

ds_images = ds_filenames_images.map(decode_image,
                                    num_parallel_calls=AUTOTUNE)

现在,我之前尝试过的是使用 tf.data.Dataset.list_files,它工作正常,但 ImageId 的顺序错误。

ds_filenames_imagesx = tf.data.Dataset.list_files(data_dir_train + "*.jpg",
                                                  shuffle=False)

区别似乎在于 pandas 使用文件名的方式,尽管它们具有相同的数据类型“字符串”。 打印出后一种方法的元素会导致:

tf.Tensor(/home/wid35008/airbus-ship-detection/train_v2/000155de5.jpg, shape=(), dtype=string)

打印出我想使用的方法的张量会导致:

tf.Tensor(['/home/wid35008/airbus-ship-detection/train_v2/0002756f7.jpg'], shape=(1,), dtype=string)

因为我不知道如何解释这些差异,也不知道如何找到解决方法。有人有解决这个问题的方法吗?提前致谢!

【问题讨论】:

标签: python pandas csv tensorflow


【解决方案1】:

因此,为我自己和可能偶然发现它的其他人提供解决方案。 我在创建后重新塑造了数据集,因此里面的张量将再次具有标量的形状。

ds_filenames_images = tf.data.Dataset.from_tensor_slices(df_imageIDs.to_numpy())
ds_filenames_images = ds_filenames_images.map(lambda t: tf.reshape(t, []))

文档对此给出了更深入的解释。 Tensor Shapes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多