分类模型决策边界、过拟合、评价指标、PR、ROC曲线

news2025/2/25 12:28:19

文章目录

  • 1、线性逻辑回归决策边界
    • 1.2、使用自定义函数绘制决策边界
    • 1.3、三分类的决策边界
    • 1.4、多项式逻辑回归决策边界
  • 2、过拟合和欠拟合
    • 2.2、欠拟合
    • 2.3、过拟合
  • 3、学习曲线
  • 4、交叉验证
  • 5、泛化能力
  • 6、混淆矩阵
  • 7、PR曲线和ROC曲线

x2可以用x1来表示
在这里插入图片描述

1、线性逻辑回归决策边界

# 逻辑回归
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
x,y = make_classification(
    n_samples=200,# 样本数
    n_features=2,# 特征数
    n_redundant=0,# 冗余特指数
    n_classes=2,# 类型
    n_clusters_per_class=1,# 族设为1
    random_state=1024
)
x.shape,y.shape

x_train,x_test,y_train,y_test = train_test_split(x,y,train_size=0.7,random_state=1024,stratify=y)
plt.scatter(x_train[:,0],x_train[:,1],c=y_train)

from sklearn.linear_model import LogisticRegression
clf = LogisticRegression()
clf.fit(x_train,y_train)
clf.score(x_test,y_test)
# clf.predict(x_test)

x1 = np.linspace(-4,4,1000)
x2 = (-clf.coef_[0][0] * x1 -clf.intercept_)/clf.coef_[0][1]
plt.scatter(x_train[:,0],x_train[:,1],c=y_train)
plt.scatter(x1,x2)
plt.show()

在这里插入图片描述

1.2、使用自定义函数绘制决策边界

很多时候不只是画一条线

def decision_boundary_plot(X, y, clf):
    axis_x1_min, axis_x1_max = X[:,0].min() - 1, X[:,0].max() + 1
    axis_x2_min, axis_x2_max = X[:,1].min() - 1, X[:,1].max() + 1
    
    x1, x2 = np.meshgrid( np.arange(axis_x1_min,axis_x1_max, 0.01) , np.arange(axis_x2_min,axis_x2_max, 0.01))
    z = clf.predict(np.c_[x1.ravel(),x2.ravel()])
    z = z.reshape(x1.shape)
    
    from matplotlib.colors import ListedColormap
    custom_cmap = ListedColormap(['#F5B9EF','#BBFFBB','#F9F9CB'])

    plt.contourf(x1, x2, z, cmap=custom_cmap)
    plt.scatter(X[:,0], X[:,1], c=y)
    plt.show()


decision_boundary_plot(x, y ,clf)

在这里插入图片描述

1.3、三分类的决策边界

from sklearn import datasets
iris = datasets.load_iris()
x = iris.data[:,:2]
y = iris.target
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=666)
plt.scatter(x_train[:,0], x_train[:,1], c = y_train)
plt.show()

clf.score(x_test, y_test)
decision_boundary_plot(x, y, clf)

在这里插入图片描述

1.4、多项式逻辑回归决策边界

np.random.seed(0)
x = np.random.normal(0, 1, size=(200, 2))
y = np.array((x[:,0]**2+x[:,1]**2)<2, dtype='int')
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size = 0.7, random_state = 233, stratify = y)
plt.scatter(x_train[:,0], x_train[:,1], c = y_train)
plt.show()


from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScaler
clf_pipe = Pipeline([
        ('poly', PolynomialFeatures(degree=2)),
        ('std_scaler', StandardScaler()),
        ('log_reg', LogisticRegression())
    ])

clf_pipe.fit(x_train, y_train)
decision_boundary_plot(x, y, clf_pipe)

在这里插入图片描述

2、过拟合和欠拟合

2.2、欠拟合

在这里插入图片描述
特征维度不足,模型复杂度角度,无法学习到数据背后的规律,使用一元线性回归拟合抛物线数据自然会导致欠拟合

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(233)
x = np.random.uniform(-4, 2, size = (100))
y = x ** 2 + 4 * x + 3 + 2 * np.random.randn(100)

X = x.reshape(-1, 1)

plt.scatter(x,y)
plt.show()

from sklearn.linear_model import LinearRegression
linear_regression = LinearRegression()
linear_regression.fit(X, y)
y_predict = linear_regression.predict(X)
plt.scatter(x, y)
plt.plot(x, y_predict, color = 'red')
plt.show()

