Tensorflow tf.gradients 详解

TensorFlow工业级交付:从SavedModel到Serving的工程实践 SavedModel是TensorFlow模型交付的核心格式,它不仅封装权重与计算图,更定义了输入输出的严格接口契约,支撑可复现、可验证、可回滚的MLOps流程。其原理基于协议缓冲区(PB)描述完整执行语义,并通过签名(Signature)和资产(Assets)实现环境无关的自包含部署。技术价值在于统一训练、验证、服务与端侧适配链路,显著降低跨平台集成成本。典型应用场景包括制造业缺陷识别、医疗影像推理、金融风控模型上线等对稳定性与合规性要求严苛的领域。本文聚焦TensorFlow在真实产线中围绕SavedM 阅读详情

tf.gradients

gradients(
ys,
xs,
grad_ys=None,
name=‘gradients’,
colocate_gradients_with_ops=False,
gate_gradients=False,
aggregation_method=None
)
在 xs 中构造了 ys 的 w.r.t. x 和的符号偏导数.
ys 和 xs 是一个张量或一个张量的列表.grad_ys 是一个张量列表,持有由 ys 接收的梯度.该列表必须与 ys 具有相同长度.

gradients() 向图形添加操作以输出 ys 相对于的偏导数 xs.它返回长度为 len (xs) 的张量列表,其中每个张量 ys 中 y 的 sum(dy/dx).
grad_ys 是与 ys 相同长度的张量列表,它包含 y 的初始梯度.当 grad_ys 是 None 时,我们在 ys 中为每个 y 填入一个1的形状的张量.用户可以提供自己的初始 grad_ys,使用不同的初始梯度为每个 y 计算导数 (例如:如果你想为每个 y 中的每个值不同地加权梯度).

参数:

ys:要区分的张量或者张量列表.
xs:用于微分的张量或者张量列表.
grad_ys:(可选)与 ys 具有相同大小的张量或张量列表,并且对 ys 中的每个 y 计算的梯度.
name:用于将所有渐变操作组合在一起的可选名称.默认为“渐变”.
colocate_gradients_with_ops:如果为 True,请尝试使用相应的操作对齐梯度.
gate_gradients:如果为True,则在操作返回的梯度周围添加一个元组.这避免了一些竞态条件.
aggregation_method:指定用于组合渐变项的方法.接受的值是在类 AggregationMethod 中定义的常量.

返回值:
该函数返回 xs 中每个 x 的 sum(dy/dx) 的列表.

可能引发的异常:
LookupError:如果 x 和 y 之间的一个操作是没有注册的梯度函数.
ValueError:如果参数无效.

对求导函数而言,其主要功能即求导公式:∂y/∂x。在tensorflow中,y和x都是tensor。
更进一步,tf.gradients()接受求导值ys和xs不仅可以是tensor,还可以是list,形如[tensor1, tensor2, …, tensorn]。当ys和xs都是list时,它们的求导关系为:
gradients() adds ops to the graph to output the derivatives of ys with respect to xs. It returns a list of Tensor of length len(xs) where each tensor is the sum(dy/dx) for y in ys.

意思是:
1 tf.gradients()实现ys对xs求导
2.求导返回值是一个list,list的长度等于len(xs)
3.假设返回值是[grad1, grad2, grad3],ys=[y1, y2],xs=[x1, x2, x3]。则,真实的计算过程为:
grad1=∂y1/∂x1+∂y2/∂x1
grad2=∂y1/∂x2+∂y2/∂x2
grad3=∂y1/∂x3+∂y2/∂x3

测试1如下:
import tensorflow as tf
tf.reset_default_graph()
w1 = tf.get_variable(‘w1’, shape=[3])
w2 = tf.get_variable(‘w2’, shape=[3])

w3 = tf.get_variable(‘w3’, shape=[3])
w4 = tf.get_variable(‘w4’, shape=[3])

z1 = 3 * w1 + 2 * w2+ w3
z2 = -1 * w3 + w4

grads = tf.gradients([z1, z2], [w1, w2, w3, w4])

with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(grads))

输出:
[array([3., 3., 3.], dtype=float32), array([2., 2., 2.], dtype=float32), array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32)]

计算过程如下:
array([3., 3., 3.], dtype=float32)=z1/w1+z2/w1=3+0=3
array([2., 2., 2.], dtype=float32)=z1/w2+z2/w2=2+0=2
array([0., 0., 0.], dtype=float32)=z1/w3+z2/w3=1+(-1)=0
array([1., 1., 1.], dtype=float32)=z1/w4+z2/w4=0+1=1
因为w1,w2,w3,w4是3维的,所以返回的梯度Tensor也是3维的,例如:[3., 3., 3.]

