網站首頁 編程語言 正文
本文實例為大家分享了Pytorch實現邏輯回歸的具體代碼,供大家參考,具體內容如下
1.邏輯回歸
?線性回歸表面上看是“回歸問題”,實際上處理的問題是“分類”問題,邏輯回歸模型是一種廣義的回歸模型,其與線性回歸模型有很多的相似之處,模型的形式也基本相同,唯一不同的地方在于邏輯回歸會對y作用一個邏輯函數,將其轉化為一種概率的結果。邏輯函數也稱為Sigmoid函數,是邏輯回歸的核心。
2.基于Pytorch實現邏輯回歸
import torch as t
import matplotlib.pyplot as plt
from torch import nn
from torch.autograd import Variable
import numpy as np
?
?
# 構造數據集
n_data = t.ones(100, 2)
# normal()返回一個張量,張量里面的隨機數是從相互獨立的正態分布中隨機生成的。
x0 = t.normal(2*n_data, 1)
y0 = t.zeros(100)
x1 = t.normal(-2*n_data, 1)
y1 = t.ones(100)
?
# 把數據給合并以下,并且數據的形式必須是下面形式
x = t.cat((x0, x1), 0).type(t.FloatTensor)
y = t.cat((y0, y1), 0).type(t.FloatTensor)
?
# 觀察制造的數據
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()
# 定義損失函數和優化函數
criterion = nn.BCELoss()
optimizer = t.optim.SGD(logistic_model.parameters(), lr=1e-3, momentum=0.9)
# 訓練模型
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為閾值進行分類
? ? ? ? mask = out.ge(0.5).float()
? ? ? ? # 計算正確預測樣本的個數
? ? ? ? correct = (mask==y_data).sum()
? ? ? ? # 計算精度
? ? ? ? acc = correct.item()/x_data.size(0)
? ? ? ? optimizer.zero_grad()
? ? ? ? loss.backward()
? ? ? ? optimizer.step()
? ? ? ? # 每個200個epoch打印一次當前的誤差和精度
? ? ? ? if(epoch+1)%200==0:
? ? ? ? ? ? print('*'*10)
? ? ? ? ? ? # 迭代次數
? ? ? ? ? ? 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
相關推薦
- 2022-04-11 C#實現簡易計算器功能(1)(窗體應用)_C#教程
- 2022-02-09 Qt5連接并操作PostgreSQL數據庫的實現示例_C 語言
- 2022-07-28 XML基本概念XPath、XSLT與XQuery函數介紹_XML/RSS
- 2022-06-12 Python語法學習之線程的創建與常用方法詳解_python
- 2023-05-16 pyinstaller打包遇到的問題解決_python
- 2022-04-16 如何使用pyinstaller打包時引入自己編寫的庫_python
- 2023-03-27 Android進階之從IO到NIO的模型機制演進_Android
- 2022-07-26 golang控制goroutine數量以及獲取處理結果
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支