Lenet5+minst手写体数据集(利用tensorflow2.3.1实现)

笔者看了看,网上关于tensorflow的CNN模型训练好多都是基于1.0的。但tensorflow2.0是大趋势(相信很多人都会选择装2.0的tf),笔者利用的是tensorflow2.0框架实现的程序。

Lenet是啥?
minst又是啥?
笔者在此不再赘述,相信有兴趣读到我文章的都是内行(虽然我是个外行,哈哈哈啊)
话不多说,直接上代码

'''
lenet5+keras+minst数据集
encoding='utf-8'
运行环境:tensorflow2.3.1(cpu),window系统,pycharm
'''
#导包
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Flatten, Dense, Conv2D, MaxPool2D
from keras.utils import to_categorical
from keras.metrics import categorical_crossentropy
import time

#记录程序运行时间
start_time = time.clock()

#定义Lenet5模型函数
def lenet5():

    #首先建立空模型
    model=Sequential()
    #第一层卷积层(6*5*5),激活函数用relu函数,不使用padding,input_shape为(28*28*1),步长为默认即可
    model.add(Conv2D(6,kernel_size=(5,5),activation='relu',padding='valid',input_shape=(28,28,1)))
    #第二层为最大池化层(2*2)
    model.add(MaxPool2D(pool_size=(2,2)))
    #第三层为卷积2层(16*5*5),激活函数用relu函数
    model.add(Conv2D(16,kernel_size=(5,5),activation='relu'))
    #第四层为最大池化2层(2*2)
    model.add(MaxPool2D(pool_size=(2,2)))
    #第五、六层为全连接层,第一层120个神经元;第二层为84个神经元
    model.add(Flatten())
    model.add(Dense(120,activation='relu'))
    model.add(Dense(84,activation='relu'))
    #输出层(手写数字体识别,因此为10个,激活函数为softmax)
    model.add(Dense(10,activation='softmax'))

    return model

#定义加载minst数据的函数
def loadingdata():

    '''
            x_train为训练集图像
            y_train为训练集的标签(真实值)
            y_train为测试集的标签(真实值)
            x_test为测试集的图像
    '''
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    # 对数据进行预处理,方便输入进去
    x_train = x_train.reshape(len(x_train), 28, 28, 1) / 255
    x_test = x_test.reshape(len(x_test), 28, 28, 1) / 255
    # one-hot编码(因为标签是1,2,3这样的,计算机只喜欢0,1这样的编码形式,这就需要one-hot编码)
    # 通俗上理解就是把(0-9)变为(0,1)这样的形式
    y_train = to_categorical(y_train, 10)
    y_test = to_categorical(y_test, 10)

    return [x_train,y_train,x_test,y_test]


# 定义训练参数
batch_size_num = 100
epochs_num = 20

#加载数据
data=loadingdata()
train_img=data[0]
train_label=data[1]
test_img=data[2]
test_label=data[3]

#start training
lenetmodel=lenet5()
lenetmodel.summary()
lenetmodel.compile(loss=categorical_crossentropy,optimizer='Rmsprop',metrics=['accuracy'])
lenetmodel.fit(train_img,train_label,batch_size=batch_size_num,epochs=epochs_num,verbose=1,
                   validation_data=(test_img,test_label))
score=lenetmodel.evaluate(test_img,test_label)
print('final_loss= %f final_accuracy= %f'%(score[0],score[1]))
end_time=time.clock()
print('time is %0.3f s'%(end_time-start_time))

笔者是Python程序小白,代码是我一句一句手动打的,可能程序不尽如人意。希望能得到大佬的建议,将程序变得更完美。

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你们卷的我睡不着QAQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值