欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Deep.Learning.for.Computer.Vision.with.Python-----chapter14Lenet网络模型

时间:2023-06-04
文章目录

一、代码演示


一、代码演示

定义网络 lenet.py:

"""LeNet:INPUT => CONV => ReLU => POOL => CONV => ReLU => POOL =>FC => ReLU => FCINPUT:28X28X1CONV:28X28X20 Filter:5X5 K=20ACT:ReLUPOOL:14X14X20 2X2 步长是2X2 每行移动2个 换行后也是2个CONV:14X14X50 5X5 K=50ACT:ReLUPOOL:7X7X50 2X2FC:500ACT:ReLUFC:10SOFTMAX:10"""from keras.models import Sequentialfrom keras.layers.convolutional import Conv2Dfrom keras.layers.convolutional import MaxPooling2Dfrom keras.layers.core import Activationfrom keras.layers.core import Flattenfrom keras.layers.core import Densefrom keras import backend as K#构建网络class LeNet: @staticmethod #class:标签类别数量 def build(width,height,depth,classes): model = Sequential() inputShape = (height,width,depth) if K.image_data_format()=='channels_first': inputShape = (depth,height,width) #CONV => RELU => POOL model.add(Conv2D(20,(5,5),padding='same',input_shape=inputShape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2))) # CONV => RELU => POOL model.add(Conv2D(50,(5,5),padding='same')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2))) #输入量变平,并可以应用一个具有500个节点的全连接层 #FC => RELU model.add(Flatten()) model.add(Dense(500)) model.add(Activation('relu')) #=> FC classes=10(10类标签) model.add(Dense(classes)) model.add(Activation('softmax')) return model

训练网络 lenet_mnist.py:

"""1.加载mnist数据2.实例化网络3.训练网络4.评估"""from lenet import LeNetfrom keras.optimizers import SGDfrom sklearn.preprocessing import LabelBinarizerfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import classification_reportimport scipy.io as sciofrom keras import backend as Kimport matplotlib.pyplot as pltimport numpy as np#1.加载数据print('[INFO] accessing MNIST...')dataset = scio.loadmat('D:/DLCV/DLCVmy_study/datasets/openml/mnist-original.mat')data = dataset['data'].Tlabel = dataset['label'].T#print(data.shape)if K.image_data_format()=='channels_first': #data.shape[0]图片个数 data = data.reshape(data.shape[0],1,28,28)else: data = data.reshape(data.shape[0], 28, 28, 1)"将原始图像强度压缩到0-1"data = data.astype("float")/255.0(trainX, testX, trainY, testY) = train_test_split(data, label, test_size=0.25,random_state=42)#将标签转为向量 如:若标签类别是3 则对应输出[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]le = LabelBinarizer()trainY = le.fit_transform(trainY)testY = le.transform(testY)#2.初始化优化器和网络print('[INFO] compiling model...')opt = SGD(lr=0.01)model = LeNet.build(width=28,height=28,depth=1,classes=10)model.compile(loss='categorical_crossentropy',optimizer=opt,metrics=['accuracy'])#3.x训练网络print('[INFO] training network...')# verbose:1代表显示进度条,0不显示进度条,默认为0H = model.fit(trainX,trainY,validation_data=(testX,testY),batch_size=128,epochs=20,verbose=1)#4.评估网络print('[INFO] evaluating network...')predictions = model.predict(testX,batch_size=128)print(classification_report(testY.argmax(axis=1),predictions.argmax(axis=1),target_names=[str(x) for x in le.classes_]))plt.style.use('ggplot')plt.figure()plt.plot(np.arange(0,20),H.history['loss'],label='train_loss')plt.plot(np.arange(0,20),H.history['val_loss'],label='val_loss')plt.plot(np.arange(0,20),H.history['acc'],label='train_acc')plt.plot(np.arange(0,20),H.history['val_acc'],label='val_acc')plt.title("Training Loss and Accuracy")plt.xlabel('Epoch #')plt.ylabel('Loss/Accuracy')plt.legend()plt.show()

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。