基于tensorflow的手写数字识别代码
from keras.utils import to_categorical
from keras import models, layers, regularizers
from keras.optimizers import RMSprop
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28 * 28)).astype("float")
test_images = test_images.reshape((10000, 28 *28)).astype("float")
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
network = models.Sequential()
network.add(layers.Dense(units=128, activation='relu', input_shape=(28*28,),
kernel_regularizer=regularizers.l1(0.0001)))
# 百分之1使得神经元丧失性能
network.add(layers.Dropout(0.001))
network.add(layers.Dense(units=32, activation='relu', kernel_regularizer=regularizers.l1(0.0001)))
network.add(layers.Dropout(0.001))
network.add(layers.Dense(units=10, activation='softmax'))
# 查看当前神经网络结构
print(network.summary())
# 编译步骤
network.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
# 训练网络,使用fit 函数,epochs 表示训练多少回合,batch_size表示每次训练给多大的数据。
network.fit(train_images, train_labels, epochs=20, batch_size=128, verbose=2)
# 使用测试集来测试性能
y_pre = network.predict(test_images[:5])
print(y_pre, test_labels[:5])
test_loss, text_accuracy = network.evaluate(test_images,test_labels)
print("test_loss",test_loss,". ","test_accuracy: ", text_accuracy)
运行结果如下:
从结果可以看出,有一定程度的过拟合,优化代码可以解决