我正在学习在线课程,并在 python 3.11 中运行以下代码,以使用 Keras 3.6 和 TensorFlow 2.18 构建用于图像分类的 CNN:
# Convolutional Nueral Network
import tensorflow as tf
import keras as kr
from tf_keras.preprocessing.image import ImageDataGenerator
import numpy as np
from tf_keras.preprocessing import image
print(tf.__version__)
print(kr.__version__)
# Part 1 - Data Preprocessing
# Preprocessing the Training Set
# Below, an instance of the class of ImageDataGenerator that causes transformations
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
training_set = train_datagen.flow_from_directory(
"dataset/training_set",
target_size=(64,64),
batch_size=32,
class_mode='binary')
# Preprocessing the Test Set
test_datagen = ImageDataGenerator(rescale=1./255)
test_set = test_datagen.flow_from_directory(
"dataset/test_set",
target_size=(64,64),
batch_size=32,
class_mode='binary')
# Part 2 - Buildinging the CNN
# Initializing the CNN
cnn = kr.Sequential()
# Step 1 - Convolution
cnn.add(kr.layers.Conv2D(filters=32,
kernel_size=3,
activation='relu',
input_shape=[64,64,3]))
# Step 2 - Pooling
cnn.add(kr.layers.MaxPool2D(pool_size=2,
strides=2,
padding='valid'))
# Step 3 - Adding a second convolutional layer
cnn.add(kr.layers.Conv2D(filters=32,
kernel_size=3,
activation='relu'))
# Step 4 - Adding a second pooling layer
cnn.add(kr.layers.MaxPool2D(pool_size=2,
strides=2,
padding='valid'))
# Step 5 Flattening
cnn.add(kr.layers.Flatten())
# Step 6 Full Connection
cnn.add(kr.layers.Dense(units=128,
activation='relu'))
# Step 7 Output Layer
cnn.add(kr.layers.Dense(units=1,
activation='sigmoid')) #Sigmoid b/c classification is binary
# Part 3 - Training the CNN
# Step 1 Compiling the CNN
cnn.compile(optimizer='adam',
loss = 'binary_crossentropy',
metrics= ['accuracy'])
# Step 2 Training the CNN on the Training Set and Evaluating it on the Test Set
cnn.fit(x = training_set,
validation_data = test_set,
epochs=25)
当进行到第 3 部分,步骤 2 训练 CNN 时,并且 cnn.fit 方法行运行,我收到以下错误:
raise ValueError(f"Unrecognized data type: x={x} (of type {type(x)})")
ValueError: Unrecognized data type: x=<tf_keras.src.preprocessing.image.DirectoryIterator object at 0x141d69210> (of type <class 'tf_keras.src.preprocessing.image.DirectoryIterator'>)
我该如何解决这个问题?我查看了 Keras 3 文档,它显示只允许某些数据类型(https://keras.io/api/models/model_training_apis/),但我不确定如何将我的训练集和测试集转换为这些数据类型类型。
我尝试在拟合过程中使用
将训练集和测试集转换为numpy数组cnn.fit(x = np.array(training_set),
validation_data = np.array(test_set),
epochs=25)
但这似乎运行了很长时间并消耗了大量内存。我不知道还能尝试什么。我感谢您的帮助!