在Scikit-Learn中创建自定义评分器函数

文章介绍了如何在Scikit-learn中创建和使用自定义评分函数,包括R²、RSS和TSS等统计度量,以及如何为多回归和多分类问题设计评分系统,通过实例展示了如何评估模型性能并使用cross_val_score进行验证。
摘要由CSDN通过智能技术生成

著名的Python机器学习工具包Scikit-learn提供了各种机器学习工具和方法,帮助程序员创建复杂的机器学习模型。Scikit-learn还提供了一个强大的框架,用于使用各种度量和评分函数来评估这些模型的有效性。为了评估其模型的有效性,用户可能希望在特定情况下设计其评分函数。Scikit-learn让这一切成为可能,在本文中,我们将介绍如何设计和调整自己的评分功能。

scikit-learn函数scorer接受两个参数:基础事实(实际值)和模型的预测值。函数返回一个用于评估预期值准确性的分数。Scikit-learn中提供了准确度、精确度、召回率、F1分数和其他预定义的评分函数。为了评估模型的有效性,用户可能希望开发自己独特的评分系统。

多回归问题的自定义评分器

要在sci-kit-learn中创建自定义scorer函数,我们需要遵循以下步骤:

步骤1:创建一个自定义函数来评估准确性

创建一个接受两个参数的Python函数:模型的预测值和基础事实(实际值)。函数应返回一个用于评估预期值准确性的分数。

决定系数(R²)是一种统计度量,代表统计模型预测结果的程度。它测量预测输出中由回归模型中的独立输入变量解释的方差比例。

在这里插入图片描述
RSS =误差平方和,也称为残差平方和(RSS),用于测量回归模型无法解释的变异。 它是预测值和实际目标值之间的平方差之和。

在这里插入图片描述
TSS =总平方和(TSS)表示因变量的总变异。它是因变量的实际值与平均值之间的平方差之和。

在这里插入图片描述

R²的值在0到1之间,值越大表示拟合越好。值为0表示回归线完全不拟合数据,而值为1表示完美拟合。

import numpy as np

def r_squared(y_true, y_pred):
	# Calculate the mean of the true values
	mean_y_true = np.mean(y_true)

	# Calculate the sum of squares of residuals and total sum of squares
	ss_res = np.sum((y_true - y_pred) ** 2)
	ss_tot = np.sum((y_true - mean_y_true) ** 2)

	# Calculate R²
	r2 = 1 - (ss_res / ss_tot)

	return r2

步骤2:创建一个scorer对象

一旦构建了评分函数,必须使用scikit-learn make_scorer()函数创建评分器对象。scoring函数作为参数传递给make_scorer()函数,该函数返回一个scorer对象。

from sklearn.metrics import make_scorer
# Create a scorer object using the r_squared function
r2_score = make_scorer(r2_squared)


步骤3:实现上面定义的scorer对象

创建scorer对象后,我们可以使用scikit-learn或其他模型评估工具提供的不同数据集子集的交叉验证函数来访问机器学习模型的性能。

from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score

# Load the California Housing Price dataset
X, y = fetch_california_housing(return_X_y=True)

# Create a Random Forest regression model
model = RandomForestRegressor()


# Evaluate the performance of the model u
# sing cross-validation with the r2_squared function
scores = cross_val_score(model,
						X, y,
						cv=5, 
						scoring=r2_score)

# Print the mean and standard deviation of the scores
print(f"R2 Squared: {scores.mean():.2f} +/- {scores.std():.2f}")

输出

R2 Squared: 0.65 +/- 0.08

多分类问题的自定义评分器

步骤:

  • 导入必要的库
  • 加载数据集
  • 使用make_scorer定义多个指标,如accuracy_score、precision_score、recall_score、f1_score。
  • 创建XGBClassifier模型
  • 使用交叉验证和自定义评分器评估模型
  • 打印每个指标的平均得分
from sklearn.metrics import make_scorer, accuracy_score
from sklearn.metrics import precision_score, recall_score, f1_score
from sklearn.model_selection import cross_validate
from sklearn.datasets import load_iris
from xgboost import XGBClassifier


# Load the iris dataset
iris = load_iris()

# Define multiple metrics
scoring = {'accuracy': make_scorer(accuracy_score),
		'precision': make_scorer(precision_score, average='macro'),
		'recall': make_scorer(recall_score, average='macro'),
		'f1-score': make_scorer(f1_score, average='macro')
		}

# Create a XGBClassifier
clf = XGBClassifier(n_estimators=2, 
					max_depth=3, 
					learning_rate=0.1)

# Evaluate the model using cross-validation and the custom scorer
scores = cross_validate(clf, iris.data, iris.target, cv=5, scoring=scoring)

# Print the mean scores for each metric
print("Accuracy mean score:", scores['test_accuracy'].mean())
print("Precision mean score:", scores['test_precision'].mean())
print("Recall mean score:", scores['test_recall'].mean())
print("f1-score:", scores['test_f1-score'].mean())

输出

Accuracy mean score: 0.9666666666666668
Precision mean score: 0.9707070707070707
Recall mean score: 0.9666666666666668
f1-score: 0.9664818612187034
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值