在Tensorflow中实现梯度下降法更新参数值

 更新时间:2020年01月23日 18:07:20   作者:勿在浮沙筑高台LS  
今天小编就为大家分享一篇在Tensorflow中实现梯度下降法更新参数值,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

我就废话不多说了,直接上代码吧!

tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

TensorFlow经过使用梯度下降法对损失函数中的变量进行修改值,默认修改tf.Variable(tf.zeros([784,10]))

为Variable的参数。

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy,var_list=[w,b])

也可以使用var_list参数来定义更新那些参数的值

#导入Minst数据集
import input_data
mnist = input_data.read_data_sets("data",one_hot=True)
 
#导入tensorflow库
import tensorflow as tf
 
#输入变量,把28*28的图片变成一维数组(丢失结构信息)
x = tf.placeholder("float",[None,784])
 
#权重矩阵,把28*28=784的一维输入,变成0-9这10个数字的输出
w = tf.Variable(tf.zeros([784,10]))
#偏置
b = tf.Variable(tf.zeros([10]))
 
#核心运算,其实就是softmax(x*w+b)
y = tf.nn.softmax(tf.matmul(x,w) + b)
 
#这个是训练集的正确结果
y_ = tf.placeholder("float",[None,10])
 
#交叉熵,作为损失函数
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
 
#梯度下降算法,最小化交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
 
#初始化,在run之前必须进行的
init = tf.initialize_all_variables()
#创建session以便运算
sess = tf.Session()
sess.run(init)
 
#迭代1000次
for i in range(1000):
 #获取训练数据集的图片输入和正确表示数字
 batch_xs, batch_ys = mnist.train.next_batch(100)
 #运行刚才建立的梯度下降算法,x赋值为图片输入,y_赋值为正确的表示数字
 sess.run(train_step,feed_dict = {x:batch_xs, y_: batch_ys})
 
#tf.argmax获取最大值的索引。比较运算后的结果和本身结果是否相同。
#这步的结果应该是[1,1,1,1,1,1,1,1,0,1...........1,1,0,1]这种形式。
#1代表正确,0代表错误
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
 
#tf.cast先将数据转换成float,防止求平均不准确。
#tf.reduce_mean由于只有一个参数,就是上面那个数组的平均值。
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
#输出
print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_: mnist.test.labels}))

计算结果如下

"C:\Program Files\Anaconda3\python.exe" D:/pycharmprogram/tensorflow_learn/softmax_learn/softmax_learn.py
Extracting data\train-images-idx3-ubyte.gz
Extracting data\train-labels-idx1-ubyte.gz
Extracting data\t10k-images-idx3-ubyte.gz
Extracting data\t10k-labels-idx1-ubyte.gz
WARNING:tensorflow:From C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\util\tf_should_use.py:175: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
2018-05-14 15:49:45.866600: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2018-05-14 15:49:45.866600: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
0.9163
 
Process finished with exit code 0

如果限制,只更新参数W查看效果

"C:\Program Files\Anaconda3\python.exe" D:/pycharmprogram/tensorflow_learn/softmax_learn/softmax_learn.py
Extracting data\train-images-idx3-ubyte.gz
Extracting data\train-labels-idx1-ubyte.gz
Extracting data\t10k-images-idx3-ubyte.gz
Extracting data\t10k-labels-idx1-ubyte.gz
WARNING:tensorflow:From C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\util\tf_should_use.py:175: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
2018-05-14 15:51:08.543600: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2018-05-14 15:51:08.544600: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
0.9187
 
Process finished with exit code 0

可以看出只修改W对结果影响不大,如果设置只修改b

#导入Minst数据集
import input_data
mnist = input_data.read_data_sets("data",one_hot=True)
 
#导入tensorflow库
import tensorflow as tf
 
#输入变量,把28*28的图片变成一维数组(丢失结构信息)
x = tf.placeholder("float",[None,784])
 
#权重矩阵,把28*28=784的一维输入,变成0-9这10个数字的输出
w = tf.Variable(tf.zeros([784,10]))
#偏置
b = tf.Variable(tf.zeros([10]))
 
#核心运算,其实就是softmax(x*w+b)
y = tf.nn.softmax(tf.matmul(x,w) + b)
 
