您的位置:首页 > 其它

tensorflow实现多层感知机进行手写字识别

2018-09-12 14:56 288 查看
版权声明:微信公众号:数据挖掘与机器学习进阶之路。本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013230189/article/details/82661615

微信公众号:数据挖掘与分析学习

1.数据准备

from __future__ import print_function

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

 

mnist=input_data.read_data_sets("/data/machine_learning/mnist/",one_hot=True) #读取mnist数据集,如果目录下有该数据则读取,否则下载,使用one-hot编码

2.参数设置

#参数设置

learning_rate=0.001 #学习率

training_epochs=15 #数据集遍历次数

batch_size=100 #批处理大小

display_step=1 #

 

#网络参数

n_hidden_1=256 #第一个隐藏层输出神经元数量

n_hidden_2=256 #第二个隐藏层输出神经元数量

n_input=784 #输入的特征数量,mnist数据中图片大小为28*28

n_classes=10 #标签类别数量

3.模型构建

#数据占位符

X=tf.placeholder("float",[None,n_input])

Y=tf.placeholder("float",[None,n_classes])

 

#隐藏层和输出层权重参数设置

weights={'h1':tf.Variable(tf.random_normal([n_input,n_hidden_1])),

        'h2':tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2])),

         'out':tf.Variable(tf.random_normal([n_hidden_2,n_classes]))

        }

 

#隐藏层和输出层偏置

biases={

    'b1':tf.Variable(tf.random_normal([n_hidden_1])),

    'b2':tf.Variable(tf.random_normal([n_hidden_2])),

    'out':tf.Variable(tf.random_normal([n_classes]))

}

 

#模型构建,两个隐藏层

def multilayer_perceptron(x):

    layer_1=tf.add(tf.matmul(x,weights['h1']),biases['b1'])

    layer_2=tf.add(tf.matmul(layer_1,weights['h2']),biases['b2']),

    out_layer=tf.add(tf.matmul(layer_1,weights['out']),biases['out'])

    return out_layer

4.模型训练和验证

logits=multilayer_perceptron(X)

 

#使用交叉熵损失

loss_op=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=Y))

 

#定义优化器

optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate)

train_op=optimizer.minimize(loss_op)#使用优化器最小化损失

 

init=tf.global_variables_initializer()#变量初始化器

 

with tf.Session()as sess:

    sess.run(init)

   

    for epoch in range(training_epochs):

        avg_cost=0

        total_batch=int(mnist.train.num_examples/batch_size)

       

        for i in range(total_batch):

            batch_x,batch_y=mnist.train.next_batch(batch_size)

            _,c=sess.run([train_op,loss_op],feed_dict={X:batch_x,Y:batch_y})

           

            avg_cost+=c/total_batch #计算平均损失

           

        if epoch%display_step==0:

            print("Epoch:","%04d"%(epoch+1),"cost={:.9f}".format(avg_cost))

    print("优化完成!")

   

    pred=tf.nn.softmax(logits=logits)

   

    correct_prediction=tf.equal(tf.argmax(pred,1),tf.argmax(Y,1))

    accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float"))

   

    print("Accuracy:",accuracy.eval({X:mnist.test.images,Y:mnist.test.labels})) #使用测试集来验证模型精度

输出:

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: