赞
踩
"""A very simple MNIST classifier. See extensive documentation at http://tensorflow.org/tutorials/mnist/beginners/index.md """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # 引入数据集 from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf #命令行运行代码时传递参数,也就是用来实现各个参数的传递 flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data') # 把数据放在/tmp/data文件夹中 mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) # 读取数据集 # 建立抽象模型 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])) a = tf.nn.softmax(tf.matmul(x, W) + b) # placeholder又叫占位符,是一个抽象的概念。用于表示输入输出数据的格式。告诉系统:这里有一个值/向量/矩阵,现在我没法给你具体数值,不过我正式运行的时候会补上的,例如上面表示[?,784]的矩阵,?具体是多少,后文按情况指定 #Variable代表变量,用来指定参数 #softmax是激活函数相当于f(x),是一个函数式 # 定义损失函数和训练方法 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(a), reduction_indices=[1])) # 损失函数为交叉熵,reduction_indices=[1]代表按第一维度进行计算,相对于矩阵来说可以看成按列计算 optimizer = tf.train.GradientDescentOptimizer(0.5) # 梯度下降法,采用随机梯度下降法,学习速率为0.5 #建立训练模型 train = optimizer.minimize(cross_entropy) # 训练目标:最小化损失函数 # 建立测试模型 correct_prediction = tf.equal(tf.argmax(a, 1), tf.argmax(y, 1))#tf.argmax表示找到最大值的位置(也就是预测的分类和实际的分类),然后看看他们是否一致,是就返回true,不是就返回false,这样得到一个boolean数组。 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))#tf.cast将boolean数组转成int数组,如果是True就转化成1,如果是False就转化成0,最后求平均值,得到分类的准确率 # 开始进行实际的训练 sess = tf.InteractiveSession() # 建立交互式会话 tf.initialize_all_variables().run()#对所有变量进行初始化 for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100)#从数据集中每次获取100个图片即100个数据 train.run({x: batch_xs, y: batch_ys})#将获得的数据给训练模型,进行训练和计算 print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})) #经过训练模型的训练得到了一批相应的参数如w,x,b等,而得到的这批参质量好不好呢?这就还要用测试模型进行测试了。 #feed_dict的作用是给使用placeholder创建出来的tensor赋值,上面就把mnist.test.images赋值给x,把mnist.test.labels赋值给y
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。