您的位置:首页 > 其它

Tensorflow实现逻辑分类器

2017-08-22 21:28 465 查看
实现分类器使用的数据集为input_data中的数据,导入数据集前需要先下载数据集,否则会报错ImportError: No module named input_data解决方法:先安装input_data.py,直接复制地址https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/tutorials/mnist在这里下载后,在终端输入Python input_data.py就好了最终结果值应该大约是91%
#coding=utf-8import tensorflow as tfimport numpy as npimport input_data#mnist.train为训练数据集,mnist.test为测试集#每个mnist数据单元由两部分组成:一张包含手写数字的图片(xs)和一个对应的标签(ys)#训练数据集和测试数据集都包含xs和ys,比如训练数据集的图片是 mnist.train.images ,训练数据集的标签是 mnist.train.labelsmnist = input_data.read_data_sets("MNIST_data/",one_hot = True)#mnist.train.images是一个形状为[55000,784]的张量,55000个图片,每张图片28*28,展开成一个向量长度为784#第一维度数字用来索引图片,第二维度数字用来索引每张图片中的像素点(值介于0-1)#标签为0-9的数字标签数据使用one-hot vectors。#mnist.train.labels为一个[55000,10]的数字矩阵#占位符X = tf.placeholder("float",[None,784])Y = tf.placeholder("float",[None,10])#第一维度可任意长w = tf.Variable(tf.zeros([784,10]))b = tf.Variable(tf.zeros([10]))#训练模型y = tf.nn.softmax(tf.matmul(X,w)+b)#损失函数lost = -tf.reduce_sum(Y*tf.log(y))#计算交叉熵train_step = tf.train.GradientDescentOptimizer(0.01).minimize(lost)#梯度下降算法sess = tf.Session()sess.run(tf.initialize_all_variables())#模型循环训练1000次for i in range(1000):#每次循环,会随机抓取训练数据中的100个批处理数据点batch_xs,batch_ys = mnist.train.next_batch(100)sess.run(train_step,feed_dict = {X:batch_xs,Y:batch_ys})#评估模型#找出预测正确的标签correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(Y,1))#把布尔值转换成浮点数,然后取平均值。例如,[True, False, True, True] 会变成 [1,0,1,1] ,取平均值后得到 0.75.accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))#计算所学习到的模型在测试数据集上面的正确率。print (sess.run(accuracy,feed_dict = {X: mnist.test.images,Y:mnist.test.labels}))sess.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: