python sklearn 逻辑回归分类

二分类问题

"""
    解决分类问题:
    使用逻辑回归的方式
"""
import numpy as np
import matplotlib.pyplot as mp
import sklearn.linear_model as lm

# 1.准备数据
x = np.array([
    [3, 1],
    [2, 5],
    [1, 8],
    [6, 4],
    [5, 2],
    [3, 5],
    [4, 7],
    [4, -1]])
y = np.array([0, 1, 1, 0, 0, 1, 1, 0])

# 2.构建逻辑回归模型
model = lm.LogisticRegression(solver="liblinear", C=1)
model.fit(x, y)
result = model.predict([[3, 9], [6, 1]])
print(result)

# 3.预测并准备 分类区域数据
# 绘制分类边界线
left, right = x[:, 0].min() - 1, x[:, 0].max() + 1
bottom, top = x[:, 1].min() - 1, x[:, 1].max() + 1
# 可视区域 划分维 500*500的区域
n = 500
grid_x, grid_y = np.meshgrid(np.linspace(left, right, n), np.linspace(bottom, top, n))
mesh_x = np.column_stack((grid_x.ravel(), grid_y.ravel()))
mesh_z = model.predict(mesh_x)
grid_z = mesh_z.reshape(grid_x.shape)

# 4.绘图 分类区域图
mp.figure("LR classification", facecolor="lightgray")
mp.title("LR classification", fontsize=16)
mp.scatter(x[:, 0], x[:, 1], c=y,
           cmap="jet", label="sample points", s=70, zorder=3)  # 绘制散点
mp.grid(linestyle=":")
mp.legend()
mp.pcolormesh(grid_x, grid_y, grid_z, cmap="gray")  # 绘制分类区域
mp.tight_layout()
mp.show()

在这里插入图片描述

多分类问题

"""
    解决分类问题:
    使用逻辑回归的解决多分类的问题
"""
import numpy as np
import matplotlib.pyplot as mp
import sklearn.linear_model as lm

# 1.准备数据
x = np.array([
    [4, 7],
    [3.5, 8],
    [3.1, 6.2],
    [0.5, 1],
    [1, 2],
    [1.2, 1.9],
    [6, 2],
    [5.7, 1.5],
    [5.4, 2.2]])
y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])

# 2.构建逻辑回归模型
model = lm.LogisticRegression(solver="liblinear", C=100, multi_class="auto")
model.fit(x, y)
result = model.predict([[3, 9], [6, 1]])
print(result)

# 3.预测并准备 分类区域数据
# 绘制分类边界线
left, right = x[:, 0].min() - 1, x[:, 0].max() + 1
bottom, top = x[:, 1].min() - 1, x[:, 1].max() + 1
# 可视区域 划分维 500*500的区域
n = 500
grid_x, grid_y = np.meshgrid(np.linspace(left, right, n), np.linspace(bottom, top, n))
mesh_x = np.column_stack((grid_x.ravel(), grid_y.ravel()))
mesh_z = model.predict(mesh_x)
grid_z = mesh_z.reshape(grid_x.shape)

# 4.绘图 分类区域图
mp.figure("LR classification", facecolor="lightgray")
mp.title("LR classification", fontsize=16)
mp.scatter(x[:, 0], x[:, 1], c=y, cmap="jet", label="sample points", s=70, zorder=3)
mp.grid(linestyle=":")
mp.legend()
mp.pcolormesh(grid_x, grid_y, grid_z, cmap="gray")
mp.tight_layout()
mp.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

廷益--飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值