Tensorflow-DNN

1、使用softmax

#!/usr/bin/python3
# -*- coding:utf-8 -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

"""
多层感知
"""

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# mnist图像大小是28x28 分成0~9 共10类
x=tf.placeholder(tf.float32,[None,28*28*1])
y_=tf.placeholder(tf.float32,[None,10])

with tf.variable_scope('wb'):
    w=tf.get_variable('w',[28*28,128],initializer=tf.random_uniform_initializer)*0.001
    b=tf.Variable(tf.zeros([128])+0.1,dtype=tf.float32)
with tf.variable_scope('wb2'):
    w2 = tf.get_variable('w2', [128, 10], initializer=tf.random_uniform_initializer) * 0.001
    b2=tf.Variable(tf.zeros([10])+0.1,dtype=tf.float32)

y=tf.nn.relu(tf.add(tf.matmul(x,w),b))
y=tf.nn.softmax(tf.add(tf.matmul(y,w2),b2))

loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y))

train_op=tf.train.AdamOptimizer(0.1).minimize(loss)

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

sess=tf.InteractiveSession(graph=tf.get_default_graph())

tf.global_variables_initializer().run()

for step in range(10000):
    batch_xs, batch_ys = mnist.train.next_batch(128)
    train_op.run({x:batch_xs,y_:batch_ys})
    if step % 1000==0:
        print("step",step,'acc',accuracy.eval({x:batch_xs,y_:batch_ys}),'loss',loss.eval({x:batch_xs,y_:batch_ys}))

# test acc
print('test acc',accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))

sess.close()

结果:
这里写图片描述

2、不使用softmax

y=tf.nn.relu(tf.add(tf.matmul(x,w),b))
# y=tf.nn.softmax(tf.add(tf.matmul(y,w2),b2))
y=tf.add(tf.matmul(y,w2),b2)

这里写图片描述

说明:上面的多层感知,其实只有一个隐藏层,如果觉得精度不够,可以参考下面的提到的方法进行修改!
一般设计网络解决问题,都是从简单到复杂,从最简单的logical 回归开始,如果精度达不到要求,主要从以下几个方面入手:
①调学习效率
②加大训练步数
③修改batch size 2^n (16~512)
④修改隐藏单元节点数 (满足2^n )
⑤加深神经层 重复①~④步

其他:加入归一化、正则化,数据增强等

以后会专门讲一些我所知道的调参和神经网络的设计!

另外补充说明:
一般sigmoid 与softmax 仅用于分类问题 输出层(也可以不使用) ,注 是分类的最后一层,对于隐藏层不要使用,回归时不要使用,其中sigmoid用于二分类,softmax用于多分类(包括二分类,二分类时,softmax就是sigmoid 数学表达式一样)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值