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

pytorch實現(xiàn)線性回歸以及多元回歸

 更新時間:2021年04月09日 17:36:21   作者:Lee_lv  
這篇文章主要為大家詳細(xì)介紹了pytorch實現(xiàn)線性回歸以及多元回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了pytorch實現(xiàn)線性回歸以及多元回歸的具體代碼,供大家參考,具體內(nèi)容如下

最近在學(xué)習(xí)pytorch,現(xiàn)在把學(xué)習(xí)的代碼放在這里,下面是github鏈接

直接附上github代碼

# 實現(xiàn)一個線性回歸
# 所有的層結(jié)構(gòu)和損失函數(shù)都來自于 torch.nn
# torch.optim 是一個實現(xiàn)各種優(yōu)化算法的包,調(diào)用的時候必須是需要優(yōu)化的參數(shù)傳入,這些參數(shù)都必須是Variable
 
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)
 
# 首先我們需要將array轉(zhuǎn)化成tensor,因為pytorch處理的單元是Tensor
 
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)
 
 
# def a simple network
 
class LinearRegression(nn.Module):
    def __init__(self):
        super(LinearRegression,self).__init__()
        self.linear = nn.Linear(1, 1)  # input and output is 2_dimension
    def forward(self, x):
        out = self.linear(x)
        return out
 
 
if torch.cuda.is_available():
    model = LinearRegression().cuda()
    #model = model.cuda()
else:
    model = LinearRegression()
    #model = model.cuda()
 
# 定義loss function 和 optimize func
criterion = nn.MSELoss()   # 均方誤差作為優(yōu)化函數(shù)
optimizer = torch.optim.SGD(model.parameters(),lr=1e-3)
num_epochs = 30000
for epoch in range(num_epochs):
    if torch.cuda.is_available():
        inputs = Variable(x_train).cuda()
        outputs = Variable(y_train).cuda()
    else:
        inputs = Variable(x_train)
        outputs = Variable(y_train)
 
    # forward
    out = model(inputs)
    loss = criterion(out,outputs)
 
    # backword
    optimizer.zero_grad()  # 每次做反向傳播之前都要進(jìn)行歸零梯度。不然梯度會累加在一起,造成不收斂的結(jié)果
    loss.backward()
    optimizer.step()
 
    if (epoch +1)%20==0:
        print('Epoch[{}/{}], loss: {:.6f}'.format(epoch+1,num_epochs,loss.data))
 
 
model.eval()  # 將模型變成測試模式
predict = model(Variable(x_train).cuda())
predict = predict.data.cpu().numpy()
plt.plot(x_train.numpy(),y_train.numpy(),'ro',label = 'original data')
plt.plot(x_train.numpy(),predict,label = 'Fitting line')
plt.show()

結(jié)果如圖所示:

多元回歸:

# _*_encoding=utf-8_*_
# pytorch 里面最基本的操作對象是Tensor,pytorch 的tensor可以和numpy的ndarray相互轉(zhuǎn)化。
# 實現(xiàn)一個線性回歸
# 所有的層結(jié)構(gòu)和損失函數(shù)都來自于 torch.nn
# torch.optim 是一個實現(xiàn)各種優(yōu)化算法的包,調(diào)用的時候必須是需要優(yōu)化的參數(shù)傳入,這些參數(shù)都必須是Variable
 
 
# 實現(xiàn) y = b + w1 *x + w2 *x**2 +w3*x**3
import os
os.environ['CUDA_DEVICE_ORDER']="PCI_BUS_ID"
os.environ['CUDA_VISIBLE_DEVICES']='0'
import torch
import numpy as np
from torch.autograd import Variable
import matplotlib.pyplot as plt
from torch import nn
 
 
# pre_processing
def make_feature(x):
    x = x.unsqueeze(1)   # unsquenze 是為了添加維度1的,0表示第一維度,1表示第二維度,將tensor大小由3變?yōu)椋?,1)
    return torch.cat([x ** i for i in range(1, 4)], 1)
 
# 定義好真實的數(shù)據(jù)
 
 
def f(x):
    W_output = torch.Tensor([0.5, 3, 2.4]).unsqueeze(1)
    b_output = torch.Tensor([0.9])
    return x.mm(W_output)+b_output[0]  # 外積,矩陣乘法
 
 
# 批量處理數(shù)據(jù)
def get_batch(batch_size =32):
 
    random = torch.randn(batch_size)
    x = make_feature(random)
    y = f(x)
    if torch.cuda.is_available():
 
        return Variable(x).cuda(),Variable(y).cuda()
    else:
        return Variable(x),Variable(y)
 
 
 