测试2,加grad_ys测试:
import tensorflow as tf
tf.reset_default_graph()
w1 = tf.get_variable(‘w1’, shape=[3])
w2 = tf.get_variable(‘w2’, shape=[3])

w3 = tf.get_variable(‘w3’, shape=[3])
w4 = tf.get_variable(‘w4’, shape=[3])

z1 = 3 * w1 + 2 * w2+ w3
z2 = -1 * w3 + w4

grads = tf.gradients([z1, z2], [w1, w2, w3, w4], grad_ys=[[-2.0, -3.0, -4.0], [-1.0, -2.0, -3.0]])

with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(grads))

输出如下:
[array([ -6., -9., -12.], dtype=float32), array([-4., -6., -8.], dtype=float32), array([-1., -1., -1.], dtype=float32), array([-1., -2., -3.], dtype=float32)]

grad_ys 为什么是两个张量,因为grad_ys是和ys具有相同长度的。而这里ys有两个张量z1,z2,所以grad_ys也需要两个张量。

计算过程如下:
array([ -6., -9., -12.], dtype=float32)
-6= z1*(-2)/w1+z2*(-1)/w1=3*(-2)+0=-6
-9= z1*(-3)/w1+z2*(-2)/w1=3*(-3)+0=-9
-12= z1*(-4)/w1+z2*(-3)/w1=3*(-4)+0=-12

array([-4., -6., -8.], dtype=float32)
-4= z1*(-2)/w2+z2*(-1)/w2=2*(-2)+0=-4
-6= z1*(-3)/w2+z2*(-2)/w2=2*(-3)+0=-6
-8= z1*(-4)/w2+z2*(-3)/w2=2*(-4)+0=-8

array([-1., -1., -1.], dtype=float32)
-1= z1*(-2)/w3+z2*(-1)/w3=1*(-2)+(-1)(-1)=-1
-1= z1
(-3)/w3+z2*(-2)/w3=1*(-3)+(-2)(-1)=-1
-1= z1
(-4)/w3+z2*(-3)/w3=1*(-4)+(-3)*(-1)=-1

array([-1., -2., -3.], dtype=float32)
-1= z1*(-2)/w4+z2*(-1)/w4=0*(-2)+(1)(-1)=-1
-2= z1
(-3)/w4+z2*(-2)/w4=0*(-3)+(1)(-2)=-2
-3= z1
(-4)/w4+z2*(-3)/w4=0*(-4)+(1)*(-3)=-3

测试3:
import tensorflow as tf
weight = tf.Variable([[1., 2.]])
y = tf.matmul(weight, [[9.], [10.]])
grads = tf.gradients(y, weight)

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
grad_val = sess.run(grads)
print(grad_val)

输出:
[array([[ 9., 10.]], dtype=float32)]

测试4 stop_gradient:
a = tf.Variable(1.0)
b = tf.Variable(1.0)

c = tf.add(a, b)
c_stoped = tf.stop_gradient( c)
d = tf.add(a, b)
e = tf.add(c_stoped, d)

gradients = tf.gradients(e, xs=[a, b])

with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(gradients))

输出:
[1.0, 1.0]

测试5,stop_gradient的使用:
import tensorflow as tf
a = tf.Variable(1.0)
b = tf.Variable(1.0)

c = tf.add(a, b)

c_stoped = tf.stop_gradient( c)
d = tf.add(a, b)
e = tf.add(c, d)

gradients = tf.gradients(e, xs=[a, b])

with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(gradients))

输出:[2.0, 2.0]

测试6,高阶导数计算:
import tensorflow as tf
with tf.device(’/cpu:0’):
a = tf.constant(2.)
b = tf.pow(a, 2.)
grad = tf.gradients(ys=b, xs=a) # 一阶导
grad_2 = tf.gradients(ys=grad[0], xs=a) # 二阶导
grad_3 = tf.gradients(ys=grad_2[0], xs=a) # 三阶导

with tf.Session() as sess:
print(sess.run(grad))
print(sess.run(grad_2))
print(sess.run(grad_3))

输出:
[4.0]
[2.0]
[0.0]

计算过程如下:
a=2, b=a^2
grad=∂a^2/∂a=2a=2*2=4
grad_2=∂2a/∂a=2
grad_3=∂2/∂a=0

测试7:
import tensorflow as tf
a = tf.constant(0.)
b=2*a
c = a + b
g = tf.gradients(c, [a, b])

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(g))
输出:
[3.0, 1.0]

