KNN算法 - 改善性能

KNN算法 - 改善性能 首页 / 机器学习入门教程 / KNN算法 - 改善性能

无涯教程知道ML模型的参数化方式可以针对特定问题调整其行为,算法调整意味着找到这些参数的最佳组合,从而可以改善ML模型的性能,这个过程有时称为超参数优化,算法本身的参数称为超参数,而ML算法找到的系数称为参数。

网格搜索参数调整

这是一种参数调整方法,该方法关键点针对网格中指定的算法参数的每种可能组合,系统地构建和判断模型。因此,可以说该算法具有搜索性质。

在以下Python中,无涯教程将使用sklearn的GridSearchCV类执行网格搜索,以判断Pima Indians糖尿病数据集上的Ridge回归算法的各种alpha值。

首先,导入所需的软件包,如下所示:

import numpy
from pandas import read_csv
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV

现在,需要像之前的示例一样加载Pima糖尿病数据集-

path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names = headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]

接下来,如下判断各种alpha值;

alphas=numpy.array([1,0.1,0.01,0.001,0.0001,0])
param_grid=dict(alpha=alphas)

现在,无涯教程需要在模型上应用网格搜索-

model=Ridge()
grid=GridSearchCV(estimator=model, param_grid=param_grid)
grid.fit(X, Y)

使用以下脚本行打印输出-

print(grid.best_score_)
print(grid.best_estimator_.alpha)

输出

链接:https://www.learnfk.comhttps://www.learnfk.com/python-machine-learning/machine-learning-with-python-improving-performance-of-ml-model.html

来源:LearnFk无涯教程网

0.2796175593129722
1.0

上面的输出提供了最佳分数以及网格中达到该分数的参数集。在这种情况下,alpha值为1.0。

随机搜索参数调整

这是一种参数调整方法。该方法工作的关键是从固定分布的迭代次数的随机分布中采样算法参数。

无涯教程网

在以下Python配方中,将使用sklearn的RandomizedSearchCV类执行随机搜索,以判断Pima Indians糖尿病数据集上的Ridge回归算法在0到1之间的不同alpha值。

首先,导入所需的软件包,如下所示:

import numpy
from pandas import read_csv
from scipy.stats import uniform
from sklearn.linear_model import Ridge
from sklearn.model_selection import RandomizedSearchCV

现在,需要像之前的示例一样加载Pima糖尿病数据集-

path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names=headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]

接下来,按以下方法在Ridge回归算法上判断各种alpha值-

param_grid = {'alpha': uniform()}
model = Ridge()
random_search = RandomizedSearchCV(
   estimator = model, param_distributions = param_grid, n_iter = 50, random_state=7)
random_search.fit(X, Y)

使用以下脚本行打印输出-

print(random_search.best_score_)
print(random_search.best_estimator_.alpha)

输出

链接:https://www.learnfk.comhttps://www.learnfk.com/python-machine-learning/machine-learning-with-python-improving-performance-of-ml-model.html

来源:LearnFk无涯教程网

0.27961712703051084
0.9779895119966027

上面的输出为无涯教程提供了最佳分数,与网格搜索类似。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

朱赟的技术管理课 -〔朱赟〕

人工智能基础课 -〔王天一〕

Java核心技术面试精讲 -〔杨晓峰〕

React实战进阶45讲 -〔王沛〕

算法面试通关40讲 -〔覃超〕

大厂设计进阶实战课 -〔小乔〕

Web 3.0入局攻略 -〔郭大治〕

超级访谈:对话道哥 -〔吴翰清(道哥)〕

程序员职业规划手册 -〔雪梅〕

好记忆不如烂笔头。留下您的足迹吧 :)