《PyTorch深度学习实践》02.PyTorch实现Logistic Regression(分类问题)

Nannan Lv5

《PyTorch深度学习实践》.PyTorch实现Logistic Regression(分类问题)

一、Regression v.s. Classification

image-20240710190754854

How to map: R -> [0,1] ?

image-20240710191246571

Sigmoid functions

image-20240710191517202

二、Logistic Function

1.Logistic Regression Model

image-20240710191617071

2.Loss function for Binary Classification

image-20240710195806388

BCE损失:

image-20240710195853670

3. Implementation of Logistic Regression

Init:

image-20240710200010003

BCELoss:

image-20240710200204630

4个步骤:

image-20240710200306053

三、Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import torch
import torch.nn.functional as F

x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[2.0],[4.0],[6.0]])

class LogisticRegressionModel(torch.nn.Model):
def __init__(self):
super(LogisticRegressionModel,self.__init__)
self.liner = torch.nn.liner(1,1)

def forward(self,x):
y_pred = F.sigmoid(self.liner(x))
return y_pred

model = LogisticRegressionModel()

criterion = torch.nn.BCELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)

for epoch in range(100):
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
print(epoch,loss)

optimizer.zero_grad()
loss.backward()
optimizer.step()


print('w=',model.liner.weight.item())
print('b=',model.liner.bias.item())

x_test = torch.Tensor([4.0])
y_test = model(x_test)
print('y_pred=',y_test.data)

  • Title: 《PyTorch深度学习实践》02.PyTorch实现Logistic Regression(分类问题)
  • Author: Nannan
  • Created at : 2024-07-12 20:52:41
  • Updated at : 2024-09-29 23:20:25
  • Link: https://redefine.ohevan.com/2024/07/12/【实践】02.Logistic Regression/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments