当前位置:网站首页>Torch learning notes (6) -- logistic regression model (self training)
Torch learning notes (6) -- logistic regression model (self training)
2022-07-03 18:22:00 【ZRX_ GIS】
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# Logical regression (Logistic Regression)
# LR It is a linear binary classification model
# y = f(wx+b) f(x) = 1/(1+e**-x) f(x) Also known as Sigmoid Function or Logistic function
# LR effect : Map input data to [0,1]
# Process quantity classification adopts “ rounding , Realize overall two classification
# Linear regression is the analysis of independent variables x And scalar y The method of the relationship between
# LR Is the analysis independent variable x And probability y The method of the relationship between
# LR It can also be generated by variant “ Logarithmic probability regression model ” ln(y/1-y) = wx+b
# Machine learning steps :data( collection 、 cleaning 、 Divide 、 Preprocessing )、model、Loss、optim
# LR Case study
# data
sample_num = torch.tensor([100.], requires_grad=True)
mean_value = 1.7
bias = 1
n_data = torch.normal(sample_num, 2)
x0 = torch.normal(mean_value * n_data, 1) + bias # Normal distribution generates
y0 = torch.zeros(100)
x1 = torch.normal(-mean_value * n_data, 1) + bias
y1 = torch.ones(100)
train_x = torch.cat((x0, x1), 0) # Splicing variables
train_y = torch.cat((y0, y1), 0)
# model
class LR(nn.Module):
def __init__(self):
super(LR, self).__init__()
self.features = nn.Linear(2, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.features(x)
x = self.sigmoid(x)
# Instantiation LR
LR = LR()
# Loss
loss_fn = nn.BCELoss()
# optim
lr = 0.01 # Learning rate
optimizer = torch.optim.SGD(LR.parameters(), lr=lr, momentum=0.9)
# train
for iteration in range(1000):
y_pred = LR(train_x)
loss = loss_fn(y_pred.squeeze(), train_y)
loss.backward()
optimizer.step()
# mapping
if iteration % 20 == 0:
mask = y_pred.ge(0.5).float().squeeze() # 0.5 Classify thresholds
correct = (mask == train_y).sum() # Number of correct classifications
acc = correct.item() / train_y.size(0) # precision
plt.scatter(x0.data.numpy()[:, 0], x0.data.numpy()[:, 1], c='r', label='class 0')
plt.scatter(x1.data.numpy()[:, 0], x1.data.numpy()[:, 1], c='b', label='class 1')
w0, w1 = LR.features.weight[0]
w0, w1 = float(w0.item()), float(w1.item())
plot_b = float(LR.features.bias[0].item())
plot_x = np.arange(-6, 6, 0.1)
plot_y = (-w0 * plot_x - plot_b) / w1
plt.xlim(-5, 7)
plt.xlim(-5, 7)
plt.plot(plot_x, plot_y)
plt.legend()
plt.show()
plt.pause(0.5)
if acc >= 0.99: break
边栏推荐
- Should I be laid off at the age of 40? IBM is suspected of age discrimination, calling its old employees "dinosaurs" and planning to dismiss, but the employees can't refute it
- [combinatorics] generating function (property summary | important generating function)*
- PHP MySQL where clause
- Win 11 major updates, new features love love.
- Reappearance of ASPP (atlas spatial pyramid pooling) code
- [combinatorics] generating function (positive integer splitting | repeated ordered splitting | non repeated ordered splitting | proof of the number of repeated ordered splitting schemes)
- How many convolution methods does deep learning have? (including drawings)
- Introduction to PHP MySQL
- PHP MySQL preprocessing statement
- 198. Looting - Dynamic Planning
猜你喜欢

2022-2028 global lithium battery copper foil industry research and trend analysis report

Nodejs (01) - introductory tutorial

2022-2028 global petroleum pipe joint industry research and trend analysis report
![[untitled]](/img/83/5a57ed90aaafde94db600246256867.jpg)
[untitled]

CTO and programmer were both sentenced for losing control of the crawler

Prototype inheritance..

Line by line explanation of yolox source code of anchor free series network (5) -- mosaic data enhancement and mathematical understanding

(8) HS corner detection

Redis core technology and practice - learning notes (VIII) sentinel cluster: sentinel hung up

PHP MySQL inserts multiple pieces of data
随机推荐
Analysis of the reasons why enterprises build their own software development teams to use software manpower outsourcing services at the same time
[combinatorics] exponential generating function (example 2 of solving multiple set permutation with exponential generating function)
Applet with multiple tabs and Swipers + paging of each tab
2022-2028 global solid phase extraction column industry research and trend analysis report
Postfix tips and troubleshooting commands
SDNUOJ1015
Install apache+php+mysql+phpmyadmin xampp and its error resolution
Computer graduation design PHP campus address book telephone number inquiry system
As soon as we enter "remote", we will never regret, and several people will be happy and several people will be sad| Community essay solicitation
Codeforces Round #803 (Div. 2) C. 3SUM Closure
图像24位深度转8位深度
Class exercises
[combinatorics] generating function (positive integer splitting | repeated ordered splitting | non repeated ordered splitting | proof of the number of repeated ordered splitting schemes)
[LINUX]CentOS 7 安装MYSQL时报错“No package mysql-server available“No package zabbix-server-mysql availabl
[教程]在 CoreOS 上构建你的第一个应用
[combinatorics] exponential generating function (properties of exponential generating function | exponential generating function solving multiple set arrangement)
PHP determines which constellation it belongs to today
Redis core technology and practice - learning notes (IX): slicing cluster
[tutorial] build your first application on coreos
Valentine's day, send you a little red flower~