PyTorch學習:一個非常簡單的線性迴歸的小例子

import torch
import numpy as np
from torch.autograd import Variable
import matplotlib.pyplot as plt
torch.manual_seed(2018)
# 讀入數據 x 和 y
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
                    [9.779], [6.182], [7.59], [2.167], [7.042],
                    [10.791], [5.313], [7.997], [3.1]], dtype=np.float32)

y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
                    [3.366], [2.596], [2.53], [1.221], [2.827],
                    [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
plt.plot(x_train, y_train, 'bo')
plt.show()
plt.close()
# 轉換成 Tensor
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)
# 定義參數 w 和 b
w = Variable(torch.randn(1), requires_grad=True) # 隨機初始化
b = Variable(torch.zeros(1), requires_grad=True) # 使用 0 進行初始化
# 構建線性迴歸模型
x_train = Variable(x_train)
y_train = Variable(y_train)

def linear_model(x):
    return x * w + b
# 計算誤差
def get_loss(y_, y):
    return torch.mean((y_ - y_train) ** 2)

for e in range(10): # 進行 10 次更新
    y_ = linear_model(x_train)
    loss = get_loss(y_, y_train)
    if e!=0:   #第一次不用歸零梯度
        w.grad.zero_() # 記得歸零梯度
        b.grad.zero_() # 記得歸零梯度
    loss.backward()
    
    w.data = w.data - 1e-2 * w.grad.data # 更新 w
    b.data = b.data - 1e-2 * b.grad.data # 更新 b 
    print('epoch: {}, loss: {}'.format(e, loss.item() ))#0.4.0之前用 loss.data[0]
    
y_ = linear_model(x_train)
plt.plot(x_train.data.numpy(), y_train.data.numpy(), 'bo', label='real')
plt.plot(x_train.data.numpy(), y_.data.numpy(), 'ro', label='estimated')
plt.legend()
plt.show()
plt.close()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章