在TensorFlow的优化器中, 都要设置学习率。学习率是在精度和速度之间找到一个平衡:

学习率太大,训练的速度会有提升,但是结果的精度不够,而且还可能导致不能收敛出现震荡的情况。

学习率太小,精度会有所提升,但是训练的速度慢,耗费较多的时间。

因而我们可以使用退化学习率,又称为衰减学习率。它的作用是在训练的过程中,对学习率的值进行衰减,训练到达一定程度后,使用小的学习率来提高精度。

在TensorFlow中的方法如下:tf.train.exponential_decay(),该方法的参数如下:

learning_rate, 初始的学习率的值

global_step, 迭代步数变量

decay_steps, 带迭代多少次进行衰减

decay_rate, 迭代decay_steps次衰减的值

staircase=False, 默认为False,为True则不衰减

例如

tf.train.exponential_decay(initial_learning_rate, global_step=global_step, decay_steps=1000, decay_rate=0.9)表示没经过1000次的迭代,学习率变为原来的0.9。

增大批次处理样本的数量也可以起到退化学习率的作用。

下面我们写了一个例子,每迭代10次,则较小为原来的0.5,代码如下:

import tensorflow as tf
import numpy as np global_step = tf.Variable(0, trainable=False)
initial_learning_rate = 0.1 learning_rate = tf.train.exponential_decay(initial_learning_rate,
global_step=global_step,
decay_steps=10,
decay_rate=0.5) opt = tf.train.GradientDescentOptimizer(learning_rate)
add_global = global_step.assign_add(1) with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(learning_rate)) for i in range(50):
g, rate = sess.run([add_global, learning_rate])
print(g, rate)

下面是程序的结果,我们发现没10次就变为原来的一般:

随后,又在MNIST上面进行了测试,发现使用学习率衰减使得准确率有较好的提升。代码如下:

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt mnist = input_data.read_data_sets('MNIST_data', one_hot=True) tf.reset_default_graph() x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10]) w = tf.Variable(tf.random_normal([784, 10]))
b = tf.Variable(tf.zeros([10])) pred = tf.matmul(x, w) + b
pred = tf.nn.softmax(pred) cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices=1)) global_step = tf.Variable(0, trainable=False)
initial_learning_rate = 0.1 learning_rate = tf.train.exponential_decay(initial_learning_rate,
global_step=global_step,
decay_steps=1000,
decay_rate=0.9) opt = tf.train.GradientDescentOptimizer(learning_rate)
add_global = global_step.assign_add(1) optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) training_epochs = 50
batch_size = 100 display_step = 1 with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) 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)
_, c, add, rate = sess.run([optimizer, cost, add_global, learning_rate], feed_dict={x:batch_xs, y:batch_ys})
avg_cost += c / total_batch if (epoch + 1) % display_step == 0:
print('epoch= ', epoch+1, ' cost= ', avg_cost, 'add_global=', add, 'rate=', rate)
print('finished') correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('accuracy: ', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))

在使用衰减学习率我们最后的精度达到0.8897,在使用固定的学习率时,精度只有0.8586。

