第100+25步 ChatGPT学习:概率校准 Histogram Binning

基于Python 3.9版本演示

一、写在前面

最近看了一篇在Lancet子刊《eClinicalMedicine》上发表的机器学习分类的文章:《Development of a novel dementia risk prediction model in the general population: A large, longitudinal, population-based machine-learning study》。

学到一种叫做“概率校准”的骚操作,顺手利用GPT系统学习学习。

文章中用的技术是:保序回归(Isotonic regression)。

为了体现举一反三,顺便问了GPT还有哪些方法也可以实现概率校准。它给我列举了很多,那么就一个一个学习吧。

这一期,介绍一个叫做 Histogram Binning 的方法。

二、Histogram Binning

Histogram Binning(直方图分箱)是一种用于数据预处理和特征工程的技术,它通过将连续变量分成离散的区间来简化数据处理和分析。基本思想是将连续变量划分成若干个区间(bin),每个区间包含一定范围内的数据点。数据点被分配到相应的区间中,通常每个区间用一个代表值(如区间的中位数或均值)来表示。

(1)作用和优势

1)处理连续变量:许多机器学习算法(如决策树、逻辑回归等)在处理连续变量时效果不佳,分箱可以将连续变量转换为离散变量,从而提高算法性能。

2)减少噪音和异常值影响:连续变量中的噪音和异常值可能会对模型训练产生不利影响。通过分箱,可以平滑数据,减少噪音和异常值的影响。

3)平衡类分布:在处理不平衡数据时,可以通过分箱技术对少数类和多数类的数据进行平衡,增强分类器对少数类的识别能力。

三、Histogram Binning代码实现

下面,我编一个1比3的不太平衡的数据进行测试,对照组使用不进行校准的SVM模型,实验组就是加入校准的SVM模型,看看性能能够提高多少?

(1)不进行校准的SVM模型(默认参数)

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve# 加载数据
dataset = pd.read_csv('8PSMjianmo.csv')
X = dataset.iloc[:, 1:20].values
Y = dataset.iloc[:, 0].values# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=666)# 标准化数据
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)# 使用SVM分类器
classifier = SVC(kernel='linear', probability=True)
classifier.fit(X_train, y_train)# 预测结果
y_pred = classifier.predict(X_test)
y_testprba = classifier.decision_function(X_test)y_trainpred = classifier.predict(X_train)
y_trainprba = classifier.decision_function(X_train)# 混淆矩阵
cm_test = confusion_matrix(y_test, y_pred)
cm_train = confusion_matrix(y_train, y_trainpred)
print(cm_train)
print(cm_test)# 绘制测试集混淆矩阵
classes = list(set(y_test))
classes.sort()
plt.imshow(cm_test, cmap=plt.cm.Blues)
indices = range(len(cm_test))
plt.xticks(indices, classes)
plt.yticks(indices, classes)
plt.colorbar()
plt.xlabel('Predicted')
plt.ylabel('Actual')
for first_index in range(len(cm_test)):for second_index in range(len(cm_test[first_index])):plt.text(first_index, second_index, cm_test[first_index][second_index])plt.show()# 绘制训练集混淆矩阵
classes = list(set(y_train))
classes.sort()
plt.imshow(cm_train, cmap=plt.cm.Blues)
indices = range(len(cm_train))
plt.xticks(indices, classes)
plt.yticks(indices, classes)
plt.colorbar()
plt.xlabel('Predicted')
plt.ylabel('Actual')
for first_index in range(len(cm_train)):for second_index in range(len(cm_train[first_index])):plt.text(first_index, second_index, cm_train[first_index][second_index])plt.show()# 计算并打印性能参数
def calculate_metrics(cm, y_true, y_pred_prob):a = cm[0, 0]b = cm[0, 1]c = cm[1, 0]d = cm[1, 1]acc = (a + d) / (a + b + c + d)error_rate = 1 - accsen = d / (d + c)sep = a / (a + b)precision = d / (b + d)F1 = (2 * precision * sen) / (precision + sen)MCC = (d * a - b * c) / (np.sqrt((d + b) * (d + c) * (a + b) * (a + c)))auc_score = roc_auc_score(y_true, y_pred_prob)metrics = {"Accuracy": acc,"Error Rate": error_rate,"Sensitivity": sen,"Specificity": sep,"Precision": precision,"F1 Score": F1,"MCC": MCC,"AUC": auc_score}return metricsmetrics_test = calculate_metrics(cm_test, y_test, y_testprba)
metrics_train = calculate_metrics(cm_train, y_train, y_trainprba)print("Performance Metrics (Test):")
for key, value in metrics_test.items():print(f"{key}: {value:.4f}")print("\nPerformance Metrics (Train):")
for key, value in metrics_train.items():
print(f"{key}: {value:.4f}")

