簡體   English   中英

Pytorch 具有平方特征的線性回歸

[英]Pytorch Linear Regression with squared features

我是 PyTorch 的新手,我想部分用 PyTorch 實現線性回歸,部分用我自己。 我想使用平方特征進行回歸:

import torch

# init
x = torch.tensor([1,2,3,4,5])
y = torch.tensor([[1],[4],[9],[16],[25]])
w = torch.tensor([[0.5], [0.5], [0.5]], requires_grad=True)

iterations = 30
alpha = 0.01

def forward(X):
    # feature transformation [1, x, x^2]
    psi = torch.tensor([[1.0, x[0], x[0]**2]])
    for i in range(1, len(X)):
        psi = torch.cat((psi, torch.tensor([[1.0, x[i], x[i]**2]])), 0)
    return torch.matmul(psi, w)
    
def loss(y, y_hat):
    return ((y-y_hat)**2).mean()

for i in range(iterations):
    
    y_hat = forward(x)

    l = loss(y, y_hat)
    l.backward()
    
    with torch.no_grad():
        w -= alpha * w.grad 
    w.grad.zero_()

    if i%10 == 0:
        print(f'Iteration {i}: The weight is:\n{w.detach().numpy()}\nThe loss is:{l}\n')

當我執行我的代碼時,回歸並沒有學習到正確的特征,並且損失會永久增加。 output如下:

Iteration 0: The weight is:
[[0.57 ]
 [0.81 ]
 [1.898]]
The loss is:25.450000762939453

Iteration 10: The weight is:
[[ 5529.5835]
 [22452.398 ]
 [97326.12  ]]
The loss is:210414632960.0

Iteration 20: The weight is:
[[5.0884394e+08]
 [2.0662339e+09]
 [8.9567642e+09]]
The loss is:1.7820802835250162e+21

有人知道,為什么我的 model 不學習?

更新

它的表現如此糟糕是有原因的嗎? 我認為這是因為訓練數據數量少。 但也有 10 個數據點,它表現不佳: 在此處輸入圖像描述

您應該標准化您的數據。 此外,由於您試圖擬合x -> ax² + bx + cc本質上是偏差。 從訓練數據中刪除它應該更明智(我在這里指的是psi )並為偏差使用單獨的參數。

可以做什么:

  • 用均值和標准差標准化您的輸入數據和目標。

  • 將參數分成w (一個雙分量權重張量)和b (偏差)。

  • 由於x是相同的,因此您不需要在每個推理上都構造psi

  • 您可以使用torch.stack([torch.ones_like(x), x, x**2], 1)構建psi ,但在這里我們不需要這些,因為我們基本上已經從權重張量中分離了偏差.

這是它的樣子:

x = torch.tensor([1,2,3,4,5]).float()
psi = torch.stack([x, x**2], 1).float()
psi = (psi - psi.mean(0)) / psi.std(0)

y = torch.tensor([[1],[4],[9],[16],[25]]).float()
y = (y - y.mean(0)) / y.std(0)

w = torch.tensor([[0.5], [0.5]], requires_grad=True)
b = torch.tensor([0.5], requires_grad=True)

iterations = 30
alpha = 0.02
def loss(y, y_hat):
    return ((y-y_hat)**2).mean()

for i in range(iterations):
    y_hat = torch.matmul(psi, w) + b
    l = loss(y, y_hat)
    l.backward()
    
    with torch.no_grad():
        w -= alpha * w.grad 
        b -= alpha * b.grad 
    w.grad.zero_()
    b.grad.zero_()

    if i%10 == 0:
        print(f'Iteration {i}: The weight is:\n{w.detach().numpy()}\nThe loss is:{l}\n')

結果:

Iteration 0: The weight is:
[[0.49954653]
 [0.5004535 ]]
The loss is:0.25755801796913147

Iteration 10: The weight is:
[[0.49503425]
 [0.5049657 ]]
The loss is:0.07994867861270905

Iteration 20: The weight is:
[[0.49056274]
 [0.50943726]]
The loss is:0.028329044580459595

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM