PyTorch實現(xiàn)多維度特征輸入邏輯回歸
一、實現(xiàn)過程
1、準(zhǔn)備數(shù)據(jù)
本文數(shù)據(jù)采取文獻[1]給出的數(shù)據(jù)集,該數(shù)據(jù)集前8列為特征,最后1列為標(biāo)簽(0/1)。本模型使用pandas處理該數(shù)據(jù)集,需要注意的是,原始數(shù)據(jù)集沒有特征名稱,需要自己在第一行添加上去,否則,pandas會把第一行的數(shù)據(jù)當(dāng)成特征名稱處理,從而影響最后的分類效果。
代碼如下:
# 1、準(zhǔn)備數(shù)據(jù)
import torch
import pandas as pd
import numpy as np
xy = pd.read_csv('G:/datasets/diabetes/diabetes.csv',dtype=np.float32)?? ?# 文件路徑
x_data = torch.from_numpy(xy.values[:,:-1])
y_data = torch.from_numpy(xy.values[:,[-1]])2、設(shè)計模型
本文采取文獻[1]的思路,激活函數(shù)使用ReLU,最后一層使用Sigmoid函數(shù),
代碼如下:
class Model(torch.nn.Module): ? ? def __init__(self): ? ? ? ? super(Model,self).__init__() ? ? ? ? self.linear1 = torch.nn.Linear(8,6) ? ? ? ? self.linear2 = torch.nn.Linear(6,4) ? ? ? ? self.linear3 = torch.nn.Linear(4,1) ? ? ? ? self.activate = torch.nn.ReLU() ? ?? ? ? def forward(self, x): ? ? ? ? x = self.activate(self.linear1(x)) ? ? ? ? x = self.activate(self.linear2(x)) ? ? ? ? x = torch.sigmoid(self.linear3(x)) ? ? ? ? return x model = Model()
將模型和數(shù)據(jù)加載到GPU上,代碼如下:
### 將模型和訓(xùn)練數(shù)據(jù)加載到GPU上
# 模型加載到GPU上
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
# 數(shù)據(jù)加載到GPU上
x = x_data.to(device)
y = y_data.to(device)3、構(gòu)造損失函數(shù)和優(yōu)化器 criterion = torch.nn.BCELoss(reduction='mean') optimizer = torch.optim.SGD(model.parameters(),lr=0.1)
4、訓(xùn)練過程
epoch_list = [] loss_list = [] epochs = 10000 for epoch in range(epochs): ? ? # Forward ? ? y_pred = model(x) ? ? loss = criterion(y_pred, y) ? ? print(epoch, loss) ? ? epoch_list.append(epoch) ? ? loss_list.append(loss.data.item()) ? ? # Backward ? ? optimizer.zero_grad() ? ? loss.backward() ? ? # Update ? ? optimizer.step()
5、結(jié)果展示
查看各個層的權(quán)重和偏置:
model.linear1.weight,model.linear1.bias model.linear2.weight,model.linear2.bias model.linear3.weight,model.linear3.bias
損失值隨迭代次數(shù)的變化曲線:
# 繪圖展示
plt.plot(epoch_list,loss_list,'b')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.grid()
plt.show()
最終的損失和準(zhǔn)確率:
# 準(zhǔn)確率
y_pred_label = torch.where(y_pred.data.cpu() >= 0.5,torch.tensor([1.0]),torch.tensor([0.0]))
acc = torch.eq(y_pred_label, y_data).sum().item()/y_data.size(0)
print("loss = ",loss.item(), "acc = ",acc)
loss = ?0.4232381284236908 acc = ?0.7931488801054019二、參考文獻
- [1] https://www.bilibili.com/video/BV1Y7411d7Ys?p=7
- [2] https://blog.csdn.net/bit452/article/details/109682078
到此這篇關(guān)于PyTorch實現(xiàn)多維度特征輸入邏輯回歸的文章就介紹到這了,更多相關(guān)PyTorch邏輯回歸內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用keras實現(xiàn)densenet和Xception的模型融合
這篇文章主要介紹了使用keras實現(xiàn)densenet和Xception的模型融合,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python卷積神經(jīng)網(wǎng)絡(luò)圖片分類框架詳解分析
在機器視覺領(lǐng)域中,卷積神經(jīng)網(wǎng)絡(luò)算法作為一種新興算法出現(xiàn),在圖像識別領(lǐng)域中,卷積神經(jīng)網(wǎng)絡(luò)能夠較好的實現(xiàn)圖像的分類效果,而且其位移和形變具有較高的容忍能力2021-11-11
Python爬取肯德基官網(wǎng)ajax的post請求實現(xiàn)過程
這篇文章主要介紹了Python爬取肯德基官網(wǎng)ajax的post請求實現(xiàn)過程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家學(xué)有所得,多多進步2021-10-10

