简体   繁体   English

使用 Pytorch 的线性回归:恒定损失

[英]Linear Regression with Pytorch : constant loss

I'm working on a linear regression problem with Pytorch (y=A*x, where the dimensions of A are 2x2).我正在研究 Pytorch 的线性回归问题(y=A*x,其中 A 的尺寸为 2x2)。 I wrote the following code.我写了以下代码。 I don't know why the loss doesn't change... Can someone help me?我不知道为什么损失没有改变......有人可以帮助我吗?

Thanks,谢谢,

Thomas托马斯

import torch
import numpy as np
from scipy.integrate import odeint
from matplotlib import pyplot as plt
from torch.autograd import Variable
def EDP(X,t):
    X_0=-2*X[0]
    X_1=-2*X[1]
    grad=np.array([X_0,X_1])
    return grad
T=np.arange(0,10,0.1)
X_train=odeint(EDP,[10,20],T)

Y_train=np.zeros_like(X_train)
for i in range(Y_train.shape[0]):
    Y_train[i,:]=np.dot(np.array([[2,0],[0,2]]),X_train[i,:])
print(X_train,Y_train)

X_train=torch.Tensor(X_train)
torch.transpose(X_train,0,1)
Y_train=torch.Tensor(Y_train)
print(X_train.shape)
import torch.nn as nn
class LinearRegression(torch.nn.Module): 
    
    def __init__(self):
        super(LinearRegression, self).__init__() 
        self.linear = torch.nn.Linear(2,2,bias = False) # bias is default True

    def forward(self, x):
        y_pred = self.linear(x)
        return y_pred
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.0001) 
our_model = LinearRegression()
x_train = X_train
y_train = Y_train
#x_train.requires_grad=True
print(x_train.shape)
print(y_train.shape)
ntrain=10

for t in range(ntrain):
    
    y_pred=our_model(x_train)
    loss=criterion(y_train,y_pred)
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
    print(t,loss)
print(our_model.linear.weight)

In my laptop it worked...在我的笔记本电脑上它工作...
since you are running it on just 10 epochs ...and using lr = 0.0001 ,you wont see it in just 10 epochs .因为您只在10 epochs上运行它......并且使用lr = 0.0001 ,所以您不会在10 epochs内看到它。

i did this optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01) (increased lr )which actually decreased the loss in just 10 epochs我做了这个optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01) (增加lr )实际上仅在 10 个时期内就减少了损失

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM