LeNet-5

使用keras搭建的LeNet

一、环境配置

pip install keras==2.4.3 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

pip install numpy==1.19.5 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

pip install pandas==1.3.5 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

pip install matplotlib==3.4.2 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

pip install sklearn==0.0 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

二、代码实现

import pathlib
import keras_preprocessing
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import keras
from keras.layers import Dense, Flatten, Conv2D, MaxPool2D

# 解决中文显示问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 读取训练集数据
data_train = 'LeNet/data/Zodiac/train/'
data_train = pathlib.Path(data_train)

# 读取验证集的数据
data_valid = 'LeNet/data/Zodiac/valid/'
data_valid = pathlib.Path(data_valid)

# 给数据类别放置到列表数据中
CLASS_NAMES = np.array(['dog', 'dragon', 'goat', 'horse', 'monkey', 'ox',
                        'pig', 'rabbit', 'ratt', 'rooster', 'snake', 'tiger'])

# 设置图片大小和批次数
BATCH_SIZE = 64
IMG_HEIGHT = 32
IM_WIDTH = 32

# 对数据进行归一化处理
image_generator = keras.preprocessing.image.ImageDataGenerator(rescale=1.0/255)

# 训练集生成器
train_data_gen = image_generator.flow_from_directory(directory=str(data_train),
                                                     batch_size=BATCH_SIZE,
                                                     shuffle=True,
                                                     target_size=(IMG_HEIGHT, IM_WIDTH),
                                                     classes=list(CLASS_NAMES)
                                                     )

# 验证机生成器
valid_data_gen = image_generator.flow_from_directory(directory=str(data_valid),
                                                     batch_size=BATCH_SIZE,
                                                     shuffle=True,
                                                     target_size=(IMG_HEIGHT, IM_WIDTH),
                                                     classes=list(CLASS_NAMES)
                                                     )

# 利用keras搭建卷积神经网络
model = keras.Sequential()
model.add(Conv2D(filters=6, kernel_size=5, input_shape=(32, 32, 3), activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(filters=16, kernel_size=5, activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(filters=120, kernel_size=5, activation='relu'))
model.add(Flatten())
model.add(Dense(84, activation='relu'))
model.add(Dense(12, activation='softmax'))

# 编译卷积神经网络
model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy'])

history = model.fit(train_data_gen, validation_data=valid_data_gen, epochs=50)

# 保存训练好的模型
model.save("model.h5")

# 绘制loss图
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['valid_loss'], label='valid')
plt.title("CNN神经网络loss值")
plt.legend()
plt.show()

# 绘制准确率
plt.plot(history.history['accuracy'], label='train')
plt.plot(history.history['valid_accuracy'], label='valid')
plt.title("CNN神经网络accuracy值")
plt.legend()
plt.show()
tory['valid_accuracy'], label='valid')
plt.title("CNN神经网络accuracy值")
plt.legend()
plt.show()

你可能感兴趣的:(深度学习,python,numpy,keras)