# def model
class poly_model(nn.Module):
    def __init__(self):
        super(poly_model,self).__init__()
        self.poly = nn.Linear(3,1)
    def forward(self,input):
        output = self.poly(input)
        return output
 
if torch.cuda.is_available():
    print("sdf")
    model = poly_model().cuda()
else:
    model = poly_model()
 
 
# 定義損失函數(shù)和優(yōu)化器
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
 
epoch = 0
while True:
    batch_x, batch_y = get_batch()
    #print(batch_x)
    output = model(batch_x)
    loss = criterion(output,batch_y)
    print_loss = loss.data
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    epoch = epoch +1
    if print_loss < 1e-3:
        print(print_loss)
        break
 
model.eval()
print("Epoch = {}".format(epoch))
 
batch_x, batch_y = get_batch()
predict = model(batch_x)
a = predict - batch_y
y = torch.sum(a)
print('y = ',y)
predict = predict.data.cpu().numpy()
plt.plot(batch_x.cpu().numpy(),batch_y.cpu().numpy(),'ro',label = 'Original data')
plt.plot(batch_x.cpu().numpy(),predict,'b', ls='--',label = 'Fitting line')
plt.show()

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python安裝后測試連接MySQL數(shù)據(jù)庫方式

    Python安裝后測試連接MySQL數(shù)據(jù)庫方式

    這篇文章主要介紹了Python安裝后測試連接MySQL數(shù)據(jù)庫方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • python密碼學(xué)對稱和非對稱密碼教程

    python密碼學(xué)對稱和非對稱密碼教程

    這篇文章主要為大家介紹了python密碼學(xué)對稱和非對稱密碼教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • 一文搞定FastAPI中的查詢參數(shù)

    一文搞定FastAPI中的查詢參數(shù)

    FastAPI中最核心的之一就是路徑參數(shù),所以這篇文章小編主要來和大家介紹一下FastAPI查詢參數(shù)的作用以及基本使用,有需要的小伙伴可以參考下
    2024-03-03
  • 利用Python進(jìn)行數(shù)據(jù)可視化常見的9種方法!超實用!

    利用Python進(jìn)行數(shù)據(jù)可視化常見的9種方法!超實用!

    這篇文章主要給大家介紹了關(guān)于利用Python進(jìn)行數(shù)據(jù)可視化常見的9種方法!文中介紹的方法真的超實用!對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-07-07
  • Python中交換兩個元素的實現(xiàn)方法

    Python中交換兩個元素的實現(xiàn)方法

    今天小編就為大家分享一篇Python中交換兩個元素的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • TensorFlow實現(xiàn)批量歸一化操作的示例

    TensorFlow實現(xiàn)批量歸一化操作的示例

    這篇文章主要介紹了TensorFlow實現(xiàn)批量歸一化操作的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • 使用python查找替換PowerPoint演示文稿中的文本

    使用python查找替換PowerPoint演示文稿中的文本

    演示文稿已成為商務(wù)會議、學(xué)術(shù)報告和教育培訓(xùn)中不可或缺的一部分,而PowerPoint演示文稿作為行業(yè)標(biāo)準(zhǔn)工具,更是承載著無數(shù)創(chuàng)意與信息的載體,本文將介紹如何使用Python來精確查找并替換PowerPoint演示文稿中的文本,需要的朋友可以參考下
    2024-07-07
  • 通俗講解python 裝飾器

    通俗講解python 裝飾器

    這篇文章主要介紹了python 裝飾器的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)python裝飾器的相關(guān)知識,感興趣的朋友可以了解下
    2020-09-09
  • Pyqt5實現(xiàn)英文學(xué)習(xí)詞典

    Pyqt5實現(xiàn)英文學(xué)習(xí)詞典

    這篇文章主要為大家詳細(xì)介紹了Pyqt5實現(xiàn)英文學(xué)習(xí)詞典的相關(guān)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-06-06
  • Python 實現(xiàn)文件打包、上傳與校驗的方法

    Python 實現(xiàn)文件打包、上傳與校驗的方法

    今天小編就為大家分享一篇Python 實現(xiàn)文件打包、上傳與校驗的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-02-02

最新評論

沙田区| 吉林省| 田林县| 介休市| 日照市| 北宁市| 若尔盖县| 黄浦区| 嘉义市| 芜湖市| 临汾市| 南召县| 资兴市| 浦县| 巩留县| 长沙市| 正安县| 永登县| 阳高县| 建宁县| 溧阳市| 陈巴尔虎旗| 宜君县| 河津市| 邵武市| 枣阳市| 罗田县| 陈巴尔虎旗| 靖安县| 瑞安市| 桦南县| 响水县| 屏东市| 彰化县| 封开县| 苍溪县| 浦北县| 灵寿县| 天水市| 江口县| 弋阳县|