在MNIST数据集上用Tensorflow实现多层神经网络算法

在MNIST数据集上用Tensorflow实现多层神经网络算法

前言

MNIST是一个被广泛使用的数据集,科研领域中也时常使用到它。

若想看在kaggle竞赛上的Digit Recognizer-MNIST比赛中Tensorflow实现神经网络算法,请点击右侧超链接:请点我

MNIST数据集,是一个在科研界都被广泛使用的数据集,其由Yann LeCun, Courant Institute, NYU、Corinna Cortes, Google Labs, New York和Christopher J.C. Burges, Microsoft Research, Redmond共同维护,该数据集比较适合用来练习卷积神经网络以及其它各种神经网络,官网网址为:MNIST官网,上面有不同文章不同算法得到的对于MNIST的最优的结果。

废话不多说,直接进入正题。

需要下载的东西(数据和代码)

训练集、测试集以及相关代码都在如下的百度云盘中:

链接:https://pan.baidu.com/s/1tPNGEriTNbBB1ym9eEwTrQ 
提取码:ccbn 

代码讲解

首先,先导入必要的库和数据

from tensorflow.examples.tutorials.mnist import input_data
# 导入MNIST数据并以onehot形式编码label
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

import tensorflow as tf
import numpy as np
from tensorflow.python.framework import ops

初始化一个session

# 初始化一个 Session
ops.reset_default_graph()
sess = tf.Session()

调参时固定随机种子

# 调参时固定随机种子
seed = 1
tf.set_random_seed(seed)
np.random.seed(seed) 

定义变量函数 (weights and bias)

# 定义变量函数 (weights and bias)
def init_weight(shape, st_dev):
    weight = tf.Variable(tf.random_normal(shape, stddev=st_dev))
    return(weight)
    

def init_bias(shape, st_dev):
    bias = tf.Variable(tf.random_normal(shape, stddev=st_dev))
    return(bias)

声明占位符(Placeholders)

# 声明占位符(Placeholders)
x_data = tf.placeholder(shape=[None, 784], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 10], dtype=tf.float32)

构建网络

# 构建双层神经网络
# 创建不同的层:
def relu_layer(input_layer, weights, biases):
    layer = tf.add(tf.matmul(input_layer, weights), biases)
    return(tf.nn.relu(layer))

def liner_layer(input_layer, weights, biases):
    layer = tf.add(tf.matmul(input_layer, weights), biases)
    return(layer)

rand_st_dev=0.01
#-------- 创建第一个隐藏层 (100个隐藏单元)--------
hidden_nodes1=100
weight_1 = init_weight(shape=[784, hidden_nodes1], st_dev=rand_st_dev)
bias_1 = init_bias(shape=[hidden_nodes1], st_dev=rand_st_dev)
layer_1 = relu_layer(x_data, weight_1, bias_1)

#-------- 创建输出层 (10个输出)--------
output_nodes=10
weight_output = init_weight(shape=[hidden_nodes1, output_nodes],
                            st_dev=rand_st_dev)
bias_output = init_bias(shape=[output_nodes], st_dev=rand_st_dev)
final_output = liner_layer(layer_1, weight_output, bias_output)

# 声明损失函数 (softmax)
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=final_output,
                                                              labels=y_target))

# 声明优化算法(optimizer)
my_opt = tf.train.RMSPropOptimizer(0.001,0.9)
train_step = my_opt.minimize(loss)

在此处声明计算准确率的op

# 在此处声明计算准确率的op
predictions=tf.placeholder(shape=[None,10], dtype=tf.int32)
train_correct_prediction = tf.equal(tf.argmax(mnist.test.labels,1),
                                    tf.argmax(predictions,1))
train_accuracy_op = tf.reduce_mean(tf.cast(train_correct_prediction,
                                           tf.float32))

训练网络

# 训练网络
# 声明批量大小(batch size)
batch_size = 512
# 初始化变量
init = tf.global_variables_initializer()
sess.run(init)

# 训练循环
loss_vec = []
train_acc=[]

for i in range(20000):
    batch_xs, batch_ys = mnist.train.next_batch(batch_size)
    sess.run(train_step, feed_dict={x_data: batch_xs, y_target: batch_ys})

    
    if (i+1)%100==0:
        temp_loss = sess.run(loss, feed_dict={x_data: batch_xs,
                                              y_target: batch_ys})
        loss_vec.append(np.sqrt(temp_loss))
        
        predictions_train=sess.run(final_output,feed_dict={x_data: mnist.test.images})
        train_accuracy=sess.run(train_accuracy_op,feed_dict=
                                {predictions:predictions_train})
        train_acc.append(train_accuracy)
        
        print('迭代次数: ' + str(i+1) + '. 训练损失 = ' + str(temp_loss))
        print("训练集准确率为: " + str(train_accuracy))
        print(" ")

这是最后的训练结果输出:
在这里插入图片描述
由于模型很简单,但也已有 98.13 % 98.13\% 98.13%的正确率,进一步调参能有更好的结果。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值