2.3、过拟合

在这里插入图片描述

from sklearn.preprocessing import PolynomialFeatures
polynomial_features = PolynomialFeatures(degree=2)
X_poly = polynomial_features.fit_transform(X)
linear_regression = LinearRegression()
linear_regression.fit(X_poly,y)
y_predict = linear_regression.predict(X_poly)
plt.scatter(x,y,s=10)
plt.plot(np.sort(x),y_predict[np.argsort(x)],color='red')
plt.show()

# 另外一种方式
X_new = np.linspace(-5,3,200).reshape(-1,1)
X_new_poly = polynomial_features.fit_transform(X_new)
y_predict = linear_regression.predict(X_new_poly)
plt.scatter(x,y,s=10)
plt.plot(X_new,y_predict,color='red')
plt.show()
print("degree:",2,"score:",linear_regression.score(X_poly,y))

在这里插入图片描述
下面三种情况,曲线越来越复杂,与我们的数据相差很远,如果划分了训练集测试机,往往就会在训练集上效果很好,在测试集上效果很差,通俗来讲就是死记了所有习题,但是一考试分数就很低,泛化能力太差。

plt.rcParams["figure.figsize"] = (10, 6)

degrees = [2, 5, 10, 15, 20, 24]
for i, degree in enumerate(degrees):
    polynomial_features = PolynomialFeatures(degree = degree)
    X_poly = polynomial_features.fit_transform(X)
    
    linear_regression = LinearRegression()
    linear_regression.fit(X_poly, y)
    
    X_new = np.linspace(-5, 3, 200).reshape(-1, 1)
    X_new_poly = polynomial_features.fit_transform(X_new)
    y_predict = linear_regression.predict(X_new_poly)
    
    plt.subplot(2, 3, i + 1)
    plt.title("Degree: {0}".format(degree))
    plt.scatter(x, y, s = 10)
    plt.ylim(-5, 25)
    plt.plot(X_new, y_predict, color = 'red')
    
    print("Degree:", degree, "Score:", linear_regression.score(X_poly, y))
    
plt.show()

3、学习曲线

在这里插入图片描述
从曲线图可以看出来,degree为1的时候误差值比较大,明显是欠拟合状态,为2的时候效果比较好,为5,20的时候明显过拟合状态,训练误差比较小,但是测试误差很大。
在这里插入图片描述

from sklearn.metrics import mean_squared_error

plt.rcParams["figure.figsize"] = (12, 8)

degrees = [1, 2, 5, 20]
for i, degree in enumerate(degrees):
    polynomial_features = PolynomialFeatures(degree = degree)
    
    X_poly_train = polynomial_features.fit_transform(x_train.reshape(-1, 1))
    X_poly_test = polynomial_features.fit_transform(x_test.reshape(-1, 1))
    
    train_error, test_error = [], []
    for k in range(len(x_train)):
        linear_regression = LinearRegression()
        linear_regression.fit(X_poly_train[:k + 1], y_train[:k + 1])

        y_train_pred = linear_regression.predict(X_poly_train[:k + 1])
        train_error.append(mean_squared_error(y_train[:k + 1], y_train_pred))

        y_test_pred = linear_regression.predict(X_poly_test)
        test_error.append(mean_squared_error(y_test, y_test_pred))
    
    plt.subplot(2, 2, i + 1)
    plt.title("Degree: {0}".format(degree))
    plt.ylim(-5, 50)
    plt.plot([k + 1 for k in range(len(x_train))], train_error, color = "red", label = 'train')
    plt.plot([k + 1 for k in range(len(x_train))], test_error, color = "blue", label = 'test')
    plt.legend()

plt.show()

4、交叉验证

有没有一种可能就是,模型正好在测试数据集上跑的效果正常,而真实情况是过拟合的,只是没有跑出来,这样的情况下准确性和学习曲线上看似良好,一跑真实数据效果就很差。
解决方法:
多抽几组数据来验证,比如:训练集比作练习题,验证机比作模拟测试,测试机比作考试题。

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris

iris = load_iris()
x = iris.data
y = iris.target

x_train, x_test, y_train, y_test = train_test_split(x, y, train_size = 0.7, random_state = 233, stratify = y)
x_train.shape, x_test.shape, y_train.shape, y_test.shape

from sklearn.model_selection import cross_val_score

