Logistic回归

本文介绍了线性回归的基本概念,最小二乘法原理,以及使用Python库如NumPy和PyTorch实现线性回归和Logistic回归。特别详细讲解了Logistic回归在处理二分类问题中的应用,包括数据准备、模型构建、损失函数、优化算法和可视化决策边界的过程。
摘要由CSDN通过智能技术生成

第五章  Logistic回归

5.1  线性回归简介

线性回归是指采用线性组合形式的回归模型,在线性回归问题中,因变量和自变量之间是线性关系的。对于第 i 个因变量xi,我们乘以权重系数wi,取y为因变量的线性组合:

y = f(x)=W1X1+·······+WnXn+b(b为常数项)

线性回归是一种用于建立自变量和因变量之间线性关系的统计方法,它通过最小化误差平方和来寻找最佳拟合直线。

线性回归的原理:

1、线性关系假设

2、最小二乘法

3、模型评估

4、误差项

代码
import numpy as np
import matplotlib.pyplot as plt

# plt是常用的绘制图像的库
# 训练集数据
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

# 定义线性模型y=wx
def forward(x):
    return x * w
# 定义损失函数:loss=(y_predect-y)2=(x*w-y)2
def loss(x,y):
    y_data = forward(x)
    return  (y_data - y) ** 2

# 定义w_list、mse_list来保存w和对应mes loss的取值
w_list = []
mse_list = []

# 穷举法计算损失值cost
for w in np.arange(0.0, 4.1, 0.1):
    print("w", w)
    l_sum = 0
    for x_val, y_val in zip(x_data, y_data):   # x, y 拼接为[x, y]
        y_pred_val = forward(x_val)   # 预测
        loss_val = loss(x_val, y_val)  # 求损失Loss
        l_sum += loss_val  # Loss求和
        print('\t', x_val, y_val, y_pred_val, loss_val)
    print('MSE=', l_sum / 3)
    w_list.append(w)
    mse_list.append(l_sum / 3)

# 画图
plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()

结果如图所示:

5.2  Logistic回归简介

Logistic回归是处理分类问题的一种常用机器学习算法,尤其适用于二分类问题,即结果只有两个类别,例如“是”或“否”。它可以估计某个事件发生的概率,比如用户是否会购买商品、病人是否患有某种疾病、广告是否会被点击等。Logistic回归模型的输出是一个介于0和1之间的概率值,这个值表示某个事件(通常是感兴趣的正类)发生的概率。

代码
import torch
import matplotlib.pyplot as plt
import torch.nn.functional as F
import numpy as np


x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]])


class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)
    def forward(self, x):
        y_pred = F.sigmoid(self.linear(x))   # 多了一个sigmid激活函数
        return y_pred

model = LinearModel()


criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)


for epoch in range(1000):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print('epoch:', epoch, 'loss', loss.item())
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()


x = np.linspace(0, 10, 200)
x_t = torch.Tensor(x).view((200, 1))    # 将转换为tensor,变成200行,1列
y_t = model(x_t)
y = y_t.data.numpy()


plt.plot(x, y)
plt.plot([0, 10], [0.5, 0.5], c='r')
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()

结果如图所示:

5.3  用PyTorch实现Logistic回归

5.3.1  数据准备

import torch
from torch import nn
from matplotlib import pyplot as plt
import numpy as np
from torch.distributions import MultivariateNormal

# 设置两组不同的均值向量和协方差矩阵
mu1 = -3 * torch.ones(2)
mu2 = 3 * torch.ones(2)
sigma1 = torch.eye(2) * 0.5
sigma2 = torch.eye(2) * 2

# 各从两个多元高斯分布中生成100个样本
m1 = MultivariateNormal(mu1, sigma1)
m2 = MultivariateNormal(mu2, sigma2)
x1 = m1.sample((100,))
x2 = m2.sample((100,))

# 设置正负样本的标签
y = torch.zeros((200, 1))
y[:100, :] = 1

# 组合、打乱样本
x = torch.cat([x1, x2], dim=0)
idx = np.random.permutation(len(x))
x = x[idx]
y = y[idx]

# 绘制样本
plt.scatter(x1.numpy()[:, 0], x1.numpy()[:, 1])
plt.scatter(x2.numpy()[:, 0], x2.numpy()[:, 1])

plt.show()

结果如图所示:

