用tensorflow实现的,基于mnist数据集上的一个简易模型

如果设
x 为原始图像
W1为第一层的权重
b1 为第一层的bias
W2 为第二层的权重
b2 为第二层的bias
y 为神经网络的输出
那么,这个简单的小模型可以表述为
y=softmax(tanh(xW1+b1)+b2)
用tanh可以让输出有正有负,个人觉得对第二层效果可能会更好。

实现的代码如下,注释应该算详尽了


import input_data
import tensorflow as tf

# load the dataset
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)



# functions used to initialize variables
def Weight(shape):
    standard_distribution = tf.truncated_normal(shape, stddev = 0.1,
                                                dtype = tf.float64)
    return tf.Variable(standard_distribution)
def Placeholder(shape):
    return tf.placeholder(tf.float64, shape)



# declare variables

# input
x = Placeholder([None, 784])

# parameters
W_layer1 = Weight([784, 25])
b_layer1 = Weight([25])
W_layer2 = Weight([25, 10])
b_layer2 = Weight([10])

# output
y_layer1 = tf.nn.tanh(tf.matmul(x, W_layer1) + b_layer1)
y_layer2 = tf.nn.softmax(tf.matmul(y_layer1, W_layer2) + b_layer2)
y = y_layer2

# answer
answer = Placeholder([None, 10])

# loss
loss = -tf.reduce_sum(answer * tf.log(y))   # cross entropy

# train
train = tf.train.GradientDescentOptimizer(0.01).minimize(loss)  # alpha = 0.01

# session
sess = tf.InteractiveSession()



# evalutate
def Eval():
    correct = tf.equal(tf.argmax(y, 1), tf.argmax(answer, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, tf.float64))
    print(accuracy.eval(feed_dict = {x: mnist.test.images,
                                     answer: mnist.test.labels}))

# main routine
sess.run(tf.global_variables_initializer()) # initiate
for i in range(1000):
    if( i % 100 == 0 ):
        Eval();
    batch = mnist.train.next_batch(50)
    train.run(feed_dict = {x: batch[0], answer: batch[1]})

Eval();

最终的正确率是93.21%,比官方的那个没有隐藏层的那个版本(准确率大约在91%)效果好一些。而且训练的特别快。

下面考虑加一些奇技淫巧来优化一下。
1:batch的大小改为100,准确率94.23%
2:batch的大小改为200,准确率95.39%
3:batch的大小改为500,准确率却下去了,变成了70.59%

那么,就让batch的大小一直是200吧0.0
下面再试试增加迭代的次数到2000

0: 0.0914
100: 0.811
200: 0.911
300: 0.9303
400: 0.9396
500: 0.9455
600: 0.942
700: 0.9441
800: 0.9423
900: 0.9464
1000: 0.945
1100: 0.9514
1200: 0.9496
1300: 0.9512
1400: 0.9523
1500: 0.9492
1600: 0.9544
1700: 0.9549
1800: 0.9518
1900: 0.952
2000: 0.9543

发现在94%到95%的部分一直在震荡,这说明学习率太高了。然而我调了一会,发现学习率再怎么变也没什么卵用,可能是我调参姿势有问题。

就这样吧,正确率95.4%,也是一个不差的结果了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值