基于深度学习卷积神经网络花卉识别python代码
时间: 2023-08-04 08:08:30 浏览: 174
Python基于卷积神经网络CNN实现的花卉识别项目源码+数据集+模型
5星 · 资源好评率100%
以下是一份基于深度学习卷积神经网络的花卉识别Python代码,使用Keras框架实现:
```
# 导入所需的库
import os
import numpy as np
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
# 设置数据路径
train_dir = 'flower_photos/train'
val_dir = 'flower_photos/val'
test_dir = 'flower_photos/test'
# 数据增强
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
val_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
# 加载数据
train_data = train_datagen.flow_from_directory(
train_dir,
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
val_data = val_datagen.flow_from_directory(
val_dir,
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
test_data = test_datagen.flow_from_directory(
test_dir,
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
# 构建模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(5, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# 训练模型
history = model.fit_generator(
train_data,
steps_per_epoch=100,
epochs=20,
validation_data=val_data,
validation_steps=50)
# 评估模型
score = model.evaluate_generator(test_data, steps=50)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 绘制训练曲线
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
```
这份代码使用了四个卷积层和两个全连接层,其中卷积层使用了ReLU激活函数,全连接层使用了Dropout防止过拟合。训练过程中使用了数据增强技术,同时在训练后绘制了训练曲线以分析模型的表现。
阅读全文