Reputation: 1
I am kind of a newbie with PyTorch. Please forgive me if the question is childish. I am trying to minimize a function using PyTorch's optim. The function includes matrix multiplication. The details are given below.
First I have a tensor:
Xv.requires_grad_()
XT.requires_grad_()
My Objective Function:
def errorFun(x):
ax = x[0]
ay = x[1]
x0 = x[2]
y0 = x[3]
A = torch.tensor([[ax, 0., x0], [0., ay, y0], [0., 0., 1.]], dtype=torch.float64)
B = torch.tensor([[b11, b12, b13], [b21, b22, b23], [b31, b32, b33]], dtype=torch.float64)
H = torch.mm(A, B)
Ps = torch.mm(H, X)
px = Ps[0,:]
py = Ps[1,:]
PX = torch.stack([px, py], dim=0)
PX.requires_grad_()
return mseloss(PX, XT)
I am minimizing it:
for ii in range(n_optim_steps):
optimizer.zero_grad()
loss = errorFun(params)
#print('Step # {}, loss: {}'.format(ii, loss.item()))
loss.backward()
# Access gradient if necessary
grad = params.grad.data
optimizer.step()
But I am getting this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-54-84b874448a25> in <module>()
77 loss.backward()
78 # Access gradient if necessary
---> 79 grad = params.grad.data
80 optimizer.step()
81
AttributeError: 'NoneType' object has no attribute 'data'
Thanks in advance.
Upvotes: 0
Views: 708
Reputation: 1974
I am not sure I understand your task. But it seems you are not using pytorch the way it was designed to be used.
There are 5 things you have to have:
Consider the simple example:
The implementation:
import torch
import torch.nn as nn
from torch.optim import SGD
input_size = 5
model = nn.Linear(input_size, 1)
opt = SGD(model.parameters(), lr=0.01)
loss_func = nn.MSELoss()
for _ range(100):
data = torch.rand(batch_size, input_size)
target = data.sum(dim=1)
opt.zero_grad()
pred = model(data)
loss = loss_func(pred, target)
loss.backward()
opt.step()
Upvotes: 1