溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

pytorch如何使用nn.Moudle實(shí)現(xiàn)邏輯回歸

發(fā)布時(shí)間:2022-07-30 14:23:31 來源:億速云 閱讀:97 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“pytorch如何使用nn.Moudle實(shí)現(xiàn)邏輯回歸”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“pytorch如何使用nn.Moudle實(shí)現(xiàn)邏輯回歸”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

問題

loss下降不明顯

解決方法

#源代碼 out的數(shù)據(jù)接收方式
     if torch.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)  #根據(jù)邏輯回歸模型擬合出的y值
    loss=criterion(out.squeeze(),y_data)  #計(jì)算損失函數(shù)
#源代碼 out的數(shù)據(jù)有拼裝數(shù)據(jù)直接輸入
#     if torch.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)  #根據(jù)邏輯回歸模型擬合出的y值
    loss=criterion(out.squeeze(),y_data)  #計(jì)算損失函數(shù)
    print_loss=loss.data.item()  #得出損失函數(shù)值

源代碼

import torch
from torch import nn
from torch.autograd import Variable
import matplotlib.pyplot as plt
import numpy as np

#生成數(shù)據(jù)
sample_nums = 100
mean_value = 1.7
bias = 1
n_data = torch.ones(sample_nums, 2)
x0 = torch.normal(mean_value * n_data, 1) + bias      # 類別0 數(shù)據(jù) shape=(100, 2)
y0 = torch.zeros(sample_nums)                         # 類別0 標(biāo)簽 shape=(100, 1)
x1 = torch.normal(-mean_value * n_data, 1) + bias     # 類別1 數(shù)據(jù) shape=(100, 2)
y1 = torch.ones(sample_nums)                          # 類別1 標(biāo)簽 shape=(100, 1)
x_data = torch.cat((x0, x1), 0)  #按維數(shù)0行拼接
y_data = torch.cat((y0, y1), 0)

#畫圖
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn')
plt.show()

# 利用torch.nn實(shí)現(xiàn)邏輯回歸
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()
# if torch.cuda.is_available():
#     logistic_model.cuda()

#loss函數(shù)和優(yōu)化
criterion = nn.BCELoss()
optimizer = torch.optim.SGD(logistic_model.parameters(), lr=0.01, momentum=0.9)
#開始訓(xùn)練
#訓(xùn)練10000次
for epoch in range(10000):
#     if torch.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)  #根據(jù)邏輯回歸模型擬合出的y值
    loss=criterion(out.squeeze(),y_data)  #計(jì)算損失函數(shù)
    print_loss=loss.data.item()  #得出損失函數(shù)值
    #反向傳播
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
    
    mask=out.ge(0.5).float()  #以0.5為閾值進(jìn)行分類
    correct=(mask==y_data).sum().squeeze()  #計(jì)算正確預(yù)測(cè)的樣本個(gè)數(shù)
    acc=correct.item()/x_data.size(0)  #計(jì)算精度
    #每隔20輪打印一下當(dāng)前的誤差和精度
    if (epoch+1)%100==0:
        print('*'*10)
        print('epoch {}'.format(epoch+1))  #誤差
        print('loss is {:.4f}'.format(print_loss))
        print('acc is {:.4f}'.format(acc))  #精度
        
        
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.xlim(-5, 7)
plt.ylim(-7, 7)
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=logistic_model(x_data)[:,0].cpu().data.numpy(), s=100, lw=0, cmap='RdYlGn')
plt.plot(plot_x, plot_y)
plt.show()

輸出結(jié)果

pytorch如何使用nn.Moudle實(shí)現(xiàn)邏輯回歸

pytorch如何使用nn.Moudle實(shí)現(xiàn)邏輯回歸

讀到這里,這篇“pytorch如何使用nn.Moudle實(shí)現(xiàn)邏輯回歸”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI