多层神经网络是一种全连接的神经网络。在keras中用Dense类实现。
构造一个神经网络的步骤如下:
- 构建神经网络
构建神经网络的方法是使用tf.keras.Sequential。用法有多种,本文采用如下的方法:
model = tf.keras.Sequential([
layers.Dense(256, input_shape=(784,),activation=tf.nn.relu),
#layers.Dense(128, activation=tf.nn.relu),
layers.Dense(10, activation=tf.nn.softmax)])
input_shape定义了输入的维度。mnist中手写数字的大小是28*28像素的,化为一维后是784。
第一个隐含层是256。在训练中,曾经增加了一层128的隐含层,不过效果并不好。这也证明了神经网络并不是越复杂就越好。
-
读取数据
读取数据是在load_data中完成的。具体可见我写的读取mnist的博客。这里不重复了。 -
构建训练方法
keras也提供了训练方法,可以在网络查找相关的资料。本博客借鉴了网络上的一种方法:
train()函数是训练神经网络的。使用了GradientTape。
loss_function()函数定义了损失函数。
compute_accuracy()计算准确度。 -
验证训练效果
test()是检查网络训练效果的。
为了增强对神经网络的使用,编写了随机选取一副图片,输入到神经网络,并用图形给出了比对结果。
代码如下:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras import layers, models, optimizers, metrics
from sklearn.metrics import confusion_matrix, accuracy_score
def load_data(path,number=10000,batch_size=500):
origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/'
path = tf.keras.utils.get_file(
path,
origin=origin_folder + 'mnist.npz',
cache_dir='DataSet/',
cache_subdir=""
)
with np.load(path, allow_pickle=True) as f:
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
x_train