结果输出:

记住这些个数字。

这个参数的SVM还没有LR好。

(2)进行校准的SVM模型(默认参数)

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve, brier_score_loss
from sklearn.calibration import calibration_curve# 加载数据
dataset = pd.read_csv('8PSMjianmo.csv')
X = dataset.iloc[:, 1:20].values
Y = dataset.iloc[:, 0].values# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=666)# 标准化数据
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)# 使用SVM分类器
classifier = SVC(kernel='rbf', C=0.1, probability=True)
classifier.fit(X_train, y_train)# 获取未校准的概率预测
y_train_probs = classifier.predict_proba(X_train)[:, 1]
y_test_probs = classifier.predict_proba(X_test)[:, 1]# Histogram Binning 校准函数
def histogram_binning(probabilities, y_true, n_bins=10):bin_edges = np.linspace(0, 1, n_bins + 1)bin_indices = np.digitize(probabilities, bin_edges) - 1bin_sums = np.zeros(n_bins)bin_true_sums = np.zeros(n_bins)bin_counts = np.zeros(n_bins)for i in range(n_bins):bin_counts[i] = np.sum(bin_indices == i)if bin_counts[i] > 0:bin_sums[i] = np.sum(probabilities[bin_indices == i])bin_true_sums[i] = np.sum(y_true[bin_indices == i])bin_probs = np.zeros_like(probabilities)for i in range(n_bins):if bin_counts[i] > 0:bin_probs[bin_indices == i] = bin_true_sums[i] / bin_counts[i]return bin_probs# 进行Histogram Binning校准
calibrated_train_probs = histogram_binning(y_train_probs, y_train)
calibrated_test_probs = histogram_binning(y_test_probs, y_test)# 预测结果
y_train_pred = (calibrated_train_probs >= 0.5).astype(int)
y_test_pred = (calibrated_test_probs >= 0.5).astype(int)# 混淆矩阵
cm_test = confusion_matrix(y_test, y_test_pred)
cm_train = confusion_matrix(y_train, y_train_pred)
print(cm_train)
print(cm_test)# 绘制混淆矩阵函数
def plot_confusion_matrix(cm, classes, title='Confusion Matrix'):plt.imshow(cm, cmap=plt.cm.Blues)indices = range(len(cm))plt.xticks(indices, classes)plt.yticks(indices, classes)plt.colorbar()plt.xlabel('Predicted')plt.ylabel('Actual')for first_index in range(len(cm)):for second_index in range(len(cm[first_index])):plt.text(first_index, second_index, cm[first_index][second_index])plt.title(title)plt.show()# 绘制测试集混淆矩阵
plot_confusion_matrix(cm_test, list(set(y_test)), 'Confusion Matrix (Test)')# 绘制训练集混淆矩阵
plot_confusion_matrix(cm_train, list(set(y_train)), 'Confusion Matrix (Train)')# 计算并打印性能参数
def calculate_metrics(cm, y_true, y_pred_prob):a = cm[0, 0]b = cm[0, 1]c = cm[1, 0]d = cm[1, 1]acc = (a + d) / (a + b + c + d)error_rate = 1 - accsen = d / (d + c)sep = a / (a + b)precision = d / (b + d)F1 = (2 * precision * sen) / (precision + sen)MCC = (d * a - b * c) / (np.sqrt((d + b) * (d + c) * (a + b) * (a + c)))auc_score = roc_auc_score(y_true, y_pred_prob)brier_score = brier_score_loss(y_true, y_pred_prob)metrics = {"Accuracy": acc,"Error Rate": error_rate,"Sensitivity": sen,"Specificity": sep,"Precision": precision,"F1 Score": F1,"MCC": MCC,"AUC": auc_score,"Brier Score": brier_score}return metricsmetrics_test = calculate_metrics(cm_test, y_test, calibrated_test_probs)
metrics_train = calculate_metrics(cm_train, y_train, calibrated_train_probs)print("Performance Metrics (Test):")
for key, value in metrics_test.items():print(f"{key}: {value:.4f}")print("\nPerformance Metrics (Train):")
for key, value in metrics_train.items():print(f"{key}: {value:.4f}")

看看结果:

大同小异吧。

四、换个策略

参考那篇文章的策略:采用五折交叉验证来建立和评估模型,其中四折用于训练,一折用于评估,在训练集中,其中三折用于建立SVM模型,另一折采用Histogram Binning概率校正,在训练集内部采用交叉验证对超参数进行调参。

