内容参考http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_beginners.html,本文内容只是方便自己下次学习,如有侵权,请联系我进行删除。
一、Tensorflow安装
我前面有些在ubuntu下安装GPU:https://blog.csdn.net/qq_33266320/article/details/79626176
装好GPU,在装anaconda,然后直接pip install tensorflow_gpu就可以了。
window下建议装anaconda然后在装gpu在一样得命名。
如果是CPU,直接pip install tensorflow(可以==版本号)
二、在tensorflow资源上引入Mnist数据
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
print(mnist.train.images.shape,mnist.train.labels.shape)#55000
print(mnist.test.images.shape,mnist.test.labels.shape)#10000
print(mnist.validation.images.shape,mnist.validation.labels.shape)#5000
三、创建模型
#Create model
x=tf.placeholder(tf.float32,[None,784])#占位符
W=tf.Variable(tf.zeros([784,10]))#参数变量
b=tf.Variable(tf.zeros([10]))
y=tf.nn.softmax(tf.matmul(x,W)+b)
y_ = tf.placeholder("float", [None,10])
# The raw formulation of cross-entropy,
#
# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
# reduction_indices=[1]))
#
# can be numerically unstable.
#
# So here we use tf.losses.sparse_softmax_cross_entropy on the raw
# outputs of 'y', and then average across the batch.
#cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y_, logits=y)
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step=tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#
四、开始训练
sess=tf.InteractiveSession()
#sess.tf.Session()
tf.global_variables_initializer().run()
#init = tf.initialize_all_variables()
#sess = tf.Session()
#sess.run(init)
#train
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
五、评估
#test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_,1))#选最大arg
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(
accuracy, feed_dict={
x: mnist.test.images,
y_: mnist.test.labels
}))
在学习率为0.01下在我电脑上运行该代码准确率是92.01%。