欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Pytorch實(shí)現(xiàn)邏輯回歸

 更新時(shí)間:2022年07月30日 10:15:51   作者:AI炮灰  
這篇文章主要為大家詳細(xì)介紹了基于Pytorch實(shí)現(xiàn)邏輯回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(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)文章

最新評(píng)論