0%

Tesorflow-Coding-Notes:简单mnist分类任务

Original Codes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import tensorflow as tf
import numpy as np

from tensorflow.examples.tutorials.mnist import input_data

#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

#每个批次的大小
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size


#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])


#创建一个简单的神经网络
w = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,w) + b)

#二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))

#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

#定义求准确率的方法,结果存在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))


with tf.Session() as sess:
sess.run(init)
for epoch in range(21):
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})

acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print("Iter" + str(epoch) + ",Testing Accuracy" + str(acc))

执行结果:20次迭代后,准确率为0.9138

Notes

Note1 tf.argmax()

1
tf.argmax(input,axis)

含义:根据axis取值的不同返回每行或者每列最大值的索引。

属性 含义
input 输入的array
axis axis=0,将每一列最大元素的所在索引记录下来,最后输出每一列最大元素所在的索引数组。axis=1,将每一行最大元素所在的索引记录下来,最后返回每一行最大元素所在的索引数组。

Note2 tf.cast()

1
tf.cast(x, dtype, name=None)

含义:tf.cast()函数的作用是执行 tensorflow 中张量数据类型转换。

属性 含义
x 待转换的数据(张量)。
dtype 目标数据类型。
name 可选参数,定义操作的名称。

Tensorflow中的数据类型列表:

数据类型 Python类型 描述
DT_FLOAT tf.float32 32位浮点数
DT_DOUBLE tf.float64 64位浮点数
DT_INT64 tf.int64 64位有符号整型
DT_INT32 tf.int32 32位有符号整型
DT_INT16 tf.int16 16位有符号整型
DT_INT8 tf.int8 8位有符号整型
DT_UINT8 tf.uint8 8位无符号整型
DT_STRING tf.string 可变长度的字节数组.每一个张量元素都是一个字节数组.
DT_BOOL tf.bool 布尔型
DT_COMPLEX64 tf.complex64 由两个32位浮点数组成的复数:实数和虚数.
DT_QINT32 tf.qint32 用于量化Ops的32位有符号整型.
DT_QINT8 tf.qint8 用于量化Ops的8位有符号整型.
DT_QUINT8 tf.quint8 用于量化Ops的8位无符号整型.

超参数调整

只有输入层和输出层

batch_size learning_rate accuracy
32 0.2 0.9236
64 0.2 0.9185
128 0.2 0.9107
16 0.2 0.9272
8 0.2 0.9310
4 0.2 0.9308
8 0.1 0.9301

增加隐藏层

隐藏层数 隐藏层神经元数 激活函数 batch_size w learning_rate accuracy
1 10 tanh 64 0 0.3 0.937
1 20 tanh 64 0 0.3 0.853
1 30 tanh 64 0 0.3 0.9638
1 30 tanh 32 0 0.3 0.961
1 30 tanh 48 0 0.3 0.962
1 30 tanh 128 0 0.3 0.962
1 40 tanh 64 0 0.3 0.967
1 50 tanh 64 0 0.3 0.798
1 32 tanh 64 0 0.3 0.962
2 10 4 tanh tanh 64 0 0.3 0.868
2 20 10 tanh tanh 64 0 0.6 0.905

Q1:weight初试化为0,网络由于对称性实际上可以再压缩