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
from sklearn.model_selection import GridSearchCV
def knn_iris_gscv():
    #1、获取数据
    iris = load_iris()
    #2、划分数据集
    x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,random_state=6)
    #3、特征工程标准化
    transfer = StandardScaler()
    x_trains = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)#只用transform保持数据平均值和方差一致性,如果用fit那么是测试机的平均值和方差
    #4、knn算法预估器
    estimate = KNeighborsClassifier()
    #加入网格搜索和交叉验证
    param_dict={"n_neighbors":[1,3,5,7,11]}
    estimater = GridSearchCV(estimate,param_grid=param_dict,cv=10)
    estimate.fit(x_train,y_train)
    #5、模型评估
    #方法一:直接比对真实值和预测值
    y_predict = estimate.predict(x_test)
    print(y_predict)
    print(y_predict==y_test)
    #方法二:计算准确率
    score = estimate.score(x_test,y_test)
    print("准确率为"+score)

    # 最佳参数
    print("最佳的k" + estimater.best_params_)
    #最佳结果
    print("最佳结果"+estimater.best_score_)
    #最佳估计器
    print("最佳估计器"+estimater.best_estimator_)
    return None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值