KNN分类练习

直接固定KNN参数

from sklearn.datasets import load_iris # 获取燕尾花数据
from sklearn.model_selection import train_test_split # 测试训练集划分
from sklearn.preprocessing import StandardScaler # 标准化模块
from sklearn.neighbors import KNeighborsClassifier # KNN 分类器
# 第一步获取数据
data = load_iris()
# 第二部进行训练集划分
x_train,x_test,y_train,y_test = train_test_split(data.data,data.target,random_state=6)
# 第三步进行标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# KNN分类器
classifier = KNeighborsClassifier()
# 分类器进行计算
classifier.fit(x_train,y_train)
# 进行分类
y_perdict = classifier.predict(x_test)
print(y_perdict == y_test)
# 分类器准确率计算
score = classifier.score(x_test,y_test)
print(score)

本来像找其他数据进行练习了,可惜没有找到,自己爬取麻烦,就这样吧

添加网格搜索cv进行模型调优

from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
# 划分训练集和测试集
x_train,x_test,y_train,y_test = train_test_split(x,y,random_state=6)
# 数据标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# 网格cv
classifier = KNeighborsClassifier()
n_neighbors = list(range(1,4))
weights = ['uniform','distance']
algorithm_options = ['auto','ball_tree','kd_tree','brute']
leaf_range = list(range(1,10))
p = list(range(1,10))
param_grid = [{'n_neighbors': n_neighbors, 'weights': weights, 'algorithm': algorithm_options, 'leaf_size': leaf_range, 'p':p}]
classifier = GridSearchCV(classifier,param_grid=param_grid,cv=10)
classifier.fit(x_train,y_train)
y_perdict = classifier.predict(x_test)
print('模型评估:{}'.format(classifier.best_params_))
print('最好的参数:{}'.format(classifier.best_score_))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值