網(wǎng)站首頁 編程語言 正文
本文實例為大家分享了Pytorch實現(xiàn)邏輯回歸的具體代碼,供大家參考,具體內(nèi)容如下
1.邏輯回歸
?線性回歸表面上看是“回歸問題”,實際上處理的問題是“分類”問題,邏輯回歸模型是一種廣義的回歸模型,其與線性回歸模型有很多的相似之處,模型的形式也基本相同,唯一不同的地方在于邏輯回歸會對y作用一個邏輯函數(shù),將其轉(zhuǎn)化為一種概率的結(jié)果。邏輯函數(shù)也稱為Sigmoid函數(shù),是邏輯回歸的核心。
2.基于Pytorch實現(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()返回一個張量,張量里面的隨機(jī)數(shù)是從相互獨立的正態(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
# 實例化
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()
? ? ? ? # 計算正確預(yù)測樣本的個數(shù)
? ? ? ? correct = (mask==y_data).sum()
? ? ? ? # 計算精度
? ? ? ? acc = correct.item()/x_data.size(0)
? ? ? ? optimizer.zero_grad()
? ? ? ? loss.backward()
? ? ? ? optimizer.step()
? ? ? ? # 每個200個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()
原文鏈接:https://blog.csdn.net/bigData1994pb/article/details/117701829
相關(guān)推薦
- 2022-06-15 C#實現(xiàn)冒泡排序和插入排序算法_C#教程
- 2022-05-11 使用git命令上傳代碼_其它綜合
- 2022-12-11 C語言如何計算一個整數(shù)的位數(shù)_C 語言
- 2022-07-26 Assertion failed: cond.is_weights() && con
- 2022-09-12 IOS開發(fā)自定義view方法規(guī)范示例_IOS
- 2023-02-09 Go語言高效編程的3個技巧總結(jié)_Golang
- 2022-02-09 Qt5連接并操作PostgreSQL數(shù)據(jù)庫的實現(xiàn)示例_C 語言
- 2024-03-04 layui表單重置按鈕不生效的問題
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支