深度学习之利用TensorFlow实现简单的全连接层网络(MNIST数据集)

Tensorflow是一个基于数据流编程(Dataflow Programming)的符号数学系统,被广泛应用于各类机器学习(Machine Learning)算法的编程实现,其前身是谷歌的神经网络算法库DistBelief。MNIST数据集是机器学习领域中非常经典的一个数据集,由60000个训练样本和10000个测试样本组成,每个样本都是一张28*28像素的灰度手写数字图片。

一、安装,并导入TensorFlow

import tensorflow as tf

二、利用TensorFlow API下载,导入MNIST数据集,并预处理

(x_train_all, y_train_all), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train_all, x_test = x_train_all / 255.0, x_test / 255.0

x_valid, x_train = x_train_all[:5000], x_train_all[5000:]
y_valid, y_train = y_train_all[:5000], y_train_all[5000:]

三、构建全连接神经网络模型

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(256, activation='relu'))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dropout(0.2))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

四、编译,并训练模型

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10, validation_data=(x_valid, y_valid))

五、评估模型

model.evaluate(x_test, y_test)

附:完整代码(TensorFlow 2.0.0-RC0)

#!/usr/bin/env python
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]='2'

import tensorflow as tf

# 打印TensorFlow版本号
print(tf.__name__, tf.__version__)

# 下载MNIST数据集
(x_train_all, y_train_all), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

# 预处理数据 [0, 255] => [0.0, 1.0]
x_train_all, x_test = x_train_all / 255.0, x_test / 255.0

# 分割数据60000条数据集,前5000条为验证数据集,后55000条为训练数据集
x_valid, x_train = x_train_all[:5000], x_train_all[5000:]
y_valid, y_train = y_train_all[:5000], y_train_all[5000:]

# 构建全连接神经网络模型
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(256, activation='relu'))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dropout(0.2))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

# 编译模型
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 训练模型
model.fit(x_train, y_train, epochs=10, validation_data=(x_valid, y_valid))

# 评估模型
model.evaluate(x_test, y_test)

测试数据集的评估结果:0s 31us/sample – loss: 0.0411 – accuracy: 0.9816,总体来说,效果还是不错的~

Leave a Reply

Your email address will not be published. Required fields are marked *