基于卷积神经网络的花卉识别示例代码
时间: 2023-08-09 19:11:44 浏览: 123
以下是基于卷积神经网络的花卉识别示例代码,使用Python语言和TensorFlow库:
```python
import tensorflow as tf
import numpy as np
import cv2
import os
# 数据集准备
data_dir = 'flower_photos/'
categories = os.listdir(data_dir)
num_classes = len(categories)
image_size = 224
# 构建卷积神经网络模型
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(image_size, image_size, 3)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(num_classes, activation='softmax')
])
# 编译并训练模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
batch_size = 32
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(image_size, image_size),
batch_size=batch_size)
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(image_size, image_size),
batch_size=batch_size)
model.fit(train_ds, validation_data=val_ds, epochs=10)
# 测试模型
test_images = []
test_labels = []
for category in categories:
folder_path = os.path.join(data_dir, category)
for img_name in os.listdir(folder_path):
img_path = os.path.join(folder_path, img_name)
img = cv2.imread(img_path)
img = cv2.resize(img, (image_size, image_size))
test_images.append(img)
test_labels.append(categories.index(category))
test_images = np.array(test_images)
test_labels = np.array(test_labels)
predictions = model.predict(test_images)
predicted_labels = np.argmax(predictions, axis=1)
accuracy = np.mean(predicted_labels == test_labels)
print("Accuracy:", accuracy)
```
上述代码中,我们首先准备了花卉数据集,然后构建了一个卷积神经网络模型。我们使用了三个卷积层和两个全连接层,并在最后一层使用了softmax激活函数进行分类。接着,我们使用了`tf.keras.preprocessing.image_dataset_from_directory`函数来加载数据集,并使用`model.fit`函数训练模型。最后,我们使用测试集对模型进行测试,并计算了模型的准确率。
需要注意的是,上述代码仅仅是一个示例,实际的代码可能会因为数据集和任务的不同而有所差异。
阅读全文