"""
使用全连接神经网络训练minist数据集
"""
import tensorflow as tf
from tensorflow.keras.utils import to_categorical
from tensorflow.keras import models, layers, regularizers
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
import cv2
"""
一、认识minist数据集
"""
(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)))
network.add(layers.Dropout(0.01))
network.add(layers.Dense(units=32, activation='relu',
kernel_regularizer=regularizers.l1(0.0001)))
network.add(layers.Dropout(0.01))
network.add(layers.Dense(units=10, activation='softmax'))
"""
三、神经网络的训练
1.编译:确定优化器和损失函数等
2.训练网络:确定训练的数据、训练的轮数和每次训练的样本数等
"""
network.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
network.fit(train_images, train_labels, epochs=20, batch_size=128, verbose=2)
"""
四、用训练好的模型进行预测,并在测试集上做出评价
"""
y_pre = network.predict(test_images[:5])
print(y_pre, "\n", test_labels[:5])
test_loss, test_accuracy = network.evaluate(test_images, test_labels)
print("test_loss:", test_loss, "test_accuracy:", test_accuracy)