neigh = KNeighborsClassifier()
cv_scores = cross_val_score(neigh, x_train, y_train, cv = 5)
print(cv_scores)

best_score = -1
best_n = -1
best_weight = ''
best_p = -1
best_cv_scores = None
for n in range(1, 20):
    for weight in ['uniform', 'distance']:
        for p in range(1, 7):
            neigh = KNeighborsClassifier(
                n_neighbors = n,
                weights = weight,
                p = p
            )
            cv_scores = cross_val_score(neigh, x_train, y_train, cv = 5)
            score = np.mean(cv_scores)
            if score > best_score:
                best_score = score
                best_n = n
                best_weight = weight
                best_p = p
                best_cv_scores = cv_scores

print("n_neighbors:", best_n)
print("weights:", best_weight)
print("p:", best_p)
print("score:", best_score)
print("best_cv_scores:", best_cv_scores)

5、泛化能力

机器学习算法对新鲜事物样本的适应能力,奥卡姆剃刀法则:能简单别复杂,泛化理论:衡量模型复杂度
在这里插入图片描述
在这里插入图片描述

6、混淆矩阵

TP:被模型预测为正类的正样本
TN:被模型预测为负类的负样本
FP:被模型预测为正类的负样本
FN:被模型预测为负类的正样本
在这里插入图片描述
TP:被模型预测为好瓜的好瓜(是真正的好瓜,而且也被模型预测为好瓜)
TN:被模型预测为坏瓜的坏瓜(是真正的坏瓜,而且也被模型预测为坏瓜)
FP:被模型预测为好瓜的坏瓜(瓜是真正的坏瓜,但是被模型预测为了好瓜)
FN:被模型预测为坏瓜的好瓜(瓜是真正的好瓜,但是被模型预测为了坏瓜)

查准率、查全率代表的含义
查准率:模型挑出来的西瓜中有多少比例是好瓜
查全率:所有的好瓜中有多少比例是被模型挑出来的
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
F1 Score
在这里插入图片描述

iris = datasets.load_iris()
X = iris.data
y = iris.target.copy()

# 变成二分类
y[y!=0] = 1

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=666)

logistic_regression = LogisticRegression()
logistic_regression.fit(X_train,y_train)
y_predict = logistic_regression.predict(X_test)

TN = np.sum((y_predict==0)&(y_test==0))
TN

FP = np.sum((y_predict==1)&(y_test==0))
FP

FN = np.sum((y_predict==0)&(y_test==1))
FN

TP = np.sum((y_predict==1)&(y_test==1))
TP

confusion_matrix = np.array([
    [TN, FP],
    [FN, TP]
])

confusion_matrix

precision = TP/ (TP+FP)
precision

recall = TP/(FN+TP)
recall

f1_score = 2*precision*recall /(precision+recall)
f1_score

from sklearn.metrics import confusion_matrix
confusion_matrix(y_test,y_predict)

from sklearn.metrics import precision_score
precision_score(y_test,y_predict)

from sklearn.metrics import recall_score
recall_score(y_test,y_predict)

from sklearn.metrics import f1_score
f1_score(y_test,y_predict)

7、PR曲线和ROC曲线

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris()
X = iris.data
y = iris.target.copy()

# 转化为二分类问题
y[y!=0] = 1

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=666)

logistic_regression = LogisticRegression()
logistic_regression.fit(X_train,y_train)
y_predict = logistic_regression.predict(X_test)
y_predict

decision_scores = logistic_regression.decision_function(X_test)
decision_scores

from sklearn.metrics import precision_score
from sklearn.metrics import recall_score

precision_scores = []
recall_scores = []
thresholds = np.sort(decision_scores)
for threshold in thresholds:
    y_predict = np.array(decision_scores>=threshold,dtype='int')
    precision = precision_score(y_test,y_predict)
    recall = recall_score(y_test,y_predict)
    precision_scores.append(precision)
    recall_scores.append(recall) 
    
plt.plot(thresholds, precision_scores, color='r',label="precision")
plt.plot(thresholds, recall_scores, color='b',label="recall")
plt.legend()
plt.show()

plt.plot(recall_scores,precision_scores)
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.show()

sklearn中实现

# sklearn中
from sklearn.metrics import precision_recall_curve

precision_scores, recall_scores,thresholds =  precision_recall_curve(y_test,decision_scores)

plt.plot(thresholds, precision_scores[:-1], color='r',label="precision")
plt.plot(thresholds, recall_scores[:-1], color='b',label="recall")
plt.legend()
plt.show()

