TensorFlow-深度学习-08-人工神经网络(ANN)-多层感知器(MLP)

本文与TensorFlow-深度学习-03-梯度下降(反向传播–BP)其实没有什么差别,主要差别在于使用了softmax函数进行梯度下降求解。

实例:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("mnist/", one_hot=True)


def ann_demo():
    hidden_num = 50
    x = tf.placeholder(shape=[None, 784], dtype=tf.float32)
    y = tf.placeholder(shape=[None, 10], dtype=tf.float32)

    '''----------第一层隐层----------'''
    w1 = tf.Variable(tf.random_normal(shape=[784, hidden_num]), dtype=tf.float32)
    b1 = tf.Variable(tf.random_normal(shape=[1, hidden_num]), dtype=tf.float32)


    '''---------第二层隐层-----------'''
    w2 = tf.Variable(tf.random_normal(shape=[hidden_num, 10]), dtype=tf.float32)
    b2 = tf.Variable(tf.random_normal(shape=[1, 10]), dtype=tf.float32)

    nn1 = tf.add(tf.matmul(x, w1), b1)
    out1 = tf.nn.softmax(nn1)

    nn2 = tf.add(tf.matmul(out1, w2), b2)
    out = tf.nn.softmax(nn2)  # 使用激活函数输出预测值


    diff = tf.subtract(y, out)  # 真实值和预测值之间的差值
    loss = tf.reduce_sum(tf.square(diff))  # 把差值平方

    step = tf.train.GradientDescentOptimizer(learning_rate=0.05).minimize(loss)

    acc_mat = tf.equal(tf.argmax(y, 1), tf.argmax(out, 1))
    acc_ret = tf.reduce_sum(tf.cast(acc_mat, dtype=tf.float32))
    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        batch_size = 128
        for i in range(20000):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(step, feed_dict={x: batch_xs, y: batch_ys})
            if (i + 1) % 2000 == 0:
                curr_acc, curr_loss = sess.run([acc_ret, loss],
                                               feed_dict={x: mnist.test.images[:1000], y: mnist.test.labels[:1000]})
                print("curr_acc:", curr_acc/10,"%", "curr_loss:", curr_loss)


if __name__ == "__main__":
    ann_demo()

运行结果:
在这里插入图片描述
结果其实并不是很尽如人意,因为对于简单的人工神经网络来说,一般3层就是最多的,训练次数也会随着loss函数的左右移动而达到一个稳态,训练就会终止。因此,对于大型的数据集,最好不要使用简单的人工神经网络来训练。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值