import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
设定种子
tf.random.set_seed(42)
预处理数据(获取0和1之间的所有像素值,也称为缩放/归一化(
train_datagen = ImageDataGenerator(rescale = 1./255)
valid_datagen = ImageDataGenerator(rescale = 1./255)
设置数据目录的路径
train_dir = '/content/pizza_steak/train'
test_dir = 'pizza_steak/test'
从目录导入数据并将其转换为批处理
train_data = train_datagen.flow_from_directory(directory = train_dir,
batch_size = 32,
target_size = (224, 224),
class_mode = 'binary',
seed = 42)
valid_data = valid_datagen.flow_from_directory(directory = test_dir,
batch_size = 32,
target_size = (224, 224),
class_mode = 'binary',
seed = 42)
构建CNN模型(与CNN解释网站上的Tiny VGG相同(
model_1 = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters = 10,
kernel_size = 3,
activation = 'relu',
input_shape = (244, 244, 3)),
tf.keras.layers.Conv2D(10, 3, activation = 'relu'),
tf.keras.layers.MaxPool2D(pool_size = 2,
padding = 'valid'),
tf.keras.layers.Conv2D(10, 3, activation = 'relu'),
tf.keras.layers.Conv2D(10, 3, activation = 'relu'),
tf.keras.layers.MaxPool2D(2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1, activation = 'sigmoid')
])
编译我们的CNN
model_1.compile(
loss = 'binary_crossentropy',
optimizer = tf.keras.optimizers.Adam(),
metrics = ['accuracy']
)
适合模型
history_1 = model_1.fit(train_data,
epochs = 5,
steps_per_epoch = len(train_data),
validation_data = valid_data,
validation_steps = len(valid_data))
您需要将input_shape
更改为(224, 224, 3)
或将target_size
更改为(244, 244, 3)
。它不适用于不同的形状。下面是一个工作示例:
import tensorflow as tf
import matplotlib.pyplot as plt
BATCH_SIZE = 32
flowers = tf.keras.utils.get_file(
'flower_photos',
'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
untar=True)
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_data = train_datagen.flow_from_directory(directory = flowers,
batch_size = 32,
target_size = (224, 224),
class_mode = 'sparse',
seed = 42)
model_1 = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters = 10,
kernel_size = 3,
activation = 'relu',
input_shape = (224, 224, 3)),
tf.keras.layers.Conv2D(10, 3, activation = 'relu'),
tf.keras.layers.MaxPool2D(pool_size = 2,
padding = 'valid'),
tf.keras.layers.Conv2D(10, 3, activation = 'relu'),
tf.keras.layers.Conv2D(10, 3, activation = 'relu'),
tf.keras.layers.MaxPool2D(2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(5, activation = 'softmax')
])
model_1.compile(
loss = 'sparse_categorical_crossentropy',
optimizer = tf.keras.optimizers.Adam(),
metrics = ['accuracy']
)
history_1 = model_1.fit(train_data,steps_per_epoch = len(train_data),
epochs = 5)