tensorflow实现softma识别MNIST
识别MNIST已经成了深度学习的helloworld,所以每次例程基本都会用到这个数据集,这个数据集在tensorflow内部用着很好的封装,因此可以方便地使用。
这次我们用tensorflow搭建一个softmax多分类器,和之前搭建线性回归差不多,第一步是通过确定变量建立图模型,然后确定误差函数,最后调用优化器优化。
误差函数与线性回归不同,这里因为是多分类问题,所以使用了交叉熵。
另外,有一点值得注意的是,这里构建模型时我试图想拆分多个函数,但是后来发现这样做难度很大,因为图是在规定变量就已经定义好的,不能随意拆分,也不能当做变量传来传去,因此需要将他们写在一起。
代码如下:
#encoding=utf-8
__author__='freedom'
importtensorflowastf
defloadMNIST():
fromtensorflow.examples.tutorials.mnistimportinput_data
mnist=input_data.read_data_sets('MNIST_data',one_hot=True)
returnmnist
defsoftmax(mnist,rate=0.01,batchSize=50,epoch=20):
n=784#向量的维度数目
m=None#样本数,这里可以获取,也可以不获取
c=10#类别数目
x=tf.placeholder(tf.float32,[m,n])
y=tf.placeholder(tf.float32,[m,c])
w=tf.Variable(tf.zeros([n,c]))
b=tf.Variable(tf.zeros([c]))
pred=tf.nn.softmax(tf.matmul(x,w)+b)
loss=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
opt=tf.train.GradientDescentOptimizer(rate).minimize(loss)
init=tf.initialize_all_variables()
sess=tf.Session()
sess.run(init)
forindexinrange(epoch):
avgLoss=0
batchNum=int(mnist.train.num_examples/batchSize)
forbatchinrange(batchNum):
batch_x,batch_y=mnist.train.next_batch(batchSize)
_,Loss=sess.run([opt,loss],{x:batch_x,y:batch_y})
avgLoss+=Loss
avgLoss/=batchNum
print'everyepochaveragelossis',avgLoss
right=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy=tf.reduce_mean(tf.cast(right,tf.float32))
print'Accracyis',sess.run(accuracy,({x:mnist.test.images,y:mnist.test.labels}))
if__name__=="__main__":
mnist=loadMNIST()
softmax(mnist)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。