代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV, KFold
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve, brier_score_loss
from sklearn.calibration import calibration_curve# 加载数据
dataset = pd.read_csv('8PSMjianmo.csv')
X = dataset.iloc[:, 1:20].values
Y = dataset.iloc[:, 0].values# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=666)# 标准化数据
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)# 定义五折交叉验证
kf = KFold(n_splits=5, shuffle=True, random_state=666)
calibrated_probs = []
true_labels = []for train_index, test_index in kf.split(X_train):X_train_fold, X_val_fold = X_train[train_index], X_train[test_index]y_train_fold, y_val_fold = y_train[train_index], y_train[test_index]# 内部三折交叉验证用于超参数调优inner_kf = KFold(n_splits=3, shuffle=True, random_state=666)param_grid = {'C': [0.01, 0.1, 1, 10, 100], 'kernel': ['rbf']}svm = SVC(probability=True)clf = GridSearchCV(svm, param_grid, cv=inner_kf, scoring='roc_auc')clf.fit(X_train_fold, y_train_fold)best_params = clf.best_params_# 使用最佳参数训练SVMclassifier = SVC(kernel=best_params['kernel'], C=best_params['C'], probability=True)classifier.fit(X_train_fold, y_train_fold)# 获取未校准的概率预测y_val_fold_probs = classifier.predict_proba(X_val_fold)[:, 1]# Histogram Binning 校准函数def histogram_binning(probabilities, y_true, n_bins=10):bin_edges = np.linspace(0, 1, n_bins + 1)bin_indices = np.digitize(probabilities, bin_edges) - 1bin_sums = np.zeros(n_bins)bin_true_sums = np.zeros(n_bins)bin_counts = np.zeros(n_bins)for i in range(n_bins):bin_counts[i] = np.sum(bin_indices == i)if bin_counts[i] > 0:bin_sums[i] = np.sum(probabilities[bin_indices == i])bin_true_sums[i] = np.sum(y_true[bin_indices == i])bin_probs = np.zeros_like(probabilities)for i in range(n_bins):if bin_counts[i] > 0:bin_probs[bin_indices == i] = bin_true_sums[i] / bin_counts[i]return bin_probs# 进行Histogram Binning校准calibrated_val_fold_probs = histogram_binning(y_val_fold_probs, y_val_fold)calibrated_probs.extend(calibrated_val_fold_probs)true_labels.extend(y_val_fold)# 用于测试集的SVM模型训练和校准
classifier_final = SVC(kernel=best_params['kernel'], C=best_params['C'], probability=True)
classifier_final.fit(X_train, y_train)
y_test_probs = classifier_final.predict_proba(X_test)[:, 1]
calibrated_test_probs = histogram_binning(y_test_probs, y_test)# 预测结果
y_train_pred = (np.array(calibrated_probs) >= 0.5).astype(int)
y_test_pred = (calibrated_test_probs >= 0.5).astype(int)# 混淆矩阵
cm_test = confusion_matrix(y_test, y_test_pred)
cm_train = confusion_matrix(y_train, y_train_pred)
print("Training Confusion Matrix:\n", cm_train)
print("Testing Confusion Matrix:\n", cm_test)# 绘制混淆矩阵函数
def plot_confusion_matrix(cm, classes, title='Confusion Matrix'):plt.imshow(cm, cmap=plt.cm.Blues)indices = range(len(cm))plt.xticks(indices, classes)plt.yticks(indices, classes)plt.colorbar()plt.xlabel('Predicted')plt.ylabel('Actual')for first_index in range(len(cm)):for second_index in range(len(cm[first_index])):plt.text(first_index, second_index, cm[first_index][second_index])plt.title(title)plt.show()# 绘制测试集混淆矩阵
plot_confusion_matrix(cm_test, list(set(y_test)), 'Confusion Matrix (Test)')# 绘制训练集混淆矩阵
plot_confusion_matrix(cm_train, list(set(y_train)), 'Confusion Matrix (Train)')# 计算并打印性能参数
def calculate_metrics(cm, y_true, y_pred_prob):a = cm[0, 0]b = cm[0, 1]c = cm[1, 0]d = cm[1, 1]acc = (a + d) / (a + b + c + d)error_rate = 1 - accsen = d / (d + c)sep = a / (a + b)precision = d / (b + d)F1 = (2 * precision * sen) / (precision + sen)MCC = (d * a - b * c) / (np.sqrt((d + b) * (d + c) * (a + b) * (a + c)))auc_score = roc_auc_score(y_true, y_pred_prob)brier_score = brier_score_loss(y_true, y_pred_prob)metrics = {"Accuracy": acc,"Error Rate": error_rate,"Sensitivity": sen,"Specificity": sep,"Precision": precision,"F1 Score": F1,"MCC": MCC,"AUC": auc_score,"Brier Score": brier_score}return metricsmetrics_test = calculate_metrics(cm_test, y_test, calibrated_test_probs)
metrics_train = calculate_metrics(cm_train, y_train, np.array(calibrated_probs))print("Performance Metrics (Test):")
for key, value in metrics_test.items():print(f"{key}: {value:.4f}")print("\nPerformance Metrics (Train):")
for key, value in metrics_train.items():print(f"{key}: {value:.4f}")# 绘制校准曲线
def plot_calibration_curve(y_true, probs, title='Calibration Curve'):fraction_of_positives, mean_predicted_value = calibration_curve(y_true, probs, n_bins=10)plt.plot(mean_predicted_value, fraction_of_positives, "s-", label="Histogram Binning")plt.plot([0, 1], [0, 1], "k--")plt.xlabel('Mean predicted value')plt.ylabel('Fraction of positives')plt.title(title)plt.legend()plt.show()# 绘制校准曲线
plot_calibration_curve(y_test, calibrated_test_probs, title='Calibration Curve (Test)')
plot_calibration_curve(y_train, np.array(calibrated_probs), title='Calibration Curve (Train)')

