我试图计算TensorFlow神经网络的输出相对于它的输入的雅可比。这很容易用tf.GradientTape.jacobian方法实现。TensorFlow文档中提供的简单示例如下:
with tf.GradientTape() as g:
x = tf.constant([1.0, 2.0])
g.watch(x)
y = x * x
jacobian = g.jacobian(y, x)
如果我只想计算输入张量x的单个实例的Jacobian,这是很好的。但是,对于x的各种实例,我需要多次、多次地对这个Jacobian进行评估。对于一个非平凡的雅可比计算(例如,对于具有非线性激
我有两个变量,x和theta。我只想尽量减少对theta的损失,但作为损失函数的一部分,我需要一个关于x的不同函数(f)的导数。这个导数本身与最小化无关,只是它的输出。但是,在PyTorch中实现此操作时,我会得到一个运行时错误。
最起码的例子如下:
# minimal example of two different autograds
import torch
from torch.autograd.functional import jacobian
def f(theta, x):
return torch.sum(theta * x ** 2)
def df(theta,
根据docs,如果张量是非标量的(即它的数据有多个元素),并且需要梯度,则当我们将后向函数调用到张量时,该函数还需要指定梯度。
import torch
a = torch.tensor([10.,10.],requires_grad=True)
b = torch.tensor([20.,20.],requires_grad=True)
F = a * b
F.backward(gradient=torch.tensor([1.,1.]))
print(a.grad)
Output: tensor([20., 20.])
现在,缩放外部梯度:
a = torch.tensor([10.
如何在PyTorch中区分矩阵?我尝试过以下几种方法,但都不起作用:
实例1:
a = torch.tensor([1., 2, 3], requires_grad=True)
b = torch.tensor([4., 5, 6], requires_grad=True)
c = a*b
c.backward()
#print(b.grad)
>>> RuntimeError: grad can be implicitly created only for scalar outputs
实例2:
a = torch.tensor([1., 2, 3], requires
我正在尝试使用lsqcurvefit将Arrhenius形式的方程拟合到一些数据点。
D = D0 * exp( -Ea / ( R * T )); % Arrhenius equation for curve fitting
D0和Ea是我要寻找的值。T是温度,代表X,D是系数,代表Y,R是气体常数。由于matlab在没有提供雅可比矩阵的情况下找不到解决方案,我计算了雅可比矩阵并包含了一个函数,正如我在早期的帖子中@m7913d所演示的那样([Matlab曲线拟合不适用于较小的值(1e-12),what can I do?](https://stackoverflow.com/q
如问题所示,我想计算矩阵行的梯度。代码:
import numpy.random as rng
import theano.tensor as T
from theano import function
t_x = T.matrix('X')
t_w = T.matrix('W')
t_y = T.dot(t_x, t_w.T)
t_g = T.grad(t_y[0,0], t_x[0]) # my wish, but DisconnectedInputError
t_g = T.grad(t_y[0,0], t_x) # no problem
我正在用Python编写一个向后的Euler方法,我在编写牛顿部分时遇到了问题。我们被赋予了1e-4的公差,使用这个公差,我在牛顿方法的输出向量中得到了非常小的数字。
这是我的代码:
def Newt(U,x,tol): #takes in matrix, x vector, tolerance
error=np.matrix([[1],[1]]) #set an error matrix of 1,1
while abs(LA.norm(error))>tol:
func=function(U,x) #define a f(x) vector
在我以前的中,我发现了如何使用PyTorch的自动梯度和张量:
import torch
from torch.autograd import grad
import torch.nn as nn
import torch.optim as optim
class net_x(nn.Module):
def __init__(self):
super(net_x, self).__init__()
self.fc1=nn.Linear(1, 20)
self.fc2=nn.Linear(20, 20)
要在Pytorch中执行backward,我们可以使用一个可选参数y.backward(v)来计算乘以v的雅可比矩阵 x = torch.randn(3, requires_grad=True)
y = x * 2
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(v)
print(x.grad) 我认为计算雅可比矩阵的成本是相同的,因为计算雅可比矩阵所必需的AD图中的每个节点仍然是计算的。那么为什么Pytorch不想给我们雅可比矩阵呢?