plt.plot(recall_scores,precision_scores)
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.show()


# ROC曲线
from sklearn.metrics import roc_curve

fpr, tpr, thresholds = roc_curve(y_test,decision_scores)
plt.plot(fpr,tpr)
plt.xlabel("FPR")
plt.ylabel("TPR")
plt.show()

# AUC
from sklearn.metrics import roc_auc_score

auc = roc_auc_score(y_test,decision_scores)
auc

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1585723.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【找工作最强助手】全平台自动投简历脚本:(boss、前程无忧、猎聘、拉勾、智联招聘)

get-jobs【工作无忧】 &#x1f4bc;自动投简历(Boss直聘、猎聘、拉勾、51job、智联招聘) 项目链接&#xff1a;https://github.com/loks666/get_jobs最新文档以上面的链接为主 特色功能 支持国内全部招聘平台(Boss直聘、猎聘、拉勾、51job、智联招聘)内置driver驱动&#xf…

各种拟合算法整理

各种拟合算法整理 1. 最小二乘法2. 霍夫变换3. RANSAC算法 本篇将介绍最小二乘法(Least Square)、霍夫变换(Hough Transform)和RANSAC(random sample consensus&#xff0c;随机抽样一致性算法)算法的原理、应用和代码。 如果已经知道了一组可靠的点&#xff0c;可以直接使用最…

数据绑定多级对象属性时的报错解决

数据绑定多级对象属性时的报错解决 &#xff08;1&#xff09;例子如下&#xff1a; &#xff08;2&#xff09;当syncObjForm被后台数据赋值时&#xff0c;会产生报错&#xff1a; &#xff08;3&#xff09;原因就是&#xff1a; 模板在渲染时&#xff0c;读取对象中的某个…

Apache SeaTunnel 社区 3 月月报

各位热爱 SeaTunnel 的小伙伴们&#xff0c;SeaTunnel 社区 3 月月报来啦&#xff01;这里将记录 SeaTunnel 社区每个月的重要更新&#xff0c;并评选出月度之星&#xff0c;欢迎关注。 SeaTunnel 月度 Merge Stars 感谢以下小伙伴 3 月为 Apache SeaTunnel 做的精彩贡献&…

家用洗地机哪个型号推荐?盘点四款最高性价比机型

在当今快节奏的生活中&#xff0c;有娃家庭的地面打扫已经成为日常的卫生保洁&#xff0c;对于许多家庭来说&#xff0c;洗地机成为了必备的助手。然而&#xff0c;面对市场上琳琅满目的洗地机品牌和型号&#xff0c;我们通常为选择哪款好&#xff1f;哪款性价比高而犯难。因为…

Linux系统本地搭建DbGate数据库并结合内网穿透实现无公网IP远程连接

文章目录 1. 安装Docker2. 使用Docker拉取DbGate镜像3. 创建并启动DbGate容器4. 本地连接测试5. 公网远程访问本地DbGate容器5.1 内网穿透工具安装5.2 创建远程连接公网地址5.3 使用固定公网地址远程访问 本文主要介绍如何在Linux Ubuntu系统中使用Docker部署DbGate数据库管理工…

Python使用requests+excel进行接口自动化测试!

在当今的互联网时代中&#xff0c;接口自动化测试越来越成为软件测试的重要组成部分。Python是一种简单易学&#xff0c;高效且可扩展的语言&#xff0c;自然而然地成为了开发人员的首选开发语言。而requests和xlwt这两个常用的Python标准库&#xff0c;能够帮助我们轻松地开发…

Java基础入门--第十二章--多线程

多线程 12.1 进程与进程12.1.1 进程12.1.2 线程 12.2 线程的创建12.2.1 继承Thread类创建多线程12.2.2 实现Runnable接口创建多线程12.2.3 实现Callable接口创建多线程12.2.4 Thread类与Runnable接口实现多线程的对比12.2.5 后台线程 12.3 线程的生命周期及状态转换12.4 线程操…

谷歌浏览器网页自动刷新插件

谷歌浏览器网页自动刷新插件下载&#xff1a;https://www.123pan.com/s/f43eVv-CO7Kd.html 效果图&#xff08;win和mac系统同样操作&#xff09; 1.打开谷歌浏览器&#xff0c;点击头像旁边的三点&#xff0c;点击扩展程序&#xff0c;点击管理扩展程序。 2.打开开发者模式&a…

用 ElementPlus 的日历组件 Calendar 自定义渲染

文章目录 需求分析1. 英文改为中文2. 修改样式3. 自定义头部4. 增删改功能接入 需求 使用 ElementPlus中的 Calendar 组件完成自定义渲染 分析 1. 英文改为中文 转为中文的方式&#xff1a;用 ElementPlus的日历组件如何改为中文 2. 修改样式 附源码 <template><…

【YOLOv8】Yolov5和Yolov8网络结构的分析与对比

目录 一 YOLOv5 二 YOLOv8 yolo通常采用backbone-neck-head的网络结构。 Backbone 主要负责从输入图像中提取高层次的语义特征,常包含多个卷积层和池化层&#xff0c;构建了一个深层次的特征提取器。Neck通常用来进一步整合与调整backbone提取的特征&#xff0c;有利于将不同…

内容创作策略:打造影响力强大的技术博客

CSDN的朋友你们好&#xff0c;我是未来&#xff0c;今天给大家带来专栏【程序员博主教程&#xff08;完全指南&#xff09;】的第6篇文章——“博客内容创作策略”。本文为技术博主提供了一个精简的内容创作策略指南&#xff0c;涵盖了设定目标、分析竞争、关键词研究、内容规划…

PMP与软考的区别看不懂?看懂这五点,小白都知道怎么选!

如果你心怀抱负&#xff0c;不甘心做项目“小透明” 如果你遇到年龄危机&#xff0c;进阶管理无门道&#xff1f; 如果你是技术&#xff0c;管理项目有如盲人摸象&#xff1f;可以考PMP! 如果你准备想攒积分&#xff0c;轻松落户 如果你想评职称&#xff0c;获得专业技术职务 如…

【环境搭建】(五)Ubuntu22.04安装cuda_11.8.0+cudnn_8.6.0

一个愿意伫立在巨人肩膀上的农民...... 设备配置&#xff1a; 一、安装GCC 安装cuda之前&#xff0c;首先应该安装GCC&#xff0c;安装cuda需要用到GCC&#xff0c;否则报错。可以先使用下方指令在终端查看是否已经安装GCC。 gcc --version 如果终端打印如下则说明已经安装…

【浏览器】Google Chrome浏览器打开自动访问网址 gw1.dhwz333.top

目录 [TOC](目录) 问题描述1、查看谷歌浏览器信息2、查看快捷方式属性2、查找注册表3、重装浏览器 解决方案一、使用360系统急救箱进行杀毒步骤1、下载360系统急救箱方式1、直接下载方式2、从360杀毒中打开&#xff0c;需要联网2.1、打开“功能大全”2.2、打开系统急救箱 步骤2…

Fitzgerald:Renin antibody抗体

货号&#xff1a;10-2421 名称&#xff1a;Renin antibody 规格&#xff1a;250ug 产品描述&#xff1a; 别名&#xff1a;Monoclonal Renin antibody, Anti-Renin antibody, FLJ10761 antibody, HNFJ2 antibody, REN antibody, RENI antibody, Renin antibody, renin precu…

第十四篇【传奇开心果系列】Python自动化办公库技术点案例示例:深度解读Python自动化处理图像

传奇开心果博文系列 系列博文目录Python自动化办公库技术点案例示例系列 博文目录前言一、Python自动化图像处理的优点介绍二、Python常用图像处理库和功能介绍三、强大且易于上手示例代码四、丰富的算法资源示例代码五、批量处理图片示例代码六、支持多种图像格式示例代码七、…

【C#】版本号

&#x1f4bb; 代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApp16 {internal class Program{static void Main(string[] args){Version version01 new Version("4.0.0…

SSM整合----第一个SSM项目

文章目录 前言一、使用步骤1.引入库2.建表3 项目结构4 web.xml的配置5 配置数据源6 SpringMVC配置7 配置MyBatis Mapper8 书写控制类 总结 前言 提示&#xff1a;这里可以添加本文要记录的大概内容&#xff1a; SSM整合是指Spring、SpringMVC和MyBatis这三个框架的整合使用。…

数据结构OJ题——栈和队列

1. 用栈实现队列&#xff08;OJ链接&#xff09; 题目描述&#xff1a;请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作&#xff08;push、pop、peek、empty&#xff09; void push(int x) 将元素 x 推到队列的末尾 int pop() 从队列的开头移除并返回…