输出:

哈哈哈,撤了撤了。

五、最后

各位可以去试一试在其他数据或者在其他机器学习分类模型中使用的效果。

数据不分享啦。

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

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

相关文章

ATT&CK靶机实战系列之vulnstack2

声明: 本文章只是用于网络安全交流与学习,若学者用学到的东西做一些与网络安全不相关的事情,结果均与本人无关!!! 靶场环境: 使用kali作为hacker的攻击机器,来对web pc dc进行攻击。 这里声明一下: 关于…

三、jsp与Listener监听器

文章目录 1. 什么是 jsp,它有什么用?2. jsp 的本质是什么3. jsp 的三种语法3.1 jsp 头部的 page 指令3.2 jsp 中的常用脚本3.3 jsp 中的三种注释 4. jsp 九大内置对象5. jsp 四大域对象6. jsp 中的 out 输出和 response.getWriter 输出的区别7. jsp 的常用标签7.1 …

Linux shell编程学习笔记81:zcat命令——快速查看压缩文件内容

0 引言 在 Linux shell编程学习笔记80:gzip命令——让文件瘦身-CSDN博客https://blog.csdn.net/Purpleendurer/article/details/141862213?spm1001.2014.3001.5501中,我们使用gzip命令可以创建压缩文件。那么,我们可以使用zcat命令来查看压…

软考(中级-软件设计师)(0919)

软考 一、软件设计师-历年考试考点分布情况-上午-计算机与软件工程知识 知识点分数说明比例软件工程基础知识11开发模型、设计原则、测试方法、质量特性、CMM、Pert图、风险管理14.67%面向对象12面向对象基本概念、面向对象分析与设计、UML、常见算法16.00%数据结构与算法10…

SPI软件模拟读写W25Q64

1.SPI初始化 #include "stm32f10x.h" // Device headervoid MySPI_W_SS(uint8_t BitValue)//片选 {GPIO_WriteBit(GPIOA,GPIO_Pin_4,(BitAction)BitValue); }void MySPI_W_SCK(uint8_t BitValue)//时钟线 {GPIO_WriteBit(GPIOA,GPIO_Pin_5,(BitAct…

LabVIEW提高开发效率技巧----使用事件结构优化用户界面响应

事件结构(Event Structure) 是 LabVIEW 中用于处理用户界面事件的强大工具。通过事件驱动的编程方式,程序可以在用户操作时动态执行特定代码,而不是通过轮询(Polling)的方式不断检查界面控件状态。这种方式…

鸿蒙 ArkUI组件三

ArkUI组件(续) QRCode组件 用于显示单个二维码的组件。 说明 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。二维码组件的像素点数量与内容有关,当组件尺寸过小时,可能…

Kettle的实战练习指南:从数据导入到ETL自动化

在数据集成和数据仓库建设中,Kettle作为一个强大的开源ETL工具,提供了灵活的数据抽取、转换和加载功能。本文将通过实战案例,详细介绍Kettle在数据导入、ETL流程设计、自动化任务调度等方面的应用。 一、数据导入 1. SQL语句导入 导入sql语…

(11)(2.1.2) DShot ESCs(二)

