当前位置:网站首页>6. Logistic model
6. Logistic model
2022-07-05 05:41:00 【A big pigeon】
Logistic model To solve the problem of classification .
If the first 5 The problem with section Whether to pass , It is a binary classification problem .

The output is the probability of passing the exam P. probability P stay 0 To 1 Between .
The output range of the original linear model is R ( The set of real Numbers ), The original output can be mapped to [0,1] Within the scope of .

It only needs two changes to change the linear model into the logistic model , Model plus sigmod() And the loss function is changed to BCELoss


Complete code :
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
# 1. Prepare the data , Note that they are all in matrix form
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]])
# 2. The design model ( class ) Inherit nn.Module In order to use its method
class LogisticRegressionModel(torch.nn.Module):
# initialization
def __init__(self):
super(LogisticRegressionModel, self).__init__()
self.linear = torch.nn.Linear(1, 1) # Linear Is a linear unit
# Feedforward method
def forward(self, x):
y_pred = F.sigmoid(self.linear(x)) # In fact, the calling object linear Of __call__() Method ,linear Of __call__() Method execution forward feedforward
return y_pred
model = LogisticRegressionModel()
# 3 loss and optimizer( Optimizer )
criterion = torch.nn.BCELoss(size_average=False) # There is no need to find the mean
# Optimizer . model.parameters() Get the parameters that need to be optimized in the model ,lr(learning rate, Learning rate )
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# 4 Training process
for epoch in range(1000):
# feedforward
y_pred = model(x_data)
# Calculate the loss
loss = criterion(y_pred, y_data)
print("epoch={},loss={}".format(epoch, loss))
optimizer.zero_grad() # Zeroing
# Back propagation
loss.backward()
# to update 、 Optimization parameters
optimizer.step()
# Test, Check the model parameters and test the training effect
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = {} for x = {}'.format(y_test.data, x_test.data))
# mapping
x = np.linspace(0,10,200)
x_t = torch.Tensor(x).view((200, 1))
y_t = model(x_t)
y = y_t.data.numpy()
plt.plot(x, y)
plt.plot([0,10], [.5,.5], c='r')
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()
边栏推荐
- Sword finger offer 09 Implementing queues with two stacks
- 搭建完数据库和网站后.打开app测试时候显示服务器正在维护.
- 2022年贵州省职业院校技能大赛中职组网络安全赛项规程
- 剑指 Offer 58 - II. 左旋转字符串
- Animation scoring data analysis and visualization and it industry recruitment data analysis and visualization
- Acwing 4300. Two operations
- Configuration and startup of kubedm series-02-kubelet
- 2017 USP Try-outs C. Coprimes
- High precision subtraction
- Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail
猜你喜欢

剑指 Offer 58 - II. 左旋转字符串

Little known skills of Task Manager

Sword finger offer 35 Replication of complex linked list

读者写者模型

【实战技能】如何做好技术培训?

YOLOv5-Shufflenetv2

Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module

sync. Interpretation of mutex source code

【Jailhouse 文章】Jailhouse Hypervisor

Introduction et expérience de wazuh open source host Security Solution
随机推荐
常见的最优化方法
Introduction to convolutional neural network
[cloud native] record of feign custom configuration of microservices
Sword finger offer 06 Print linked list from beginning to end
【实战技能】非技术背景经理的技术管理
每日一题-搜索二维矩阵ps二维数组的查找
Personal developed penetration testing tool Satania v1.2 update
ALU逻辑运算单元
The number of enclaves
Sword finger offer 09 Implementing queues with two stacks
Csp-j-2020-excellent split multiple solutions
kubeadm系列-00-overview
SAP method of modifying system table data
Using HashMap to realize simple cache
Scope of inline symbol
Control unit
Educational Codeforces Round 107 (Rated for Div. 2) E. Colorings and Dominoes
Wazuh开源主机安全解决方案的简介与使用体验
Use of room database
[jailhouse article] look mum, no VM exits