import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from tqdm import tqdm
dataset_path = "./flowers" # 数据集路径
image_size = (320, 240) # 图像大小
batch_size = 32 # 批量大小
num_classes = 5 # 类别数量
epochs=10
datagen = ImageDataGenerator(
rescale=1./255, # 图像归一化
validation_split=0.2 # 划分验证集
)# 创建数据生成器
train_generator = datagen.flow_from_directory(
dataset_path,
target_size=image_size,
batch_size=batch_size,
class_mode='categorical',
subset='training'
)# 加载训练集和验证集
validation_generator = datagen.flow_from_directory(
dataset_path,
target_size=image_size,
batch_size=batch_size,
class_mode='categorical',
subset='validation'
)
sample_images, _ = next(train_generator)
plt.figure(figsize=(10, 10))
for i in range(9):
plt.subplot(3, 3, i + 1)
plt.imshow(sample_images[i])
plt.axis("off")
plt.show()# 显示部分训练集图像
# 显示部分验证集图像
sample_images, _ = next(validation_generator)
plt.figure(figsize=(10, 10))
for i in range(9):
plt.subplot(3, 3, i + 1)
plt.imshow(sample_images[i])
plt.axis("off")
plt.show()
model = keras.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(image_size[0], image_size[1], 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(num_classes, activation='softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
train_steps_per_epoch = train_generator.samples // batch_size
val_steps_per_epoch = validation_generator.samples // batch_size
for epoch in range(epochs):
print("Epoch {}/{}".format(epoch + 1, epochs))
pbar = tqdm(total=train_steps_per_epoch, unit="batch")
for _ in range(train_steps_per_epoch):
x_batch, y_batch = next(train_generator)
loss, acc = model.train_on_batch(x_batch, y_batch)
pbar.update(1)
pbar.set_description("Train loss: {:.4f}, acc: {:.4f}".format(loss, acc))
pbar.close()
val_loss, val_acc = model.evaluate(validation_generator, steps=val_steps_per_epoch)
print("Validation loss: {:.4f}, acc: {:.4f}".format(val_loss, val_acc))
model.save("flower_classification_model.h5") # 保存模型
test_image_path = "./flowers/test3-t.jpg" # 替换为要预测的图像路径
test_image = tf.keras.preprocessing.image.load_img(test_image_path, target_size=image_size)
test_image_array = tf.keras.preprocessing.image.img_to_array(test_image)
test_image_array = tf.expand_dims(test_image_array, 0) # 添加批次维度
saved_model = keras.models.load_model("flower_classification_model.h5") # 加载保存的模型
predictions = saved_model.predict(test_image_array)
predicted_class_index = tf.argmax(predictions, axis=-1)
predicted_class = train_generator.class_indices
for class_name, class_index in predicted_class.items():
if class_index == predicted_class_index:
print("预测结果:", class_name)
break
CNN卷积神经网络花朵识别(5种)
最新推荐文章于 2024-04-25 11:58:59 发布
该代码示例展示了如何利用TensorFlow和Keras库对花卉图像进行预处理、构建卷积神经网络(CNN)模型、训练模型并进行预测。数据集通过ImageDataGenerator进行增强和归一化,模型结构包含多层卷积和全连接层,并在训练后保存为.h5文件。
摘要由CSDN通过智能技术生成