tensorflow构建神经网络对于mnist进行判断
2018-03-05 本文已影响0人
大梦一场三十一
以下是根据莫烦Python的程序
https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-01-classifier/
还有一个作者写的挺好的
http://blog.csdn.net/wuyzhen_csdn/article/details/64920773
初步构建出基于tensorflow的一个简单的神经网络
运用的数据是mnist手写字符库
构建了三层的网络 输入层,隐藏层,输出层
代码如下
import tensorflow as tf
#下载或者加载mnist手写库
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def add_layer(inputs, in_size, out_size, activation_function=None,):
# add one more layer and return the output of this layer
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b,)
return outputs
#计算识别的准确度
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs})
correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32,[None,784]) #28*28
ys = tf.placeholder(tf.float32,[None,10]) #10输出
#add output layer
prediction = add_layer(xs,784,10,activation_function=tf.nn.softmax)
#the error between prediction and real data
#loss函数(即最优化目标函数)选用交叉熵函数
#交叉熵用来衡量预测值和真实值的相似程度,如果完全相同,它们的交叉熵等于零。
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1]))
##tf.log计算y中元素的对数,tf.reduce_sum计算y中第2维元素的相加
##(y为tensor with shape[None, 10]),因为参数reduction_indices=[1]
##最后tf.reduce_mean计算平均值,在源代码中我们不使用该方程,
##因为它数字上不是稳定的对于非规范化的逻辑,
##使用tf.nn.softmax_cross_entropy_with_logits
## cross_entropy = tf.reduce_mean(
## tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
##sess = tf.Session()
###现在可以运行模型,通过InteractiveSession
sess = tf.InteractiveSession();
# important step
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
if i % 50 == 0:
print(compute_accuracy(
mnist.test.images, mnist.test.labels))