【发布时间】:2019-08-22 00:15:08
【问题描述】:
我正在尝试将旧代码转换为 PyTorch 代码作为实验。最终,我将对 10,000+ x 100 矩阵进行回归,适当地更新权重等等。
尝试学习,我正在慢慢扩大玩具示例。我正在使用以下示例代码碰壁。
import torch
import torch.nn as nn
import torch.nn.functional as funct
from torch.autograd import Variable
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
x_data = Variable( torch.Tensor( [ [1.0, 2.0], [2.0, 3.0], [3.0, 4.0] ] ),
requires_grad=True )
y_data = Variable( torch.Tensor( [ [2.0], [4.0], [6.0] ] ) )
w = Variable( torch.randn( 2, 1, requires_grad=True ) )
b = Variable( torch.randn( 1, 1, requires_grad=True ) )
class Model(torch.nn.Module) :
def __init__(self) :
super( Model, self).__init__()
self.linear = torch.nn.Linear(2,1) ## 2 features per entry. 1 output
def forward(self, x2, w2, b2) :
y_pred = x2 @ w2 + b2
return y_pred
model = Model()
criterion = torch.nn.MSELoss( size_average=False )
optimizer = torch.optim.SGD( model.parameters(), lr=0.01 )
for epoch in range(10) :
y_pred = model( x_data,w,b ) # Get prediction
loss = criterion( y_pred, y_data ) # Calc loss
print( epoch, loss.data.item() ) # Print loss
optimizer.zero_grad() # Zero gradient
loss.backward() # Calculate gradients
optimizer.step() # Update w, b
但是,这样做,我的损失总是一样的,调查显示我的 w 和 b 从未真正改变。我对这里发生的事情有点迷茫。
最终,我希望能够存储“新” w 和 b 的结果,以便在迭代和数据集之间进行比较。
【问题讨论】:
标签: regression linear-regression pytorch prediction