tensorflow学习笔记(二)

tensorflow中自带的mnist手写数字识别,运用最简单的单层神经网络,softmax激活函数,极客学院上说准确率有91%,我今天调整到了92%!

import tensorflow as tf
import numpy as np
import math
import tensorflow.examples.tutorials.mnist as mn
class Mnist:
def __init__(self):
sess = tf.InteractiveSession()
self.mnist = mn.input_data.read_data_sets("E:\\Python35\\Lib\\site-packages\\tensorflow\\examples\\tutorials\\mnist\\MNIST_data",one_hot=True)
self.x = tf.placeholder("float", shape=[None, 784])
self.y_ = tf.placeholder("float", shape=[None, 10])
self.W = tf.Variable(tf.zeros([784,10]))
self.b = tf.Variable(tf.zeros([10]))
self.y = tf.nn.softmax(tf.matmul(self.x,self.W) + self.b)
self.cross_entropy = -tf.reduce_sum(self.y_*tf.log(self.y))
sess.run(tf.global_variables_initializer())

self.bestModel = None
self.bestPredict = 0.0
self.bestIter = 0
self.bestRate = 0.0
self.bestSample = 0

self.iters = [1000,1200,1400]
self.rates = [0.01,0.02]
self.samples = [100,150,200]

def train(self):
for iter in self.iters:
for rate in self.rates:
train_step = tf.train.GradientDescentOptimizer(rate).minimize(self.cross_entropy)
for sample in self.samples:
self.optimizer(iter, rate, sample, train_step)

def optimizer(self,iter,rate,sample,train_step):
for i in range(iter):
batch = self.mnist.train.next_batch(sample)
model = train_step.run(feed_dict={self.x: batch[0], self.y_: batch[1]})
correct_prediction = tf.equal(tf.argmax(self.y, 1), tf.argmax(self.y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
predict = accuracy.eval(feed_dict={self.x: self.mnist.test.images, self.y_: self.mnist.test.labels})
if predict > self.bestPredict:
self.bestPredict = predict
self.bestModel = model
self.bestIter = iter
self.bestRate = rate
self.bestSample = sample

def output(self):
print("bestRate:",self.bestRate,"bestIter:",self.bestIter,"bestSample:",self.bestSample,"bestPredict:",self.bestPredict)

if __name__ == '__main__':
mnist = Mnist()
mnist.train()
mnist.output()


E:\Python35\python.exe E:/PycharmProjects/test/com/python/machinelearning/tensorflowTest.py
Extracting E:\Python35\Lib\site-packages\tensorflow\examples\tutorials\mnist\MNIST_data\train-images-idx3-ubyte.gz
Extracting E:\Python35\Lib\site-packages\tensorflow\examples\tutorials\mnist\MNIST_data\train-labels-idx1-ubyte.gz
Extracting E:\Python35\Lib\site-packages\tensorflow\examples\tutorials\mnist\MNIST_data\t10k-images-idx3-ubyte.gz
Extracting E:\Python35\Lib\site-packages\tensorflow\examples\tutorials\mnist\MNIST_data\t10k-labels-idx1-ubyte.gz

bestRate: 0.01 bestIter: 1000 bestSample: 100 bestPredict: 0.9193
posted @ 2017-07-13 23:39  佟学强  阅读(374)  评论(0编辑  收藏  举报