网络编程
位置:首页>> 网络编程>> Python编程>> tensorflow实现softma识别MNIST

tensorflow实现softma识别MNIST

作者:freedom098  发布时间:2021-02-17 22:32:56 

标签:tensorflow,softma,MNIST

识别MNIST已经成了深度学习的hello world,所以每次例程基本都会用到这个数据集,这个数据集在tensorflow内部用着很好的封装,因此可以方便地使用。

这次我们用tensorflow搭建一个softmax多分类器,和之前搭建线性回归差不多,第一步是通过确定变量建立图模型,然后确定误差函数,最后调用优化器优化。

误差函数与线性回归不同,这里因为是多分类问题,所以使用了交叉熵。

另外,有一点值得注意的是,这里构建模型时我试图想拆分多个函数,但是后来发现这样做难度很大,因为图是在规定变量就已经定义好的,不能随意拆分,也不能当做变量传来传去,因此需要将他们写在一起。

代码如下:


#encoding=utf-8
__author__ = 'freedom'
import tensorflow as tf

def loadMNIST():
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data',one_hot=True)
return mnist

def softmax(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)
for index in range(epoch):
 avgLoss = 0
 batchNum = int(mnist.train.num_examples/batchSize)
 for batch in range(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 'every epoch average loss is ',avgLoss

right = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(right,tf.float32))
print 'Accracy is ',sess.run(accuracy,({x:mnist.test.images,y:mnist.test.labels}))

if __name__ == "__main__":
mnist = loadMNIST()
softmax(mnist)

来源:http://blog.csdn.net/freedom098/article/details/52116813

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com