最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2020年01月15日 09:34:23   作者:wangqianqianya  
今天小編就為大家分享一篇pytorch實(shí)現(xiàn)線性擬合方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

一維線性擬合

數(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)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 淺談python numpy中nonzero()的用法

    淺談python numpy中nonzero()的用法

    下面小編就為大家分享一篇淺談python numpy中nonzero()的用法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • Python爬蟲獲取基金基本信息

    Python爬蟲獲取基金基本信息

    這篇文章主要介紹了Python爬蟲獲取基金基本信息,文章基于上一篇文章內(nèi)容基于python的相關(guān)資料展開主題,需要的小伙伴可以參考一下
    2022-05-05
  • python中將函數(shù)賦值給變量時(shí)需要注意的一些問題

    python中將函數(shù)賦值給變量時(shí)需要注意的一些問題

    變量賦值是我們在日常開發(fā)中經(jīng)常會遇到的一個(gè)問題,下面這篇文章主要給大家介紹了關(guān)于python中將函數(shù)賦值給變量時(shí)需要注意的一些問題,文中通過示例代碼介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。
    2017-08-08
  • 使用BeeWare實(shí)現(xiàn)iOS調(diào)用Python方式

    使用BeeWare實(shí)現(xiàn)iOS調(diào)用Python方式

    這篇文章主要介紹了使用BeeWare實(shí)現(xiàn)iOS調(diào)用Python方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Python實(shí)現(xiàn)將n個(gè)點(diǎn)均勻地分布在球面上的方法

    Python實(shí)現(xiàn)將n個(gè)點(diǎn)均勻地分布在球面上的方法

    這篇文章主要介紹了Python實(shí)現(xiàn)將n個(gè)點(diǎn)均勻地分布在球面上的方法,涉及Python繪圖的技巧與相關(guān)數(shù)學(xué)函數(shù)的調(diào)用,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-03-03
  • Tensorflow2.4使用Tuner選擇模型最佳超參詳解

    Tensorflow2.4使用Tuner選擇模型最佳超參詳解

    這篇文章主要介紹了Tensorflow2.4使用Tuner選擇模型最佳超參詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • 詳解Python如何查看一個(gè)函數(shù)的參數(shù)

    詳解Python如何查看一個(gè)函數(shù)的參數(shù)

    inspect模塊提供了許多用于檢查對象的工具函數(shù),其中包括用于獲取函數(shù)參數(shù)信息的函數(shù),所以在Python中,大家可以使用inspect模塊來查看一個(gè)函數(shù)的參數(shù)信息,本文就來和大家講講具體操作吧
    2023-05-05
  • wxpython布局的實(shí)現(xiàn)方法

    wxpython布局的實(shí)現(xiàn)方法

    這篇文章主要介紹了wxpython布局的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Python線性擬合實(shí)現(xiàn)函數(shù)與用法示例

    Python線性擬合實(shí)現(xiàn)函數(shù)與用法示例

    這篇文章主要介紹了Python線性擬合實(shí)現(xiàn)函數(shù)與用法,結(jié)合實(shí)例形式分析了Python使用線性擬合算法與不使用線性擬合算法的相關(guān)算法操作技巧,需要的朋友可以參考下
    2018-12-12
  • python網(wǎng)絡(luò)編程之UDP通信實(shí)例(含服務(wù)器端、客戶端、UDP廣播例子)

    python網(wǎng)絡(luò)編程之UDP通信實(shí)例(含服務(wù)器端、客戶端、UDP廣播例子)

    UDP,用戶數(shù)據(jù)報(bào)傳輸協(xié)議,它位于TCP/IP協(xié)議的傳輸層,是一種無連接的協(xié)議,它發(fā)送的報(bào)文不能確定是否完整地到達(dá)了另外一端
    2014-04-04

最新評論

竹溪县| 长丰县| 阿拉善盟| 蒙自县| 北辰区| 黄骅市| 泽普县| 永宁县| 精河县| 万盛区| 武强县| 隆子县| 榆中县| 阳信县| 博罗县| 长子县| 新兴县| 珲春市| 阿瓦提县| 伊金霍洛旗| 怀远县| 华宁县| 溧水县| 乡城县| 射阳县| 贵定县| 肃宁县| 滨州市| 赫章县| 竹山县| 清水县| 靖宇县| 襄樊市| 红原县| 富平县| 临城县| 定远县| 会理县| 会东县| 太白县| 甘德县|