• 入门教程
• 分类教程
• 回归教程
• 聚类教程
• KNN教程
• 关注我们

# KNN算法 - 改善性能

## 网格搜索参数调整

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

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

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)

0.2796175593129722
1.0

## 随机搜索参数调整

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

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

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)

0.27961712703051084
0.9779895119966027

## 猜你喜欢

Linux实战技能100讲 -〔尹会生〕

Selenium自动化测试实战 -〔郭宏志〕