单个神经元相关总结

Graph图的一些操作

注意:

import tensorflow as tf
c = tf.constant(0.0)
g = tf.Graph()
with g.as_default():
    c1 = tf.constant(0.0)
    print(c1.graph)
    print(g)
    print(c.graph)
    g3 = tf.get_default_graph()#获取为新创建的图
    print(g3)

使用softmax分类时,需要将目标分为几类,就在最后这层放几个节点。

损失函数

  • 均值平方差(每一个真实值与预测值相减的平方取平均值)
  • 交叉熵(一般用于分类问题)

两者均为值越小,代表预测结果越准确。

在神经网络进行计算时,预测值要与真实值控制在同样的数据分布内,假设将预测值经过sigmoid激活函数得到的取值范围在0-1之间,那么真实值也应该归一化到0-1之间,这样在 做loss计算时才会有较好的效果。

损失算法的选取

损失函数的选取取决于输入标签数据的类型:如果输入的是实数,无界的值,损失函数使用平方差;如果输入的是位矢量(分类标志),使用交叉熵更合适。

梯度下降

在训练过程中,每次的正向传播后都会得到输出值与真实值的损失值,这个损失值越小,代表模型越好。于是梯度下降的算法就用在这里,帮助寻找最小的那个损失值,从而可以反推出学习参数w和b,达到优化模型的效果。

常用的梯度下降法可以分为:

  • 批量梯度下降
  • 随机梯度下降
  • 小批量梯度下降

批量梯度下降:遍历全部数据集计算以此损失函数,然后计算函数对各个参数的梯度和更新梯度。这种方法没更新一次参数,都要把数据集里的所有样本看一遍,计算量大,计算速度慢,不支持在线学习。

随机梯度下降:每看一个数据就计算一下损失函数,然后求梯度更新参数,这成为随机梯度下降。这个方法速度虽然比较快,但收敛性能不太好,可能在最优点附近晃来晃去,命中不到最优点。两次参数的更新也有可能相互抵消,造成目标函数震荡比较剧烈。

小批量梯度下降:为了克服上面两种方法的缺点,一般采用一种折中手段,小批量的梯度下降,这种方法把数据分为若干批,按批来更新参数,这样一批中的一组数据共同决定了本次梯度的方向,下降起来就不容易跑偏,减少了随机性。另一方面因为批的样本数与整个数据集相比小了很多,计算量也不是很大。

常用下降函数

tf.train.GradientDescentOptimizer(learningrate)
#一般的梯度下降算法
tf.train.AdamOptimizer(learningrate)
#Adam优化器

退化学习率

  • 当学习率的值过大时,训练速度会有所提升,但结果的精度不够。
  • 当学习率的值过小时,精度虽然提升了,但训练会耗费太多的时间。

那么我们如何平衡精度与速度呢? 可以采用退化学习率。

退化学习率又叫学习率衰减,它的本意是希望在训练过程中对于学习率大和小的优点都能为我们所用,也就是当训练刚开始的时候,使用大学习率加快速度,训练到一定程度后,使用小学习率来提高精度。

import tensorflow as tf
global_step = tf.Variable(0, trainable=False)
initial_learning_rate = 0.1
learning_rate = tf.train.exponential_decay(learning_rate=initial_learning_rate, global_step=global_step, decay_steps=10, decay_rate=0.9)
opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
global_step = global_step.assign_add(1)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(learning_rate)
    for i in range(20):
        g, rate = sess.run([global_step, learning_rate])
        print(g, rate)
Tensor("ExponentialDecay:0", shape=(), dtype=float32)
1 0.1
2 0.09895193
3 0.09791484
4 0.09688862
5 0.095873155
6 0.094868325
7 0.09387404
8 0.092890166
9 0.09191661
10 0.09095325
11 0.089999996
12 0.08812335
13 0.087199755
14 0.087199755
15 0.08628584
16 0.0853815
17 0.08448663
18 0.08360115
19 0.08272495
20 0.08185793

可以看到学习率在不断减小。

初始化学习参数

一般的常用初始化函数为tf.truncated_normal函数以及tf.truncated_normal_initializar函数,因为该函数具有截断功能,以生成相对比较温和的初始值。

使用maxout网络进行实现MNIST分类

Maxout网络是将激活函数变成一个网络选择器,原理就是将多个神经元并列的放在一起,从他们的输出结果中找到最大的那个,代表对特征相应最为敏感。然后去这个神经元的结果参与后面的运算。

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

import tensorflow as tf #导入tensorflow库

def max_out(inputs, num_units, axis=None):
    shape = inputs.get_shape().as_list()
    if shape[0] is None:
        shape[0] = -1
    if axis is None:  # Assume that channel is the last dimension
        axis = -1
    num_channels = shape[axis]
    if num_channels % num_units:
        raise ValueError('number of features({}) is not '
                         'a multiple of num_units({})'.format(num_channels, num_units))
    shape[axis] = num_units
    shape += [num_channels // num_units]
    outputs = tf.reduce_max(tf.reshape(inputs, shape), -1, keep_dims=False)
    return outputs


tf.reset_default_graph()
# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data维度 28*28=784
y = tf.placeholder(tf.int32, [None, 10]) # 0-9 数字=> 10 classes

# Set model weights
W = tf.Variable(tf.random_normal([784, 100]))
b = tf.Variable(tf.zeros([100]))


z= tf.matmul(x, W) + b
#maxout = tf.reduce_max(z,axis= 1,keep_dims=True)

maxout= max_out(z, 50)

# Set model weights
W2 = tf.Variable(tf.truncated_normal([50, 10], stddev=0.1))
b2 = tf.Variable(tf.zeros([10]))
# 构建模型
#pred = tf.nn.softmax(tf.matmul(maxout, W2) + b2)
pred = tf.matmul(maxout, W2) + b2
# 构建模型
pred = tf.nn.softmax(pred) # Softmax分类

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred))

#参数设置
learning_rate = 0.01
# 使用梯度下降优化器
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)


training_epochs = 500
batch_size = 100
display_step = 1

correct_prediction = tf.equal(tf.argmax(pred,1), tf.argmax(y, 1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# 启动session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())# Initializing OP

    # 启动循环开始训练
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # 遍历全部数据集
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys})
            # Compute average loss
            avg_cost += c / total_batch
        # 显示训练中的详细信息
        if (epoch+1) % display_step == 0:
            print ("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
            print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))
    print( " Finished!")
发布了267 篇原创文章 · 获赞 51 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/AcSuccess/article/details/89448784