TensorFlow——学习率衰减的使用方法的更多相关文章

  1. TensorFlow之DNN(二):全连接神经网络的加速技巧(Xavier初始化、Adam、Batch Norm、学习率衰减与梯度截断)

    在上一篇博客<TensorFlow之DNN(一):构建“裸机版”全连接神经网络>中,我整理了一个用TensorFlow实现的简单全连接神经网络模型,没有运用加速技巧(小批量梯度下降不算哦) ...

  2. Tensorflow实现学习率衰减

    Tensorflow实现学习率衰减 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 Deeplearning AI Andrew Ng Tensorflow1.2 API 学习率衰减 ...

  3. Adam和学习率衰减(learning learning decay)

    目录 梯度下降法更新参数 Adam 更新参数 Adam + 学习率衰减 Adam 衰减的学习率 References 本文先介绍一般的梯度下降法是如何更新参数的,然后介绍 Adam 如何更新参数,以及 ...

  4. 改善深层神经网络_优化算法_mini-batch梯度下降、指数加权平均、动量梯度下降、RMSprop、Adam优化、学习率衰减

    1.mini-batch梯度下降 在前面学习向量化时,知道了可以将训练样本横向堆叠,形成一个输入矩阵和对应的输出矩阵: 当数据量不是太大时,这样做当然会充分利用向量化的优点,一次训练中就可以将所有训练 ...

  5. Dropout和学习率衰减

         Dropout 在机器学习的模型中,如果模型的参数太多,而训练样本又太少,训练出来的模型很容易产生过拟合的现象.在训练神经网络的时候经常会遇到过拟合的问题,过拟合具体表现在:模型在训练数据上 ...

  6. [深度学习] pytorch学习笔记(3)(visdom可视化、正则化、动量、学习率衰减、BN)

    一.visdom可视化工具 安装:pip install visdom 启动:命令行直接运行visdom 打开WEB:在浏览器使用http://localhost:8097打开visdom界面 二.使 ...

  7. 权重衰减(weight decay)与学习率衰减(learning rate decay)

    本文链接:https://blog.csdn.net/program_developer/article/details/80867468“微信公众号” 1. 权重衰减(weight decay)L2 ...

  8. TensorFlow模型保存和加载方法

    TensorFlow模型保存和加载方法 模型保存 import tensorflow as tf w1 = tf.Variable(tf.constant(2.0, shape=[1]), name= ...

  9. 吴恩达深度学习笔记(五) —— 优化算法:Mini-Batch GD、Momentum、RMSprop、Adam、学习率衰减

    主要内容: 一.Mini-Batch Gradient descent 二.Momentum 四.RMSprop 五.Adam 六.优化算法性能比较 七.学习率衰减 一.Mini-Batch Grad ...

随机推荐

  1. X Samara Regional Intercollegiate Programming Contest

    A. Streets of Working Lanterns - 2 对于每个括号序列,存在一个\(mv\),表示要接上这个序列至少需要\(-mv\)个左括号,同时处理出接上这个序列后,左括号数量的增 ...

  2. 洛谷P3957 跳房子 题解 二分答案/DP/RMQ

    题目链接:https://www.luogu.org/problem/P3957 这道题目我用到了如下算法: 线段树求区间最大值: 二分答案: DP求每一次枚举答案g时是否能够找到 \(\ge k\) ...

  3. spark mllib docs,MLlib: RDD-based API

    MLlib: RDD-based API This page documents sections of the MLlib guide for the RDD-based API (the spar ...

  4. Python--day65--模板语言之filter

    参考的原文链接:http://www.cnblogs.com/liwenzhou/p/7931828.html Filters(过滤器) 在Django的模板语言中,通过使用 过滤器 来改变变量的显示 ...

  5. Element节点输出到System.out

    protected void writeElementToFile(Element valrespEle) { try { TransformerFactory transformerFactory ...

  6. Aizu 0531 "Paint Color" (坐标离散化+DFS or BFS)

    传送门 题目描述: 为了宣传信息竞赛,要在长方形的三合板上喷油漆来制作招牌. 三合板上不需要涂色的部分预先贴好了护板. 被护板隔开的区域要涂上不同的颜色,比如上图就应该涂上5种颜色. 请编写一个程序计 ...

  7. FatJar技术

    概念 将一个jar及其依赖的三方jar全部打到一个包中,这个包即为FatJar. 作用 作用: Jar包隔离,避免Jar冲突. 打包方式 maven-shade-plugin插件: spring-bo ...

  8. Dbvisualizer各种中文乱码问题解决方法

    1.SQL Commander里中文显示成‘口’ 解:进入Tools -> Tool Properties -> General -> Appearence -> Fonts, ...

  9. 两种方法,轻松上手ConfigMap!

    属性配置文件在任何应用程序中都非常重要.它们不仅可以让应用程序具备灵活性,还能够根据文件中配置的值产生不同的功能.实际上,在staging.开发.测试.UAT或生产环境中,我们都使用属性配置文件来驱动 ...

  10. How to use code to exit the application in UWP

    I will tell you how to exit the application in UWP by the code. We can call some static method to he ...