当前位置:网站首页>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
边栏推荐
- Kotlin's collaboration: Context
- [combinatorics] generating function (use generating function to solve the number of solutions of indefinite equation)
- Supervisor monitors gearman tasks
- [combinatorics] generating function (positive integer splitting | basic model of positive integer splitting | disordered splitting with restrictions)
- English语法_形容词/副词3级 - 倍数表达
- An academic paper sharing and approval system based on PHP for computer graduation design
- SQL injection -day16
- 模块九作业
- Unsafe类的使用
- 2022-2028 global sepsis treatment drug industry research and trend analysis report
猜你喜欢

Win 11 major updates, new features love love.

模块九作业

2022-2028 global petroleum pipe joint industry research and trend analysis report

How to analyze the rising and falling rules of London gold trend chart

How many convolution methods does deep learning have? (including drawings)

PHP MySQL inserts multiple pieces of data

Computer graduation design PHP sports goods online sales system website

Computer graduation design PHP makeup sales Beauty shopping mall

What kind of experience is it when the Institute earns 20000 yuan a month?

2022-2028 global plasmid DNA cdmo industry research and trend analysis report
随机推荐
A. Berland Poker &1000【简单数学思维】
Redis core technology and practice - learning notes (VIII) sentinel cluster: sentinel hung up
2022-2028 global marking ink industry research and trend analysis report
How to expand the capacity of golang slice slice
[combinatorics] generating function (generating function application scenario | using generating function to solve recursive equation)
Reappearance of ASPP (atlas spatial pyramid pooling) code
Keepalived setting does not preempt resources
[教程]在 CoreOS 上构建你的第一个应用
企业级自定义表单引擎解决方案(十二)--表单规则引擎2
[untitled]
Classroom attendance system based on face recognition tkinter+openpyxl+face_ recognition
2022-2028 global petroleum pipe joint industry research and trend analysis report
Unsafe类的使用
Analysis of the reasons why enterprises build their own software development teams to use software manpower outsourcing services at the same time
Mature port AI ceaspectus leads the world in the application of AI in terminals, CIMC Feitong advanced products go global, smart terminals, intelligent ports, intelligent terminals
2022-2028 global plasmid DNA cdmo industry research and trend analysis report
AcWing 271. 杨老师的照相排列【多维DP】
A. Odd Selection【BruteForce】
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