基于Pytorch實(shí)現(xiàn)邏輯回歸
本文實(shí)例為大家分享了Pytorch實(shí)現(xiàn)邏輯回歸的具體代碼,供大家參考,具體內(nèi)容如下
1.邏輯回歸
線性回歸表面上看是“回歸問題”,實(shí)際上處理的問題是“分類”問題,邏輯回歸模型是一種廣義的回歸模型,其與線性回歸模型有很多的相似之處,模型的形式也基本相同,唯一不同的地方在于邏輯回歸會(huì)對(duì)y作用一個(gè)邏輯函數(shù),將其轉(zhuǎn)化為一種概率的結(jié)果。邏輯函數(shù)也稱為Sigmoid函數(shù),是邏輯回歸的核心。
2.基于Pytorch實(shí)現(xiàn)邏輯回歸
import torch as t import matplotlib.pyplot as plt from torch import nn from torch.autograd import Variable import numpy as np ? ? # 構(gòu)造數(shù)據(jù)集 n_data = t.ones(100, 2) # normal()返回一個(gè)張量,張量里面的隨機(jī)數(shù)是從相互獨(dú)立的正態(tài)分布中隨機(jī)生成的。 x0 = t.normal(2*n_data, 1) y0 = t.zeros(100) x1 = t.normal(-2*n_data, 1) y1 = t.ones(100) ? # 把數(shù)據(jù)給合并以下,并且數(shù)據(jù)的形式必須是下面形式 x = t.cat((x0, x1), 0).type(t.FloatTensor) y = t.cat((y0, y1), 0).type(t.FloatTensor) ? # 觀察制造的數(shù)據(jù) plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0) plt.show() ? # 建立邏輯回歸 class LogisticRegression(nn.Module): ? ? def __init__(self): ? ? ? ? super(LogisticRegression, self).__init__() ? ? ? ? self.lr = nn.Linear(2, 1) ? ? ? ? self.sm = nn.Sigmoid() ? ? def forward(self, x): ? ? ? ? x = self.lr(x) ? ? ? ? x = self.sm(x) ? ? ? ? return x # 實(shí)例化 logistic_model = LogisticRegression() # 看GPU是否可使用,如果可以使用GPU否則不使用 if t.cuda.is_available(): ? ? logistic_model.cuda() # 定義損失函數(shù)和優(yōu)化函數(shù) criterion = nn.BCELoss() optimizer = t.optim.SGD(logistic_model.parameters(), lr=1e-3, momentum=0.9) # 訓(xùn)練模型 for epoch in range(1000): ? ? if t.cuda.is_available(): ? ? ? ? x_data = Variable(x).cuda() ? ? ? ? y_data = Variable(y).cuda() ? ? else: ? ? ? ? x_data = Variable(x) ? ? ? ? y_data = Variable(y) ? ? ? ? out = logistic_model(x_data) ? ? ? ? loss = criterion(out, y_data) ? ? ? ? print_loss = loss.data.item() ? ? ? ? # 以0.5為閾值進(jìn)行分類 ? ? ? ? mask = out.ge(0.5).float() ? ? ? ? # 計(jì)算正確預(yù)測(cè)樣本的個(gè)數(shù) ? ? ? ? correct = (mask==y_data).sum() ? ? ? ? # 計(jì)算精度 ? ? ? ? acc = correct.item()/x_data.size(0) ? ? ? ? optimizer.zero_grad() ? ? ? ? loss.backward() ? ? ? ? optimizer.step() ? ? ? ? # 每個(gè)200個(gè)epoch打印一次當(dāng)前的誤差和精度 ? ? ? ? if(epoch+1)%200==0: ? ? ? ? ? ? print('*'*10) ? ? ? ? ? ? # 迭代次數(shù) ? ? ? ? ? ? print('epoch{}'.format(epoch+1)) ? ? ? ? ? ? # 誤差 ? ? ? ? ? ? print('loss is {:.4f}'.format((print_loss))) ? ? ? ? ? ? # 精度 ? ? ? ? ? ? print('acc is {:.4f}'.format(acc)) if __name__=="__main__": ? ? logistic_model.eval() ? ? w0, w1 = logistic_model.lr.weight[0] ? ? w0 = float(w0.item()) ? ? w1 = float(w1.item()) ? ? b = float(logistic_model.lr.bias.item()) ? ? plot_x = np.arange(-7, 7, 0.1) ? ? plot_y = (-w0*plot_x-b)/w1 ? ? plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0) ? ? plt.plot(plot_x, plot_y) ? ? plt.show()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
跟老齊學(xué)Python之賦值,簡(jiǎn)單也不簡(jiǎn)單
在《初識(shí)永遠(yuǎn)強(qiáng)大的函數(shù)》一文中,有一節(jié)專門討論“取名字的學(xué)問”,就是有關(guān)變量名稱的問題,本溫故而知新的原則,這里要復(fù)習(xí)一下2014-09-09Python Matplotlib繪制箱型圖(箱線圖)boxplot的方法詳解
箱線圖(箱型圖)主要作用是發(fā)現(xiàn)數(shù)據(jù)內(nèi)部整體的分布分散情況,包括上下限、各分位數(shù)、異常值等,本文為大家整理了Matplotlib繪制箱型圖的所以方法,希望對(duì)大家有所幫助2023-05-05pandas去除重復(fù)列的實(shí)現(xiàn)方法
這篇文章主要介紹了pandas去除重復(fù)列的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01Pytorch訓(xùn)練模型得到輸出后計(jì)算F1-Score 和AUC的操作
這篇文章主要介紹了Pytorch訓(xùn)練模型得到輸出后計(jì)算F1-Score 和AUC的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05pytorch讀取圖像數(shù)據(jù)轉(zhuǎn)成opencv格式實(shí)例
這篇文章主要介紹了pytorch讀取圖像數(shù)據(jù)轉(zhuǎn)成opencv格式實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06Pandas自定義選項(xiàng)option設(shè)置
pandas有一個(gè)option系統(tǒng)可以控制pandas的展示情況,一般來說我們不需要進(jìn)行修改,但是不排除特殊情況下的修改需求。本文將會(huì)詳細(xì)講解pandas中的option設(shè)置,感興趣的可以了解下2021-07-07使用Python下的XSLT API進(jìn)行web開發(fā)的簡(jiǎn)單教程
這篇文章主要介紹了使用Python下的XSLT API進(jìn)行web開發(fā)的簡(jiǎn)單教程,本文來自于IBM官方網(wǎng)站技術(shù)文檔,需要的朋友可以參考下2015-04-04python 實(shí)現(xiàn)百度網(wǎng)盤非會(huì)員上傳超過500個(gè)文件的方法
這篇文章主要介紹了python 實(shí)現(xiàn)百度網(wǎng)盤非會(huì)員上傳超過500個(gè)文件的方法,幫助大家更好的利用python解決問題,感興趣的朋友可以了解下2021-01-01