import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist = input_data.read_data_sets(‘MNIST_data’,one_hot=True)
#每个批次大小
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
#创建一个简单的神经网络
w = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,w) + b)
#二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#初始化变量
init = tf.global_variables_initializer()
#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
for epoch in range(21):
for batch in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print('Iter' + str(epoch) + ',Testing Accuracy' + str(acc))
返回值:
Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
Iter0,Testing Accuracy0.8308
Iter1,Testing Accuracy0.8711
Iter2,Testing Accuracy0.881
Iter3,Testing Accuracy0.8876
Iter4,Testing Accuracy0.8948
Iter5,Testing Accuracy0.8967
Iter6,Testing Accuracy0.8997
Iter7,Testing Accuracy0.9017
Iter8,Testing Accuracy0.9031
Iter9,Testing Accuracy0.905
Iter10,Testing Accuracy0.9058
Iter11,Testing Accuracy0.9071
Iter12,Testing Accuracy0.9079
Iter13,Testing Accuracy0.9096
Iter14,Testing Accuracy0.9095
Iter15,Testing Accuracy0.9106
Iter16,Testing Accuracy0.9119
Iter17,Testing Accuracy0.9119
Iter18,Testing Accuracy0.9127
Iter19,Testing Accuracy0.9134
Iter20,Testing Accuracy0.9143
本文使用TensorFlow库训练一个简单的神经网络,对MNIST数据集进行手写数字分类。通过梯度下降法优化二次代价函数,经过多轮训练,模型的测试准确性逐渐提高。
1244

被折叠的 条评论
为什么被折叠?