文章目录 前言 3 配置伺服功能 4 检查RC横幅 5 参数说明 前言 DShot 是一种数字 ESC 协议,它允许快速、高分辨率的数字通信,可以改善飞行器控制,这在多旋翼和 quadplane 应用中特别有用。 3 配置伺服功能 如上所述,如果使用…

数据结构-3.链表

前言 本篇博客给大家带来的是链表的知识点, 其中包括面试经常会提问的真题 ArrayList 和 LinkedList 的区别 . 文章专栏: Java-数据结构 若有问题 评论区见 欢迎大家点赞 评论 收藏 分享 如果你不知道分享给谁,那就分享给薯条, 如果分享不成功, 那我就会回你一下,那样你就分享成…

c++与cmake:完整的C++项目构建注意事项

个人博客:Sekyoro的博客小屋 个人网站:Proanimer的个人网站 最近常常使用cmake构建c项目有感,从创建项目到打包发布总结一下需要注意的事情. 项目组织方式 具体的项目组织方式因人而异,这里推荐一种,在src目录中创建模块目录,再在include目录中常见对应的同名目录包含头文件,…

阿里巴巴API助力电商:商品详情获取与数据驱动的完美结合

阿里巴巴API在电商领域的应用,特别是在商品详情获取与数据驱动的决策过程中,发挥着至关重要的作用。以下是对这一主题的详细阐述: 一、阿里巴巴API在商品详情获取中的应用 丰富的数据支持: 阿里巴巴提供的商品详情API&#xff0…

html详细知识

1-标题标签、水平线、字体标签 <!--1.标题标签1&#xff09;格式&#xff1a;<hn></hn> n的范围是1-6&#xff0c;依次递减2&#xff09;标题标签特点&#xff1a;a:单独占一行b:自动加粗2.水平线1&#xff09;格式&#xff1a;<hr/>2)属性&#xff1a;…

深度学习对抗海洋赤潮危机!浙大GIS实验室提出ChloroFormer模型,可提前预警海洋藻类爆发

2014 年 8 月&#xff0c;美国俄亥俄州托莱多市超 50 万名居民突然收到市政府的一则紧急通知——不得擅自饮用自来水&#xff01; 水是人类生存的基本供给&#xff0c;此通告关系重大&#xff0c;发出后也引起了不小的恐慌。究其原因&#xff0c;其实是美国伊利湖爆发了大规模…

如何使用ssm实现在线视频网站开发

TOC ssm631在线视频网站开发jsp 绪论 1.1 选题背景 当人们发现随着生产规模的不断扩大&#xff0c;人为计算方面才是一个巨大的短板&#xff0c;所以发明了各种计算设备&#xff0c;从结绳记事&#xff0c;到算筹&#xff0c;以及算盘&#xff0c;到如今的计算机&#xff0…

关于嵌入式硬件需要了解的基础知识

成长路上不孤单&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a; 【14后&#x1f60a;///C爱好者&#x1f60a;///持续分享所学&#x1f60a;///如有需要欢迎收藏转发///&#x1f60a;】 今日分享关于嵌入式硬件基础知识的相关内容&#xff…

html,css基础知识点笔记(二)

9.18&#xff08;二&#xff09; 本文主要教列表的样式设计 1&#xff09;文本溢出 效果图 文字限制一行显示几个字&#xff0c;多余打点 line-height: 1.8em; white-space: nowrap; width: 40em; overflow: hidden; text-overflow: ellipsis;em表示一个文字的大小单位&…

828华为云征文|云服务器Flexus X实例|Ubunt部署Vue项目

概要 本章将深入阐述Vue项目在Ubuntu环境下&#xff0c;实现在华为云Flexus X云服务器上的部署过程&#xff0c;此次演示以Vue.js项目为核心华为云在已经到来的828 B2B企业节上&#xff0c;为Vue等前端项目的部署与运维提供强有力的支持。 Ubuntu部署Vue项目的影响&#xff1…

VS Code远程连接虚拟机

VS Code远程连接虚拟机 1.下载vscode2.打开VS Code下载Remote-SSH插件1.修改相关信息 3.虚拟机检查或安装ssh4.检查虚拟机服务是否安装成功5.开启ssh&#xff0c;并检查是否开启成功 1.下载vscode 2.打开VS Code下载Remote-SSH插件 1.修改相关信息 2. 3.虚拟机检查或安装ssh…

封装svg图片

前言 项目中有大量svg图片&#xff0c;为了方便引入&#xff0c;所以对svg进行了处理 一、svg是什么&#xff1f; svg是可缩放矢量图形&#xff0c;是一种图片格式 二、使用步骤 1.创建icons文件夹 将icons文件夹放进src中&#xff0c;并创建一个svg文件夹和index.js&…