在本文中,我们使用tensorflow2.x实现了lenet-5,用于mnist的识别。
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
from tensorflow import keras
数据预处理
我们先载入mnist数据
(x_train, y_train),(x_test, y_test) = keras.datasets.mnist.load_data()
我们把特征数据增加一个纬度,用于LeNet5的输入:
print(x_train.shape, y_train.shape)
x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)
print(x_train.shape, y_train.shape)
(60000, 28, 28) (60000,)
(60000, 28, 28, 1) (60000,)
特征数据归一化:
x_train = x_train/255.0
x_test = x_test/255.0
标签做onehot:
y_train = np.array(pd.get_dummies(y_train))
y_test = np.array(pd.get_dummies(y_test))
构建模型
我们使用sequential构建LeNet-5模型&