python-LeNet卷积神经网络目标检测

LeNet网络

lenet卷积神经网络是比较早的目标检测网络,今天复现一下,数据集采用mnist,在网络中加入了参数量和计算量和网络结构查看代码,而且将网络结构与训练代码进行分离,这样可以在设计网络结构时,可以将lenet网络改为你想设计的网络。出创新点。

代码结构

python-LeNet卷积神经网络目标检测_第1张图片
其中,LeNet为网络结构模块,summary是网络结构查看模块,xunlian模块是训练网络模块,utils是设计支持summary的模块

LeNet网络

from keras.models import Sequential
from keras.layers.convolutional import Conv2D,MaxPooling2D
from keras.layers.core import Dense,Activation,Flatten


class lenet():
    @staticmethod
    def net(input_shape,classes):
        model = Sequential()

        model.add(Conv2D(32 , (3,3) , padding = 'same' , input_shape=input_shape,data_format = 'channels_first'))
        model.add(Activation('relu') )
        model.add(MaxPooling2D(pool_size = (2,2) , strides = (2,2)))

        model.add(Conv2D(50, (5,5) , padding = 'same' , input_shape=input_shape,data_format = 'channels_first'))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size = (2,2),strides = (2,2)))

        model.add(Flatten())
        model.add(Dense(500))
        model.add(Activation ('relu'))

        model.add(Dense(classes))
        model.add(Activation ('softmax'))

        return model

可以在该代码的基础上,进行网络改进,改为自己想要的网络结构

summary

from LeNet import lenet

from utils import net_flops

if __name__ == "__main__":
    input_shape = [28,28]
    classes = 10

    model = lenet.net([input_shape[0],input_shape[1],3],classes)
    #查看网络结构
    model.summary()
    #计算网络的flops
    net_flops(model,table = False)

用于查看设计好的网络结构和参数、计算量,lenet的网络结构如下所示
python-LeNet卷积神经网络目标检测_第2张图片
python-LeNet卷积神经网络目标检测_第3张图片

xunlian网络

from keras.datasets import mnist
from keras.optimizers import nadam
from LeNet import lenet
from keras import backend as K
import matplotlib.pyplot as plot
from keras.utils import np_utils
import numpy as np
#参数设置
eproch = 40
batch_size = 128
verbose = 1
optimizer = nadam()
val_spilt = 0.2
r,w = 28,28
Class = 10
input_shape = (1,r,w)

#输入数据处理
(x_train,y_train),(x_test,y_test) = mnist.load_data()

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /=255
x_test /=255
x_train = x_train[:, np.newaxis, :, :]
x_test = x_test[:, np.newaxis, :, :]
print(x_train.shape[0], "train sample")
print(x_test.shape[0], "test sample")

y_train = np_utils.to_categorical(y_train,Class)
y_test = np_utils.to_categorical(y_test,Class)

#建立的模型导入
model = lenet.net(input_shape = input_shape,classes = Class)
#编译
model.compile(loss = 'categorical_crossentropy',optimizer=optimizer,metrics=["accuracy"])
history = model.fit(x_train,y_train,batch_size=batch_size,epochs=eproch,verbose=verbose,validation_split=val_spilt)
score = model.evaluate(x_test,y_test,verbose=verbose)
print(f"test score:{score[0]}")
print(f"test accuracy:{score[1]}")
print(history.history.keys())

plot.plot(history.history["acc"])
plot.plot(history.history["val_acc"])
plot.title("model accuracy")
plot.ylabel("accuracy")
plot.xlabel("epoch")
plot.legend(["train","test"],loc="upper left")
plot.show()

plot.plot(history.history["loss"])
plot.plot(history.history["val_loss"])
plot.title("model loss")
plot.ylabel("loss")
plot.xlabel("epoch")
plot.legend(["train","test"],loc="upper left")
plot.show()

训练结果

python-LeNet卷积神经网络目标检测_第4张图片

训练的是自带的mnist数据集,下一个博客将介绍训练自己的数据集

你可能感兴趣的:(目标检测,python,cnn)