深度学习 花卉图像识别的代码
时间: 2024-06-09 19:03:24 浏览: 184
深度学习是机器学习中的一种方法,通过多层神经网络来学习数据中的特征并进行分类或预测。而花卉图像识别则是深度学习在计算机视觉领域的一个重要应用。
下面是一个基于 Python 和 TensorFlow 的花卉图像识别代码示例:
1. 数据预处理
```
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
import os
import cv2
# 数据路径
data_path = 'flower_photos'
# 获取所有图像路径和标签
image_paths = []
labels = []
label_names = os.listdir(data_path)
for i, label_name in enumerate(label_names):
image_dir = os.path.join(data_path, label_name)
for image_name in os.listdir(image_dir):
image_path = os.path.join(image_dir, image_name)
image_paths.append(image_path)
labels.append(i)
# 将标签转换为 one-hot 编码
num_classes = len(label_names)
labels = tf.keras.utils.to_categorical(labels, num_classes)
# 划分训练集和测试集
train_image_paths, test_image_paths, train_labels, test_labels = train_test_split(
image_paths, labels, test_size=0.2, random_state=42)
# 图像预处理函数
def preprocess_image(image_path):
image = cv2.imread(image_path)
image = cv2.resize(image, (224, 224))
image = image / 255.0
return image
# 数据生成器
def data_generator(image_paths, labels, batch_size):
while True:
indices = np.random.choice(len(image_paths), batch_size)
batch_image_paths = [image_paths[i] for i in indices]
batch_labels = labels[indices]
batch_images = [preprocess_image(image_path) for image_path in batch_image_paths]
yield np.array(batch_images), batch_labels
```
2. 模型训练
```
from tensorflow.keras.applications import VGG16
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
# 加载预训练模型 VGG16
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# 冻结预训练模型的参数
base_model.trainable = False
# 构建模型
model = Sequential()
model.add(base_model)
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
batch_size = 32
train_steps_per_epoch = len(train_image_paths) // batch_size
test_steps_per_epoch = len(test_image_paths) // batch_size
train_generator = data_generator(train_image_paths, train_labels, batch_size)
test_generator = data_generator(test_image_paths, test_labels, batch_size)
model.fit_generator(train_generator,
steps_per_epoch=train_steps_per_epoch,
epochs=10,
validation_data=test_generator,
validation_steps=test_steps_per_epoch)
```
3. 模型评估
```
# 在测试集上评估模型性能
test_loss, test_acc = model.evaluate_generator(test_generator, test_steps_per_epoch)
print('Test accuracy:', test_acc)
```
阅读全文