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

pytorch 模擬關(guān)系擬合——回歸實(shí)例

 更新時(shí)間:2020年01月14日 14:56:30   作者:HF飛哥  
今天小編就為大家分享一篇pytorch 模擬關(guān)系擬合——回歸實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

本次用 pytroch 來實(shí)現(xiàn)一個(gè)簡(jiǎn)單的回歸分析,也借此機(jī)會(huì)來熟悉 pytorch 的一些基本操作。

1. 建立數(shù)據(jù)集

import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt

# torch.linspace(-1,1,100)表示返回一個(gè)一維張量,包含在區(qū)間 -1到1 上均勻間隔的100個(gè)點(diǎn);
# torch.unsqueeze(input,dim=1)表示轉(zhuǎn)換維度
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
# 生成的y值為x的平方加上隨機(jī)數(shù) 
y = x.pow(2) + 0.2*torch.rand(x.size())         

# 用 Variable 來修飾這些數(shù)據(jù) tensor
x, y = torch.autograd.Variable(x), Variable(y)

# 畫圖
plt.scatter(x.data.numpy(), y.data.numpy())
plt.show()

2. 構(gòu)建神經(jīng)網(wǎng)絡(luò)

import torch
import torch.nn.functional as F   # 激勵(lì)函數(shù)都在這

class Net(torch.nn.Module): # 繼承 torch 的 Module
  def __init__(self, n_feature, n_hidden, n_output):
    super(Net, self).__init__()   # 繼承 __init__ 功能
    # 定義每層用什么樣的形式
    self.hidden = torch.nn.Linear(n_feature, n_hidden)  # 隱藏層線性輸出
    self.predict = torch.nn.Linear(n_hidden, n_output)  # 輸出層線性輸出

  def forward(self, x):  # 這同時(shí)也是 Module 中的 forward 功能
    # 正向傳播輸入值, 神經(jīng)網(wǎng)絡(luò)分析出輸出值
    x = F.relu(self.hidden(x))   # 激勵(lì)函數(shù)(隱藏層的線性值)
    x = self.predict(x)       # 輸出值
    return x

net = Net(n_feature=1, n_hidden=10, n_output=1)

print(net) # net 的結(jié)構(gòu)
"""
Net (
 (hidden): Linear (1 -> 10)
 (predict): Linear (10 -> 1)
)
"""

3. 實(shí)時(shí)繪圖查看回歸效果

import matplotlib.pyplot as plt

plt.ion() #打開交互繪圖模式(便于實(shí)時(shí)顯示圖像變化)
plt.show() 

optimizer = torch.optim.SGD(net.parameters(), lr=0.1) # 定義優(yōu)化器和學(xué)習(xí)率
loss_func = torch.nn.MSELoss() #定義損失函數(shù)

for t in range(200):
  prediction = net(x)
  loss = loss_func(prediction, y)

  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

  if t%5 == 0:
    plt.cla() 
    plt.scatter(x.data.numpy(), y.data.numpy()) # 畫散點(diǎn)圖
    plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5) # 畫擬合曲線
    plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size':20,'color':'red'}) # 顯示損失數(shù)值
    plt.pause(0.1)

# 如果在腳本中使用ion()命令開啟了交互模式,沒有使用ioff()關(guān)閉的話,則圖像會(huì)一閃而過,并不會(huì)常留。要想防止這種情況,需要在plt.show()之前加上ioff()命令。
plt.ioff() 
plt.show()

運(yùn)行終態(tài)效果圖如下:

以上這篇pytorch 模擬關(guān)系擬合——回歸實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論