可以很明显地看出多元高斯分布生成的样本聚成了两个簇,并且簇的中心分别处于不同的位置(多元高斯分布的均值向量决定了其位置)。右上角簇的样本分布比较稀疏,而左下角簇的样本分布紧凑(多元高斯分布的协方差矩阵决定了分布形状)。

5.3.2 

线性方程

激活函数

损失函数

优化算法

模型可视化

完整代码:

import torch
from torch import nn, sigmoid_
from matplotlib import pyplot as plt
from torch import optim
import numpy as np
from torch.distributions import MultivariateNormal


# 设置两组不同的均值向量和协方差矩阵
mu1 = -3 * torch.ones(2)
mu2 = 3 * torch.ones(2)
sigma1 = torch.eye(2) * 0.5
sigma2 = torch.eye(2) * 2

# 各从两个多元高斯分布中生成100个样本
m1 = MultivariateNormal(mu1, sigma1)
m2 = MultivariateNormal(mu2, sigma2)
x1 = m1.sample((100,))
x2 = m2.sample((100,))

# 设置正负样本的标签
y = torch.zeros((200, 1))
y[:100, :] = 1

# 组合、打乱样本
x = torch.cat([x1, x2], dim=0)
idx = np.random.permutation(len(x))
x = x[idx]
y = y[idx]

# 绘制样本
plt.scatter(x1.numpy()[:, 0], x1.numpy()[:, 1])
plt.scatter(x2.numpy()[:, 0], x2.numpy()[:, 1])

D_in, D_out = 2, 1
linear = nn.Linear(D_in, D_out, bias=True)
output = linear(x)

print(x.shape, linear.weight.shape, linear.bias.shape, output.shape)


def my_linear(x, w, b):
    return torch.mm(x, w.t()) + b
torch.sum(output - my_linear(x, linear.weight, linear.bias))

sigmoid = nn.Sigmoid()
scores = sigmoid(output)


def my_sigmoid(x):
    x = 1 / (1 + torch.exp(-x))
    return x
torch.sum(sigmoid(output) - sigmoid_(output))

loss = nn.BCELoss()
loss(sigmoid(output), y)

def my_loss(x, y):
    loss = - torch.mean(torch.log(x) * y + torch.log(1 - x) * (1 - y))
    return loss
loss(sigmoid(output), y) - my_loss(sigmoid_(output), y)

class LogisticRegression(nn.Module):
    def __init__(self, D_in):
        super(LogisticRegression, self).__init__()
        self.linear = nn.Linear(D_in, 1)
        self.sigmoid = nn.Sigmoid()
    def forward(self, x):
        x = self.linear(x)
        output = self.sigmoid(x)
        return output

lr_model = LogisticRegression(2)
loss = nn.BCELoss()
loss(lr_model(x), y)


class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.linear1 = nn.Linear(1, 1, bias=False)
        self.linear2 = nn.Linear(1, 1, bias=False)
    def forward(self):
        pass

for param in MyModel().parameters():
    print(param)

optimizer = optim.SGD(lr_model.parameters(), lr=0.03)

batch_size = 10
iters = 10
#for input, target in dataset:
for _ in range(iters):
    for i in range(int(len(x) / batch_size)):
        input = x[i * batch_size: (i + 1) * batch_size]
        target = y[i * batch_size: (i + 1) * batch_size]
        optimizer.zero_grad()
        output = lr_model(input)
        l = loss(output, target)
        l.backward()
        optimizer.step()
output=lr_model(x)
pred_neg = (output <= 0.5).view(-1)
pred_pos = (output > 0.5).view(-1)
plt.scatter(x[pred_neg, 0], x[pred_neg, 1])
plt.scatter(x[pred_pos, 0], x[pred_pos, 1])

print("pred_neg shape:", pred_neg.shape)
print("x shape:", x.shape)


w = lr_model.linear.weight[0]
b = lr_model.linear.bias[0]

def draw_decision_boundary(w, b, x0):
    x1 = (-b-w[0]*x0)/ w[1]
    plt.plot(x0.detach().numpy(),x1.detach().numpy(), 'r')
draw_decision_boundary(w, b, torch.linspace(x.min(), x.max(), 50))

plt.show()


Logistic 回归模型的判决边界在高维空间是一个超平面,而我们的数据集是二维的,所以判决边界只是平面内的一条直线,在线的一侧被预测为正类,另一侧则被预测为负类。

结果如图所示:

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值