『TensorFlow』读书笔记_SoftMax分类器

今年3、4月份的时候就买了这本书,同时还买了另外一本更为浅显的书,当时读不懂这本,所以一度以为这本书很一般,前些日子看见知乎有人推荐它,也就拿出来翻翻看,发现写的的确蛮好,只是稍微深一点,当时的自己理解不了罢了。另外一方面,感觉自己虽然对tensorflow比较熟稔,但是由于一开始的学习期对于编程实在太白,所以基础并不牢靠,今来重读之,在技术层面:希望能对tensorflow有个更为系统的理解,希望对基于深度学习的图像、文字、强化学习有更为系统的认识,希望对tensorflow基础编码之外包含GPU加速、分布式、可视化、代码调试等等辅助模块有更深的见地。而由于这本书的编写结构很好,所以也想借这本书,对深度学习发展有个系统的梳理,这也就意味着我不仅会跟着体会比较复杂的代码网络,简单的脚本我也会写,比如这篇的……

SoftMax分类器

softmax对mnist数据集合的准确率在92%左右,程序如下,

# Author : Hellcat
# Time   : 2017/12/6

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('../../../Mnist_data/',one_hot=True)
print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.labels.shape)

import tensorflow as tf

sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None,784])

W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.add(tf.matmul(x, W),b))
y_ = tf.placeholder(tf.float32,[None, 10])

# tf的函数继承了np风格,能够自动广播,所以这里直接对onehot码进行计算
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),axis=1))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
tf.global_variables_initializer().run() # 节点使用run

'''
# 下面代码也会报错
# 说明op没有tensor返回时会返回op实例作为替代
init = tf.global_variables_initializer()
init.exal()
'''

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    train_step.run({x:batch_xs, y_:batch_ys})

    # equal函数会返回bool值,使用cast将之转换为float32
    correct_prediction = tf.equal(tf.argmax(y,axis=1), tf.argmax(y_,axis=1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    print('准确率为:{0:.3f}'.
          format(accuracy.eval({x:mnist.test.images, y_:mnist.test.labels}))) # 张量使用eval

tensorflow理解深化:

operation.run()

tensor.eval()

a = operation()操作如果op返回tensor的话a会代表tensor,否则a会代表节点本身,此时启动会话方式是有区别的。