CNN花朵分类代码
时间: 2023-07-05 13:06:19 浏览: 112
基于cnn的花卉图像分类.代码+数据+可作为毕设课设
5星 · 资源好评率100%
以下是使用CNN进行花朵分类的Python代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
# 设置数据集路径和类别
DATADIR = "flower_photos"
CATEGORIES = ["daisy", "dandelion", "roses", "sunflowers", "tulips"]
# 加载数据集并进行预处理
X = []
y = []
for category in CATEGORIES:
path = os.path.join(DATADIR, category)
for img in os.listdir(path):
img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_COLOR)
img_array = cv2.resize(img_array, (150, 150))
X.append(img_array)
y.append(CATEGORIES.index(category))
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# 将标签转换为独热编码
y_train = to_categorical(y_train, num_classes=len(CATEGORIES))
y_test = to_categorical(y_test, num_classes=len(CATEGORIES))
# 将像素值归一化到0到1之间
X_train = np.array(X_train) / 255.0
X_test = np.array(X_test) / 255.0
# 建立卷积神经网络模型
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(150, 150, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, kernel_size=(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(len(CATEGORIES), activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
history = model.fit(X_train, y_train, batch_size=32, epochs=20, validation_data=(X_test, y_test))
# 绘制训练和测试准确率随时间的变化图
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
```
这段代码实现了一个简单的卷积神经网络模型,用于分类花朵图像。首先,我们从文件夹中加载图像数据集,并对其进行预处理。然后,我们将数据集分为训练集和测试集,并将标签转换为独热编码。接下来,我们建立一个卷积神经网络模型,并对其进行编译。最后,我们使用训练数据集训练模型,并绘制训练和测试准确率随时间的变化图。
阅读全文