TensorFlow如何实现反向传播
作者:lilongsy 发布时间:2023-07-04 08:44:36
标签:TensorFlow,反向传播
使用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 plt
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
ops.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.
# 生成数据,创建占位符和变量A
x_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 graph
sess = 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 function
my_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)
# 初始化变量A
init = 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
来源:http://blog.csdn.net/lilongsy/article/details/79258470


猜你喜欢
- 什么是标签平滑?在PyTorch中如何去使用它?在训练深度学习模型的过程中,过拟合和概率校准(probability calibration
- Go-操作redis安装golang操作redis的客户端包有多个比如redigo、go-redis,github上Star最多的莫属red
- read()方法读取文件size个字节大小。如果读取命中获得EOF大小字节之前,那么它只能读取可用的字节。语法以下是read()
- fromkeys()方法类似于列表的浅拷贝首先用该方法创建一个字典dict_ = dict.fromkeys(('a',
- 本文实例为大家分享了bootstrap响应式工具的具体代码,供大家参考,具体内容如下<!DOCTYPE html><htm
- 使用Django的ORM操作的时候,想要获取本条,上一条,下一条。初步的想法是写3个ORM,3个ORM如下:本条:models.Obj.ob
- 在我的博客上,以前我经常谈到SQL Serverl里的书签查找,还有它们带来的很多问题。在今天的文章里,我想从性能角度进一步谈下书签查找,还
- 本文实例讲述了Python松散正则表达式用法。分享给大家供大家参考,具体如下:Python 允许用户利用所谓的 松散正则表达式来完成这个任务
- 按照正常的产品逻辑,我们在进行页面切换时滚动条应该是在页面顶部的,可是。。。在使用vue-router进行页面切换时,发现滚动条所处的位置被
- 大家都知道,数据库的安全性是很重要的,它直接影响到数据库的广泛应用。用户可以采用任意一种方法来保护数据库应用程序,也可以将几种方法结合起来使
- 本文主要讲解的是表单,这个其实对于做过网站的人来说,并不陌生,而且可以说是最为常用的提交数据的Form表单。本文主要来讲解一下内容:1.基本
- reshape函数:改变数组的维数(注意不是shape大小)>>> e= np.arange(10)>>>
- 我们可以把全体人数当作一个集合,想要往其中加入新人有不同的增加方式。可以一周增加一次,也可以集中到月底一起加入集体。我们今天所要讲的在pyt
- let str = '这是一个字符串[html]语句;[html]字符串很常见';alert(str.replace(/\[
- 那怎么开始设计一个合格的类呢,一开始就写class{}的都错了,正确的是什么都不写,而是假设这个类已经存在,这个对象已经存在,各种属性方法都
- 一、安装MySQL的注意事项官网下载安装,选择zip包,解压后不用安装只用配置好环境变量Path并在解压后的文件夹里新建文本文档my.ini
- 起源就在今年9月份,我负责的部门平台项目发布了一个新版本,该版本同时上线了一个新功能,简单说有点类似定时任务。头一天一切正常,但第二天出现了
- 本文实例讲述了Python装饰器decorator用法。分享给大家供大家参考。具体分析如下:1. 闭包(closure)闭包是Python所
- 我就废话不多说了,直接上代码吧!from numpy import *import numpy as npimport cv2, os, m
- js原生获取css样式,并且设置,看似简单,其实并不简单,我们平时用的ele.style.样式,只能获取内嵌的样式,但是我们写的样式基本都在