tensorflow实现多层感知机进行手写字识别
微信公众号:数据挖掘与分析学习
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})) #使用测试集来验证模型精度 |
输出:
阅读更多
- keras实现多层感知机进行手写字识别
- tensorflow 学习专栏(五):在mnist数据集上使用tensorflow实现临近算法(Nearest-Neighbor)进行手写数字识别
- Tensorflow实战——利用多层感知机识别手写数字
- 【TensorFlow-windows】(一)实现Softmax Regression进行手写数字识别(mnist)
- 多层感知机实现mnist手写数字识别
- tensorflow实现logistic回归进行手写字识别
- TensorFlow学习笔记(二):手写数字识别之多层感知机
- TensorFlow笔记(二)---多层感知机识别手写数字
- 利用tensorflow一步一步实现基于MNIST 数据集进行手写数字识别的神经网络,逻辑回归
- TensorFlow实战(二)Tensorflow实现自编码器及多层感知机
- TensorFlow实现MLP(多层感知机)
- TensorFlow实现多层感知机
- tensorflow 实现kaggle手写识别Digit Recognizer(二)卷积神经网络
- Tensorflow高速入门2--实现手写数字识别
- TensorFlow(二)实现Softmax Regression 识别手写数字
- tensorflow 学习笔记9 卷积神经网络(CNN)实现mnist手写识别
- tensorflow进行MNIST手写数字识别-简单版
- TensorFlow学习---实现mnist手写数字识别
- Tensorflow 实现 MNIST 手写数字识别
- 用TensorFlow的Softmax Regression进行手写数字识别