sklearn实现非线性逻辑回归

sklearn实现非线性逻辑回归

前言: 上一篇博文,我使用python实现了非线性逻辑回归的梯度下降算法进行分类,看上去比较复杂,这篇博文将利用sklearn包进行非线性逻辑回归的实现,非线性实现的思想也是通处理样本数据将非线性转为线性,具体思路看我的这篇博文

一、sklearn实现非线性逻辑回归Demo

import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.metrics import classification_report
from sklearn.datasets import make_gaussian_quantiles
from sklearn.preprocessing import PolynomialFeatures

# 生成2维正态分布,生成的数据按分位数分为两类,500个样本,2个样本特征
# 可以生成两类或者多类数据
x_data, y_data = make_gaussian_quantiles(n_samples=500, n_features=2, n_classes=2)

# 定义多项式回归,degree的值可以调节多项式的特征
poly_reg = PolynomialFeatures(degree=3)  # 得到非线性方程y = theta0+theta1*x1+theta2*x1^2+theta3*x1*x2+theta4*x^2所需的样本数据
# 特征处理(获取多项式相应特征所对应的样本数据)
x_poly = poly_reg.fit_transform(x_data)

# 训练模型
model = linear_model.LogisticRegression()
model.fit(x_poly, y_data)

# 获取数据值所在的范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1

# 生成网格矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
# 测试点的预测值
z = model.predict(poly_reg.fit_transform(np.c_[xx.ravel(), yy.ravel()]))
for i in range(len(z)):
    if z[i] > 0.5:
        z[i] = 1
    else:
        z[i] = 0

z = z.reshape(xx.shape)
# 绘制等高线图
cs = plt.contourf(xx, yy, z)
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)

# 计算准确率,召回率,F1值
print(classification_report(y_data, model.predict(x_poly)))
print('score:', model.score(x_poly, y_data))
plt.show()

二、执行结果

                  precision    recall  f1-score   support

	           		0       0.97      0.99      0.98       250
           			1       0.99      0.97      0.98       250

   micro avg       0.98      0.98      0.98       500
   macro avg       0.98      0.98      0.98       500
weighted avg       0.98      0.98      0.98       500

在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mekeater

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

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

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

打赏作者

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

抵扣说明:

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

余额充值