亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

pytorch實現(xiàn)線性擬合方式

 更新時間:2020年01月15日 09:34:23   作者:wangqianqianya  
今天小編就為大家分享一篇pytorch實現(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實現(xiàn)線性擬合方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python使用PyNmap進行網(wǎng)絡(luò)掃描的詳細步驟

    Python使用PyNmap進行網(wǎng)絡(luò)掃描的詳細步驟

    使用 PyNmap 進行網(wǎng)絡(luò)掃描是一個非常有效的方式,PyNmap 是 Nmap 工具的一個 Python 封裝,它允許你在 Python 腳本中使用 Nmap 的強大功能,本文介紹了如何使用 PyNmap 進行網(wǎng)絡(luò)掃描的詳細步驟,需要的朋友可以參考下
    2024-08-08
  • django 模版關(guān)閉轉(zhuǎn)義方式

    django 模版關(guān)閉轉(zhuǎn)義方式

    這篇文章主要介紹了django 模版關(guān)閉轉(zhuǎn)義方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • python列表推導(dǎo)式操作解析

    python列表推導(dǎo)式操作解析

    這篇文章主要介紹了python列表推導(dǎo)式操作解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下
    2019-11-11
  • 詳解Python編程中基本的數(shù)學(xué)計算使用

    詳解Python編程中基本的數(shù)學(xué)計算使用

    這篇文章主要介紹了Python編程中基本的數(shù)學(xué)計算使用,其中重點講了除法運算及相關(guān)division模塊的使用,需要的朋友可以參考下
    2016-02-02
  • 舉例講解Linux系統(tǒng)下Python調(diào)用系統(tǒng)Shell的方法

    舉例講解Linux系統(tǒng)下Python調(diào)用系統(tǒng)Shell的方法

    這篇文章主要介紹了舉例講解Linux系統(tǒng)下Python調(diào)用系統(tǒng)Shell的方法,包括用Python和shell讀取文件某一行的實例,需要的朋友可以參考下
    2015-11-11
  • python程序的組織結(jié)構(gòu)詳解

    python程序的組織結(jié)構(gòu)詳解

    這篇文章主要為大家介紹了python程序的組織結(jié)構(gòu),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-12-12
  • Python制作腳本幫女朋友搶購清空購物車

    Python制作腳本幫女朋友搶購清空購物車

    這篇文章主要介紹了Python制作的搶購清空購物車的腳本,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-08-08
  • Python數(shù)據(jù)預(yù)處理常用的5個技巧

    Python數(shù)據(jù)預(yù)處理常用的5個技巧

    大家好,本篇文章主要講的是Python數(shù)據(jù)預(yù)處理常用的5個技巧,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-02-02
  • python基于右遞歸解決八皇后問題的方法

    python基于右遞歸解決八皇后問題的方法

    這篇文章主要介紹了python基于右遞歸解決八皇后問題的方法,實例分析了右遞歸算法的相關(guān)使用技巧,需要的朋友可以參考下
    2015-05-05
  • 詳解基于python的多張不同寬高圖片拼接成大圖

    詳解基于python的多張不同寬高圖片拼接成大圖

    這篇文章主要介紹了詳解基于python的多張不同寬高圖片拼接成大圖,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧
    2019-09-09

最新評論