pytorch實(shí)現(xiàn)邏輯回歸
本文實(shí)例為大家分享了pytorch實(shí)現(xiàn)邏輯回歸的具體代碼,供大家參考,具體內(nèi)容如下
一、pytorch實(shí)現(xiàn)邏輯回歸
邏輯回歸是非常經(jīng)典的分類算法,是用于分類任務(wù),如垃圾分類任務(wù),情感分類任務(wù)等都可以使用邏輯回歸。
接下來(lái)使用邏輯回歸模型完成一個(gè)二分類任務(wù):
# 使用邏輯回歸完成一個(gè)二分類任務(wù) # 數(shù)據(jù)準(zhǔn)備 import torch import matplotlib.pyplot as plt x1 = torch.randn(365)+1.5 # randn():輸出一個(gè)形狀為size的標(biāo)準(zhǔn)正態(tài)分布Tensor x2 = torch.randn(365)-1.5 #print(x1.shape) # torch.Size([365]) #print(x2.shape) # torch.Size([365]) data = zip(x1.data.numpy(),x2.data.numpy()) # 創(chuàng)建一個(gè)聚合了來(lái)自每個(gè)可迭代對(duì)象中的元素的迭代器。 x = [1,2,3] pos = [] neg = [] def classification(data): for i in data: if (i[0] > 1.5+0.1*torch.rand(1).item()*(-1)**torch.randint(1,10,(1,1)).item()): pos.append(i) else: neg.append(i) classification(data) # 將正、負(fù)兩類數(shù)據(jù)可視化 pos_x = [i[0] for i in pos] pos_y = [i[1] for i in pos] neg_x = [i[0] for i in neg] neg_y = [i[1] for i in neg] plt.scatter(pos_x,pos_y,c = 'r',marker = "*") plt.scatter(neg_x,neg_y,c = 'b',marker = "^") plt.show() # 構(gòu)造正、負(fù)兩類數(shù)據(jù)可視化結(jié)果如上圖所示 # 構(gòu)建模型 import torch.nn as nn class LogisticRegression(nn.Module): def __init__(self): super(LogisticRegression, self).__init__() self.linear = nn.Linear(2,1) self.sigmoid = nn.Sigmoid() def forward(self,x): return self.sigmoid(self.linear(x)) model = LogisticRegression() criterion = nn.BCELoss() optimizer = torch.optim.SGD(model.parameters(),0.01) epoch = 5000 features = [[i[0],i[1]] for i in pos] features.extend([[i[0],i[1]] for i in neg]) #extend 接受一個(gè)參數(shù),這個(gè)參數(shù)總是一個(gè) list,并且把這個(gè) list 中的每個(gè)元素添加到原 list 中 features = torch.Tensor(features) # torch.Tensor 生成單精度浮點(diǎn)類型的張量 label = [1 for i in range(len(pos))] label.extend(0 for i in range(len(neg))) label = torch.Tensor(label) print(label.shape) for i in range(500000): out = model(features) #print(out.shape) loss = criterion(out.squeeze(1),label) optimizer.zero_grad() loss.backward() optimizer.step() # 分類任務(wù)準(zhǔn)確率 acc = (out.ge(0.5).float().squeeze(1)==label).sum().float()/features.size()[0] if (i % 10000 ==0): plt.scatter(pos_x, pos_y, c='r', marker="*") plt.scatter(neg_x, neg_y, c='b', marker="^") weight = model.linear.weight[0] #print(weight.shape) wo = weight[0] w1 = weight[1] b = model.linear.bias.data[0] # 繪制分界線 test_x = torch.linspace(-10,10,500) # 500個(gè)點(diǎn) test_y = (-wo*test_x - b) / w1 plt.plot(test_x.data.numpy(),test_y.data.numpy(),c="pink") plt.title("acc:{:.4f},loss:{:.4f}".format(acc,loss)) plt.ylim(-5,3) plt.xlim(-3,5) plt.show()
附上分類結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python編程快速上手——strip()函數(shù)的正則表達(dá)式實(shí)現(xiàn)方法分析
這篇文章主要介紹了Python strip()函數(shù)的正則表達(dá)式實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python基于正則表達(dá)式實(shí)現(xiàn)strip()函數(shù)的方法,需要的朋友可以參考下2020-02-02python?opencv背景減去法摳圖實(shí)現(xiàn)示例
這篇文章主要為大家介紹了python?opencv背景減去法摳圖實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05上手簡(jiǎn)單,功能強(qiáng)大的Python爬蟲(chóng)框架——feapder
這篇文章主要介紹了上手簡(jiǎn)單,功能強(qiáng)大的Python爬蟲(chóng)框架——feapder的使用教程,幫助大家更好的利用python進(jìn)行爬蟲(chóng),感興趣的朋友可以了解下2021-04-04Python實(shí)現(xiàn)雙軸組合圖表柱狀圖和折線圖的具體流程
這篇文章主要介紹了Python雙軸組合圖表柱狀圖+折線圖,Python繪制雙軸組合的關(guān)鍵在plt庫(kù)的twinx()函數(shù),具體實(shí)例代碼跟隨小編一起看看吧2021-08-08Python 面向?qū)ο笾庋b、繼承、多態(tài)操作實(shí)例分析
這篇文章主要介紹了Python 面向?qū)ο笾庋b、繼承、多態(tài)操作,結(jié)合實(shí)例形式分析了Python面相對(duì)象程序設(shè)計(jì)中封裝、繼承、多態(tài)相關(guān)操作技巧與使用注意事項(xiàng),需要的朋友可以參考下2019-11-11python機(jī)器學(xué)習(xí)實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)示例解析
這篇文章主要為大家介紹了python機(jī)器學(xué)習(xí)python實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)的示例解析,在同樣在進(jìn)行python機(jī)器學(xué)習(xí)的同學(xué)可以借鑒參考下,希望能夠有所幫助2021-10-10python破解WiFi教程代碼,Python蹭網(wǎng)原理講解
用Python生成一個(gè)簡(jiǎn)單的密碼本,一般是有數(shù)字、字母和符號(hào)組成,這里用到的思路主要是窮舉法。通過(guò)使用pywifi?模塊,根據(jù)密碼本暴力破解WiFi。本文只是從技術(shù)的角度來(lái)闡述學(xué)習(xí)Pywifi庫(kù)!并不建議大家做任何破壞性的操作和任何不當(dāng)?shù)男袨椋?/div> 2023-01-01最新評(píng)論