【问题标题】:Cannot convert tf.keras.preprocessing.image_dataset_from_directory to np.array无法将 tf.keras.preprocessing.image_dataset_from_directory 转换为 np.array
【发布时间】:2022-01-25 05:54:55
【问题描述】:

我正在尝试使用 CNN 创建图像分类模型。为此,我正在使用tf.keras.preprocessing.image_dataset_from_directory 函数读取数据。

这是代码:

train_ds = tf.keras.preprocessing.image_dataset_from_directory(data_dir_train,seed=123,validation_split = 0.2,subset = 'training',image_size=(img_height, img_width),batch_size=batch_size)

然后我尝试在 np.array 对象中转换数据集。我的代码是

x_train = np.array(train_ds)

但是当我打印 x_train 时,我得到了

array(<BatchDataset shapes: ((None, 180, 180, 3), (None,)), types: (tf.float32, tf.int32)>, dtype=object)

对象train_ds 的形状为(2000,180,180,3)。我不确定我的代码有什么问题。

【问题讨论】:

  • 你期望得到什么?
  • @richardec : 为什么会出现 ((None, 180, 180, 3), (None,))。我觉得应该是(2000,180,180,3)

标签: python numpy tensorflow keras conv-neural-network


【解决方案1】:

使用image_dataset_from_directory时:

... image_dataset_from_directory(main_directory, labels='inferred') 将返回一个 tf.data.Dataset,该 yields 批图像来自子目录 ...

获取所需数据的一种方法是使用take 创建一个数据集,其中最多包含 count 个来自该数据集的元素。

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

img = np.empty((6000,180,180,3), dtype=np.float32)
label = np.empty((6000,), dtype=np.int32)

train_ds = tf.data.Dataset.from_tensor_slices((img,label)).batch(2000)
print(train_ds) # <BatchDataset shapes: ((None, 180, 180, 3), (None,)), types: (tf.float32, tf.int32)>

for imgs, labels in train_ds.take(1):
    print(imgs.shape) # (2000, 180, 180, 3)
    print(labels.shape) # (2000,)
    for img in imgs:
        plt.imshow(img.numpy().astype(np.uint8)) # print imgs in the batch

根据您构建代码的方式,您甚至可能不需要转换为 numpy.array,因为 tf.keras.Model fit 接受 tf.data 数据集。 p>

model.fit(
  train_ds,
  validation_data=val_ds,
  epochs=epochs
)

【讨论】:

  • 但是如何打印图片。
  • 要打印图像,您可以使用 Matplotlib imshow 函数。我已经编辑了答案。
  • 但是当我使用这个功能时它只显示一个黑色方块。不是图像。你能帮我解决这个问题吗?
  • 很可能是因为您正在运行这个使用np.empty 构建的示例,它创建一个数组而不初始化条目。在for循环中,使用从image_dataset_from_directory获得的你自己的train_ds
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 2023-03-16
  • 2021-06-11
  • 1970-01-01
相关资源
最近更新 更多