pytorch實(shí)現(xiàn)線性擬合方式
更新時間:2020年01月15日 09:34:23 作者:wangqianqianya
今天小編就為大家分享一篇pytorch實(shí)現(xiàn)線性擬合方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
一維線性擬合
數(shù)據(jù)為y=4x+5加上噪音
結(jié)果:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
from torch.autograd import Variable
import torch
from torch import nn
X = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
Y = 4*X + 5 + torch.rand(X.size())
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(1, 1) # 輸入和輸出的維度都是1
def forward(self, X):
out = self.linear(X)
return out
model = LinearRegression()
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-2)
num_epochs = 1000
for epoch in range(num_epochs):
inputs = Variable(X)
target = Variable(Y)
# 向前傳播
out = model(inputs)
loss = criterion(out, target)
# 向后傳播
optimizer.zero_grad() # 注意每次迭代都需要清零
loss.backward()
optimizer.step()
if (epoch + 1) % 20 == 0:
print('Epoch[{}/{}], loss:{:.6f}'.format(epoch + 1, num_epochs, loss.item()))
model.eval()
predict = model(Variable(X))
predict = predict.data.numpy()
plt.plot(X.numpy(), Y.numpy(), 'ro', label='Original Data')
plt.plot(X.numpy(), predict, label='Fitting Line')
plt.show()
多維:
from itertools import count
import torch
import torch.autograd
import torch.nn.functional as F
POLY_DEGREE = 3
def make_features(x):
"""Builds features i.e. a matrix with columns [x, x^2, x^3]."""
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, POLY_DEGREE+1)], 1)
W_target = torch.randn(POLY_DEGREE, 1)
b_target = torch.randn(1)
def f(x):
return x.mm(W_target) + b_target.item()
def get_batch(batch_size=32):
random = torch.randn(batch_size)
x = make_features(random)
y = f(x)
return x, y
# Define model
fc = torch.nn.Linear(W_target.size(0), 1)
batch_x, batch_y = get_batch()
print(batch_x,batch_y)
for batch_idx in count(1):
# Get data
# Reset gradients
fc.zero_grad()
# Forward pass
output = F.smooth_l1_loss(fc(batch_x), batch_y)
loss = output.item()
# Backward pass
output.backward()
# Apply gradients
for param in fc.parameters():
param.data.add_(-0.1 * param.grad.data)
# Stop criterion
if loss < 1e-3:
break
def poly_desc(W, b):
"""Creates a string description of a polynomial."""
result = 'y = '
for i, w in enumerate(W):
result += '{:+.2f} x^{} '.format(w, len(W) - i)
result += '{:+.2f}'.format(b[0])
return result
print('Loss: {:.6f} after {} batches'.format(loss, batch_idx))
print('==> Learned function:\t' + poly_desc(fc.weight.view(-1), fc.bias))
print('==> Actual function:\t' + poly_desc(W_target.view(-1), b_target))
以上這篇pytorch實(shí)現(xiàn)線性擬合方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python使用PyNmap進(jìn)行網(wǎng)絡(luò)掃描的詳細(xì)步驟
使用 PyNmap 進(jìn)行網(wǎng)絡(luò)掃描是一個非常有效的方式,PyNmap 是 Nmap 工具的一個 Python 封裝,它允許你在 Python 腳本中使用 Nmap 的強(qiáng)大功能,本文介紹了如何使用 PyNmap 進(jìn)行網(wǎng)絡(luò)掃描的詳細(xì)步驟,需要的朋友可以參考下2024-08-08
詳解Python編程中基本的數(shù)學(xué)計(jì)算使用
這篇文章主要介紹了Python編程中基本的數(shù)學(xué)計(jì)算使用,其中重點(diǎn)講了除法運(yùn)算及相關(guān)division模塊的使用,需要的朋友可以參考下2016-02-02
舉例講解Linux系統(tǒng)下Python調(diào)用系統(tǒng)Shell的方法
這篇文章主要介紹了舉例講解Linux系統(tǒng)下Python調(diào)用系統(tǒng)Shell的方法,包括用Python和shell讀取文件某一行的實(shí)例,需要的朋友可以參考下2015-11-11
Python數(shù)據(jù)預(yù)處理常用的5個技巧
大家好,本篇文章主要講的是Python數(shù)據(jù)預(yù)處理常用的5個技巧,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02

