侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

TensorFlow如何实现反向传播

技术  /  管理员 发布于 7年前   165

使用TensorFlow的一个优势是,它可以维护操作状态和基于反向传播自动地更新模型变量。
TensorFlow通过计算图来更新变量和最小化损失函数来反向传播误差的。这步将通过声明优化函数(optimization function)来实现。一旦声明好优化函数,TensorFlow将通过它在所有的计算图中解决反向传播的项。当我们传入数据,最小化损失函数,TensorFlow会在计算图中根据状态相应的调节变量。

回归算法的例子从均值为1、标准差为0.1的正态分布中抽样随机数,然后乘以变量A,损失函数为L2正则损失函数。理论上,A的最优值是10,因为生成的样例数据均值是1。

二个例子是一个简单的二值分类算法。从两个正态分布(N(-1,1)和N(3,1))生成100个数。所有从正态分布N(-1,1)生成的数据标为目标类0;从正态分布N(3,1)生成的数据标为目标类1,模型算法通过sigmoid函数将这些生成的数据转换成目标类数据。换句话讲,模型算法是sigmoid(x+A),其中,A是要拟合的变量,理论上A=-1。假设,两个正态分布的均值分别是m1和m2,则达到A的取值时,它们通过-(m1+m2)/2转换成到0等距的值。后面将会在TensorFlow中见证怎样取到相应的值。

同时,指定一个合适的学习率对机器学习算法的收敛是有帮助的。优化器类型也需要指定,前面的两个例子会使用标准梯度下降法,它在TensorFlow中的实现是GradientDescentOptimizer()函数。

# 反向传播#----------------------------------## 以下Python函数主要是展示回归和分类模型的反向传播import matplotlib.pyplot as pltimport numpy as npimport tensorflow as tffrom tensorflow.python.framework import opsops.reset_default_graph()# 创建计算图会话sess = tf.Session()# 回归算法的例子:# We will create sample data as follows:# x-data: 100 random samples from a normal ~ N(1, 0.1)# target: 100 values of the value 10.# We will fit the model:# x-data * A = target# Theoretically, A = 10.# 生成数据,创建占位符和变量Ax_vals = np.random.normal(1, 0.1, 100)y_vals = np.repeat(10., 100)x_data = tf.placeholder(shape=[1], dtype=tf.float32)y_target = tf.placeholder(shape=[1], dtype=tf.float32)# Create variable (one model parameter = A)A = tf.Variable(tf.random_normal(shape=[1]))# 增加乘法操作my_output = tf.multiply(x_data, A)# 增加L2正则损失函数loss = tf.square(my_output - y_target)# 在运行优化器之前,需要初始化变量init = tf.global_variables_initializer()sess.run(init)# 声明变量的优化器my_opt = tf.train.GradientDescentOptimizer(0.02)train_step = my_opt.minimize(loss)# 训练算法for i in range(100):  rand_index = np.random.choice(100)  rand_x = [x_vals[rand_index]]  rand_y = [y_vals[rand_index]]  sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})  if (i+1)%25==0:    print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)))    print('Loss = ' + str(sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})))# 分类算法例子# We will create sample data as follows:# x-data: sample 50 random values from a normal = N(-1, 1)#     + sample 50 random values from a normal = N(1, 1)# target: 50 values of 0 + 50 values of 1.#     These are essentially 100 values of the corresponding output index# We will fit the binary classification model:# If sigmoid(x+A) < 0.5 -> 0 else 1# Theoretically, A should be -(mean1 + mean2)/2# 重置计算图ops.reset_default_graph()# Create graphsess = tf.Session()# 生成数据x_vals = np.concatenate((np.random.normal(-1, 1, 50), np.random.normal(3, 1, 50)))y_vals = np.concatenate((np.repeat(0., 50), np.repeat(1., 50)))x_data = tf.placeholder(shape=[1], dtype=tf.float32)y_target = tf.placeholder(shape=[1], dtype=tf.float32)# 偏差变量A (one model parameter = A)A = tf.Variable(tf.random_normal(mean=10, shape=[1]))# 增加转换操作# Want to create the operstion sigmoid(x + A)# Note, the sigmoid() part is in the loss functionmy_output = tf.add(x_data, A)# 由于指定的损失函数期望批量数据增加一个批量数的维度# 这里使用expand_dims()函数增加维度my_output_expanded = tf.expand_dims(my_output, 0)y_target_expanded = tf.expand_dims(y_target, 0)# 初始化变量Ainit = tf.global_variables_initializer()sess.run(init)# 声明损失函数 交叉熵(cross entropy)xentropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=my_output_expanded, labels=y_target_expanded)# 增加一个优化器函数 让TensorFlow知道如何更新和偏差变量my_opt = tf.train.GradientDescentOptimizer(0.05)train_step = my_opt.minimize(xentropy)# 迭代for i in range(1400):  rand_index = np.random.choice(100)  rand_x = [x_vals[rand_index]]  rand_y = [y_vals[rand_index]]  sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})  if (i+1)%200==0:    print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)))    print('Loss = ' + str(sess.run(xentropy, feed_dict={x_data: rand_x, y_target: rand_y})))# 评估预测predictions = []for i in range(len(x_vals)):  x_val = [x_vals[i]]  prediction = sess.run(tf.round(tf.sigmoid(my_output)), feed_dict={x_data: x_val})  predictions.append(prediction[0])accuracy = sum(x==y for x,y in zip(predictions, y_vals))/100.print('最终精确度 = ' + str(np.round(accuracy, 2)))

输出:

Step #25 A = [ 6.12853956]Loss = [ 16.45088196]Step #50 A = [ 8.55680943]Loss = [ 2.18415046]Step #75 A = [ 9.50547695]Loss = [ 5.29813051]Step #100 A = [ 9.89214897]Loss = [ 0.34628963]Step #200 A = [ 3.84576249]Loss = [[ 0.00083012]]Step #400 A = [ 0.42345378]Loss = [[ 0.01165466]]Step #600 A = [-0.35141727]Loss = [[ 0.05375391]]Step #800 A = [-0.74206048]Loss = [[ 0.05468176]]Step #1000 A = [-0.89036471]Loss = [[ 0.19636908]]Step #1200 A = [-0.90850282]Loss = [[ 0.00608062]]Step #1400 A = [-1.09374011]Loss = [[ 0.11037558]]最终精确度 = 1.0

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    用十张图详解TensorFlow数据读取机制(附代码)
    下一条:
    tensorflow TFRecords文件的生成和读取的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(1个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(1个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客