测试8:
import tensorflow as tf
a = tf.constant(0.)
b=2*a
g = tf.gradients(a + b, [a, b], stop_gradients=[a, b])

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(g))
输出:
[1.0, 1.0]

或者等价于下面的代码:
import tensorflow as tf
a = tf.stop_gradient(tf.constant(0.))
b = tf.stop_gradient(2 * a)
g = tf.gradients(a + b, [a, b])

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(g))

输出:[1.0, 1.0]

测试9:
import tensorflow as tf
tf.reset_default_graph()
weight1 = tf.get_variable(‘weight1’, shape=[2])
weight2 = tf.get_variable(‘weight2’, shape=[2])
weight3 = tf.get_variable(‘weight3’, shape=[2])
weight4 = tf.get_variable(‘weight4’, shape=[2])

a = weight1 + weight2
a_stopped = tf.stop_gradient(a)
y3 = a_stopped + weight3

gradients1 = tf.gradients(y3, [weight1, weight2, weight3], grad_ys=[tf.convert_to_tensor([1., 2.])])
gradients2 = tf.gradients(y3, [weight3], grad_ys=[tf.convert_to_tensor([1., 2.])])
print(gradients1) # [None, None, < tf.Tensor ‘gradients_1/grad_ys_0:0’ shape = (2,) dtype = float32 >]
print(gradients2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
‘’’
下面代码会报错
因为weight1、weight2 的梯度被停止,程序试图去求一个None的梯度,所以报错
注释掉求 gradients2 就又正确了
‘’’
#print(sess.run(gradients1))
print(sess.run(gradients2))

输出:
[None, None, <tf.Tensor ‘gradients/grad_ys_0:0’ shape=(2,) dtype=float32>]
[<tf.Tensor ‘gradients_1/grad_ys_0:0’ shape=(2,) dtype=float32>]
[array([1., 2.], dtype=float32)]

tensorflow API:梯度修剪apply_gradients和compute_gradients 梯度修剪主要避免训练梯度爆炸和消失问题 tf.train.XXXOptimizer compute_gradients Args: Returns: apply_gradients Args: Returns: 例子: 梯度修剪主要避免训练梯度爆炸和消失问题 tf.train.XXXOptimizer apply_gradients和compute_gradients... 阅读详情

相关推荐

tensorflow——optimizer.minimize()、optimizer.compute_gradients()、optimizer.apply_gradients()

优化函数 # 损失函数 loss = ... optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1) train_op =optimizer.minimize(loss) 其中minimize()包含两个步骤: 1.计算loss对指定val_list的梯度(导数),返回元组列表[(gradient,variable),…]...

sinat_37386947的博客 2万+

tensorflow—tf.gradients()简单实用教程

声明: 参考官方文档 参考tensorflow学习笔记(三十) 关于神经网络中的梯度计算,推荐吴恩达的deeplearning公开课 tf.gradients() 在tensorflow中,tf.gradients()的参数如下: tf.gradients(ys, xs, grad_ys=None, name='gradients...

hustqb的博客 6万+

Tensorflow中k.gradients()和tf.stop_gradient()用法说明

上周在实验室开荒某个代码,看到中间这么一段,对Tensorflow中的stop_gradient()还不熟悉,特此周末进行重新并总结。 y = xx + K.stop_gradient(rounded – xx) 这代码最终调用位置在tensoflow.python.ops.gen_array_ops.stop_gradient(input, name=None),关于这段代码为什么这样写的意义在文末给出。 【stop_gradient()意义】 用stop_gradient生成损失函数w.r.t.的梯度。 【tf.gradients()理解】 tf中我们只需要设计我们自己的函数,tf提供

tensorflow中tf.gradients()解析

tf.gradients()解析及grad_ys在xs为(?, 1)时的理解 问题简介 使用tensorflow1.15学习时,有一项tf.gradients的代码,其中用到了grad_ys这个参数,经过一些解析,得到了一些自己的理解 原代码 def fwd_gradients_1(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x1_tf)[0] return tf.gradients(g, self.d

sunshine9404的博客 2766

超详细Matlab R2021a免费安装教程(附安装包)

Matlab是一种高级技术计算语言和交互式环境,用于算法开发、数据可视化和数值计算。它集成了数学、工程和科学计算的丰富函数库,提供了强大的数据分析和绘图工具。Matlab还支持并行计算和大规模数据处理,适用于各种领域,如信号处理、图像处理、控制系统、机器学习等。

waicsdn_haha的博客 1万+

9 海康视觉平台VisionMaster 上手系列:典型案例之螺丝机案例

海康视觉平台VisionMaster 上手系列:典型案例之螺丝机案例 快速入门 工业机器视觉 机器视觉

HuangGong2022的博客 7192

tf.gradients()和tf.stop_gradient()

1、tf.gradients() tf.gradients( ys, xs, grad_ys=None, name='gradients', colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None, stop_gradient...

weixin_36670529的博客 8525

ESP32-S3开发环境避坑指南:VS Code+ESP-IDF离线安装全流程(附国内镜像加速)

本文提供了一份详细的ESP32-S3开发环境离线安装指南,重点解决网络依赖问题。通过整合国内镜像加速,手把手教你完成VS Code、ESP-IDF框架、工具链及Python依赖的本地化部署,实现稳定、可重复的开发环境搭建,大幅提升IoT开发效率。

peach的博客 968

【tensorflow】【python】tf.gradients

【代码】【tensorflow】【python】tf.gradients。

wq6qeg88的博客 645

Unity URP项目里Post Processing死活没效果?别急,这5个坑我帮你踩过了

本文详细解析了Unity URP项目中Post Processing效果不显示的5个常见问题及解决方案,包括管线配置、Volume设置、摄像机选项、Layer冲突和Shader兼容性。通过专业排查步骤和实用代码片段,帮助开发者快速定位并修复后处理效果失效问题,提升项目开发效率。

weixin_28693309的博客 239

在cadence中进行sdf文件的反标及并进行数模混仿

3.在Main-Include Option Settings-Libraries Files/Directories下面加载上面说到的两个.v文件(综合文件和工艺库器件文件),其他默认点击OK;最近在做一个数模混合电路的流片工作,数字部分综合后会生成一个.sdf(标准延时格式)文件,正常来说应该是要在vcs软件上进行电路延时的反标,但由于我的电路需要信号在数字模块和模拟模块中来回循环多次,因此,打算在cadence中完成sdf文件反标,进行数模混合仿真。1.综合生成的电路网表的.v文件;

WSBHX的博客 3301

TensorFlow专题

tf.placeholder函数说明

qq_32732581的博客 173

工业缺陷检测深度学习方法综述

异常:点异常、 上下文异常和集群异常。点异常:又称为离群值 (outliers)[9], 描述数值上偏离正 常样本的独立数据。与异常相近的概念还包括新颖点(novelty)和分布外数据。上下文异常:同样描述数据点,其数值属于正常范围,但不符合局部上下文规律。集群异常:描述一系列相关数据的集合,集合中的每一个实例的数值在单独考察时都处于正常值域,但集 合整体的相关性特征不服从正常模式。一般的图像异常检测往往仅需区分正常与异常样本,而工业缺陷检测更关注于检测 图像中的异常像素.

2301_80355452的博客 1850

30天吃掉那个TensorFlow2:优化器(tf.keras.optimizers)完全指南——从SGD到Adam的选型与实战

> 本文是《30天吃掉那个TensorFlow2》开源教程中阶API系列的第 7 篇,聚焦 TensorFlow2 中优化器的完整使用体系。文章从"优化算法决定模型性能上限"这一核心观点出发,系统讲解 `apply_gradients`、`minimize`、`model.fit` 三种迭代优化方式,逐一剖析 SGD/SGDM/NAG、Adagrad、RMSprop、Adadelta、Adam、N

gitblog_06856的博客 159

一篇关于轴承故障诊断的综述

在设备的故障检测中,有约30%-40%的设备故障是由轴承故障引起的,因此本文将列举有关检测轴承故障使用到的相关数据集,模型和算法。 数据集 现有的数据集,普遍由固定在电机马达上的两个震动检测器获得,并根据需要,分离震动数据在时域和频域上的特征以供网络模型学习。 不同的数据集,区别在于,检测的马达转速不同,环境不同,取样频率不同,一段样本的时长不同等等 (1)Case Western Reserve University (CWRU) Dataset 该数据集拥有多种数据,测量的时候,通过改变轴承.

weixin_42036144的博客 2万+

用 SAP Fiori Launchpad Content Manager 做目录传输:把 Catalog 变更稳稳送到目标系统

摘要:SAP Fiori项目中,目录传输是确保应用一致交付的关键环节。开发团队常遇到目录在不同系统/客户端间不一致的问题,核心在于理解Launchpad内容管理的两种作用域:系统级(/UI2/FLPCM_CONF)使用workbench请求跨系统传输,客户端级(/UI2/FLPCM_CUST)通过customizing请求按SCC4设置传输。混淆作用域会导致目录分叉,如系统级目录被客户端本地修改后形成独立副本。官方推荐使用Content Manager而非过时的Launchpad Designer,并强调手

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 114

TF1用户必看:saliency框架TensorFlow 1.x适配与实战教程

saliency框架是一个与框架无关的实现,支持多种最先进的显著性方法(如XRAI、BlurIG、SmoothGrad等)。本教程专为TensorFlow 1.x用户打造,将详细介绍如何在TF1环境中适配和使用saliency框架进行显著性分析。 ## 一、saliency框架TF1适配模块概览 📦 saliency框架为TensorFlow 1.x提供了完整的适配支持,相关实现集中在 [s

gitblog_00368的博客 523

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Tensorflow中k.gradients()和tf.stop_gradient()的深入理解

上周在实验室开荒某个代码,看到中间这么一段,对Tensorflow中的stop_gradient()还不熟悉,特此周末进行重新并总结。 y = xx + K.stop_gradient(rounded - xx) 这代码最终调用位置在tensoflow.python.ops.gen_array_ops.stop_gradient(input, name=None),关于这段代码...

码农的科研笔记 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

tf.gradients、tf.compute_gradients和tf.stop_gradient

import tensorflow as tf w = tf.Variable([2., 5.]) # u = tf.Variable([7., 9.]) y = 2 * w x = 2 * y z = 2 * x stop_y = tf.stop_gradient(y) stop_x = 2 * stop_y grad1 = tf.gradients(y, w) grad2 = tf.grad...

Seventeen0084的博客 1520

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

TensorFlow梯度求解tf.gradients

import tensorflow as tf w1 = tf.Variable([[1,2]]) w2 = tf.Variable([[3,4]]) res = tf.matmul(w1, [[2],[1]]) grads = tf.gradients(res,[w1]) with tf.Session() as sess: tf.global_variables_init

yqtao的博客 1万+

TensorFlow tf.gradients的用法详细解析以及具体例子

tf.gradients 官方定义: tf.gradients( ys, xs, grad_ys=None, name='gradients', stop_gradients=None, ) Constructs symbolic derivatives of sum ofysw.r.t. x inxs. ysand...

weixin_30540691的博客 901

tensorflow: tf.variable_scope,tf.summary,tf.gradients

目录1 变量共享1.1 命名空间: tf.name_scope()1.2 变量空间: tf.variable_scope() 1 变量共享 1.1 命名空间: tf.name_scope() tensorflow不知道什么nodes应该聚集在一起,除非在定义功能的时候,通过tf.name_scope(name)来显式的告诉tensorflow。 with tf.name_scope('data'): ... with tf.name_scope('loss'): ... with tf.name_s

BGoodHabit的博客 482

tensorflow的tf.gradients和tf.stop_gradients

1.tf.gradients的功能介绍 首先看下tf.gradients的功能,字面意思就很容易看出,tf.gradients用来对变量求梯度,我们给出一个简单的例子: import tensorflow as tf sess = tf.Session() a = tf.Variable(0.,name="a") b = tf.Variable(0.,name="b") c=5*a+b print(sess.run(tf.gradients(c, [a, b]))) print(sess.run(tf

fangfanglovezhou的博客 625

tf.gradients

tf.gradients tf.gradients( ys, xs, grad_ys=None, name=’gradients’, colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None...

ustc_imcl_fj的博客 1278

TensorFlow—计算梯度与控制梯度 : tf.gradients和compute_gradients和apply_gradients和clip_by_global_norm控制梯度

TensorFlow的梯度 我们知道训练神经网络有一个很重要的就是反向传播更新参数,如果没有经历过2015-2017年的神经网络的研究生,这一步听陌生的,但是不重要,我们知道TensorFlow给我们API怎么用就行了。 对于反向传播这一步,我们常见的代码是如下: # 损失计算,也就是优化对象 loss = tf.nn.............. # 反向传播 # 定义优化器,学习率定义1.0 ...

xinjieyuan的博客 6828

tensorflow的computer_gradients()和tf.gradients()函数

函数原型: computer_gradients(loss,val_list) loss:损失函数,也即需要被优化的tensor val_list:需要求梯度的变量列表 简单示例: w = tf.Variable(initial_value=10., dtype='float32') y = w*w + 2 opt = tf.train.GradientDescentOptimizer(0....

m0_38027013的博客 1485
上一篇: jemalloc 深入分析 之Jemalloc 内存 分配 释放 过程
下一篇: Tensorflow 交叉熵(Cross Entropy)详解
EversChen5
博客等级 码龄17年 5粉丝 16原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值