#这个是训练集的正确结果
y_ = tf.placeholder("float",[None,10])
 
#交叉熵,作为损失函数
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
 
#梯度下降算法,最小化交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy,var_list=[b])
 
#初始化,在run之前必须进行的
init = tf.initialize_all_variables()
#创建session以便运算
sess = tf.Session()
sess.run(init)
 
#迭代1000次
for i in range(1000):
 #获取训练数据集的图片输入和正确表示数字
 batch_xs, batch_ys = mnist.train.next_batch(100)
 #运行刚才建立的梯度下降算法,x赋值为图片输入,y_赋值为正确的表示数字
 sess.run(train_step,feed_dict = {x:batch_xs, y_: batch_ys})
 
#tf.argmax获取最大值的索引。比较运算后的结果和本身结果是否相同。
#这步的结果应该是[1,1,1,1,1,1,1,1,0,1...........1,1,0,1]这种形式。
#1代表正确,0代表错误
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
 
#tf.cast先将数据转换成float,防止求平均不准确。
#tf.reduce_mean由于只有一个参数,就是上面那个数组的平均值。
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
#输出
print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_: mnist.test.labels}))

计算结果:

"C:\Program Files\Anaconda3\python.exe" D:/pycharmprogram/tensorflow_learn/softmax_learn/softmax_learn.py
Extracting data\train-images-idx3-ubyte.gz
Extracting data\train-labels-idx1-ubyte.gz
Extracting data\t10k-images-idx3-ubyte.gz
Extracting data\t10k-labels-idx1-ubyte.gz
WARNING:tensorflow:From C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\util\tf_should_use.py:175: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
2018-05-14 15:52:04.483600: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2018-05-14 15:52:04.483600: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
0.1135
 
Process finished with exit code 0

如果只更新b那么对效果影响很大。

以上这篇在Tensorflow中实现梯度下降法更新参数值就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Python flask-script 模块详解

    Python flask-script 模块详解

    Flask Script扩展提供向Flask插入外部脚本的功能,这篇文章主要介绍了Flask之flask-script模块使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-11-11
  • python不带重复的全排列代码

    python不带重复的全排列代码

    输入起始数字和结束数字将数组全排列,需要的朋友可以参考下
    2013-08-08
  • python调用系统中应用程序的函数示例

    python调用系统中应用程序的函数示例

    这篇文章主要为大家介绍了python调用系统中应用程序详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • python使用Matplotlib绘制分段函数

    python使用Matplotlib绘制分段函数

    这篇文章主要为大家详细介绍了python使用Matplotlib绘制分段函数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-09-09
  • 十个Python自动化常用操作,即拿即用

    十个Python自动化常用操作,即拿即用

    这篇文章主要介绍了十个Python自动化常用操作,即拿即用,文中有非常详细的代码示例,对正在学习python的小伙伴们有很好的帮助哟,需要的朋友可以参考下
    2021-05-05
  • Python实现Matplotlib,Seaborn动态数据图的示例代码

    Python实现Matplotlib,Seaborn动态数据图的示例代码

    这篇文章主要为大家详细介绍了如何让Matplotlib、Seaborn的静态数据图动起来,变得栩栩如生。文中的示例代码讲解详细,感兴趣的小伙伴可以学习一下
    2022-05-05
  • Ubuntu16.04/树莓派Python3+opencv配置教程(分享)

    Ubuntu16.04/树莓派Python3+opencv配置教程(分享)

    下面小编就为大家分享一篇Ubuntu16.04/树莓派Python3+opencv配置教程。具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-04-04
  • pytorch sampler对数据进行采样的实现

    pytorch sampler对数据进行采样的实现

    今天小编就为大家分享一篇pytorch sampler对数据进行采样的实现,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • Python使用PDFMiner解析PDF代码实例

    Python使用PDFMiner解析PDF代码实例

    本篇文章主要介绍了Python使用PDFMiner解析PDF代码实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-03-03
  • 详谈python中subprocess shell=False与shell=True的区别

    详谈python中subprocess shell=False与shell=True的区别

    这篇文章主要介绍了详谈python中subprocess shell=False与shell=True的区别说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-04-04

最新评论