使用Python基于卷积神经网络实现是否佩戴安全帽的二分类问题带详细注释,并绘出损失和准确率的曲线图,并显示分类结果
时间: 2024-11-22 15:44:02 浏览: 13
基于python实现的CNN卷积神经网络手写数字识别项目源码+详细注释+数据集(毕业设计&期末大作业)
在Python中,我们可以使用深度学习库如TensorFlow或PyTorch结合Keras库来实现基于卷积神经网络(Convolutional Neural Network, CNN)的二分类任务,比如识别行人是否佩戴了安全帽。以下是使用Keras的一个简单示例:
```python
# 导入所需库
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import to_categorical
import matplotlib.pyplot as plt
# 数据预处理
data_dir = 'your_data_directory' # 替换为实际数据路径
img_width, img_height = 64, 64 # 图像尺寸
train_datagen = ImageDataGenerator(rescale=1./255) # 对图像做归一化
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
data_dir + '/train',
target_size=(img_width, img_height),
batch_size=32,
class_mode='binary') # 二分类问题
validation_generator = validation_datagen.flow_from_directory(
data_dir + '/validation',
target_size=(img_width, img_height),
batch_size=32,
class_mode='binary')
# 构建CNN模型
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(img_width, img_height, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(128, (3, 3), activation='relu'),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 训练模型并绘制训练过程
history = model.fit(train_generator,
epochs=10,
validation_data=validation_generator)
# 绘制损失和准确率曲线图
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss Curves')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy Curves')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
# 预测和展示分类结果
test_generator = ImageDataGenerator(rescale=1./255).flow_from_directory(
data_dir + '/test',
target_size=(img_width, img_height),
batch_size=1,
class_mode=None) # 这里不需要class_mode,因为我们只关心结果
predictions = model.predict(test_generator)
results = np.argmax(predictions, axis=1)
for i, img in enumerate(test_generator.filenames):
print(f"Image: {img}\nPredicted: {'wearing hat' if results[i] else 'not wearing hat'}\n")
```
注意:这个例子假设你已经有了标注好的训练集、验证集和测试集,它们分别放在'data_dir/train'、'data_dir/validation'和'data_dir/test'下,每个目录下还应有对应的子目录,分别表示不同的类别。实际操作中你需要替换`your_data_directory`为实际的数据存储位置。
阅读全文