这是代码 来自 https://keras.io/examples/vision/image_classification_from_scratch/
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# generate a dataset
image_size = (180,180)
batch_size = 32
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
"PetImages",
validation_split = 0.2,
subset = "training",
seed = 1337,
image_size = image_size,
batch_size = batch_size,
)
错误是
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-21-bb7f2d14bf63> in <module>
3 batch_size = 32
4
----> 5 train_ds = tf.keras.preprocessing.image_dataset_from_directory(
6 "PetImages",
7 validation_split = 0.2,
AttributeError: module 'tensorflow.keras.preprocessing' has no attribute 'image_dataset_from_directory'
我现在忽略的任何最小的细节?
v2.5.0
我使用该代码遇到了同样的错误:
tf.keras.utils.image_dataset_from_directory(...)
将其更改为:
tf.keras.preprocessing.image_dataset_from_directory(...)
解决我的问题
已在此问题下解决。
The specific function (tf.keras.preprocessing.image_dataset_from_directory) is not available under TensorFlow v2.1.x or v2.2.0 yet. It is only available with the tf-nightly builds and is existent in the source code of the master branch.
太糟糕了,他们没有在现场的任何地方指出这一点。现在最好使用
flow_from_directory
。或者切换到 tf-nightly
并继续。
我也遇到了同样的问题。当我将 TensorFlow 版本升级到 2.3.0 时,它起作用了。
tf.keras.utils.image_dataset_from_directory
函数,因为tf.keras.utils模块中不存在该函数。从目录加载图像数据集的正确函数是
tf.keras.preprocessing.image_dataset_from_directory
此功能是
tf.keras.preprocessing
模块的一部分,而不是 tf.keras.utils
。
语法
import tensorflow as tf
dataset = tf.keras.preprocessing.image_dataset_from_directory(
directory, # Path to the directory
labels='inferred', # Automatically infers labels from directory structure
label_mode='int', # Labels are integers
color_mode='rgb', # Images are color
batch_size=32, # Size of the batches of data
image_size=(256, 256), # Size to resize images to
)
请将
directory
替换为图像目录的路径。该函数将自动从目录结构推断标签。例如,如果您的目录结构为 directory/dog/xxx.png
和 directory/cat/yyy.png
,则该函数会将标签 ‘dog’
分配给 xxx.png
,将 ‘cat’
分配给 yyy.png
。标签将表示为整数(在本例中,0 表示“狗”,1 表示“猫”)。
图像的大小将调整为
256x256 pixels
并且它们将位于 color (RGB)
中。该函数将返回一个 tf.data.Dataset
对象。