博客第四天

交叉验证

cv = n份:即用其中一份做验证集,其他为训练集,多次评估模型。
交叉验证法,是划分数据集的一种方法,目的就是为了得到更加准确可信的模型评分。

网格搜索

网格搜索是模型调参的有力工具。寻找最优超参数的工具!只需要将若干参数传递给网格搜索对象,它自动帮我们完成不同超参数的组合、模型训练、模型评估,最终返回一组最优的超参数。

网格搜索+交叉验证


•交叉验证解决模型的数据输入问题(数据集划分)得到更可靠的模型
•网格搜索解决超参数的组合
•两个组合再一起形成一个模型参数调优的解决方案

代码实现

# 1.加载数据集
from sklearn.datasets import load_iris
iris_data = load_iris()
# 2.数据划分
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(iris_data.data,iris_data.target,train_size=0.3,random_state=22)
# 数据预处理(标准化)
from sklearn.preprocessing import StandardScaler
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)
# 实例化模型
from sklearn.neighbors import KNeighborsClassifier
estimator = KNeighborsClassifier()
# 交叉验证
from sklearn.model_selection import GridSearchCV
estimator = GridSearchCV(estimator=estimator, param_grid={'n_neighbors': [1, 3, 5, 7]}, cv=5)
estimator.fit(x_train, y_train)
print(f'{estimator.best_params_}')
# 模型评估
import pandas as pd
cvresults = pd.DataFrame(estimator.cv_results_)
cvresults.to_csv(path_or_buf='./cvresult.csv')
score = estimator.score(x_test, y_test)
print(f'{score}')

# 结果:
{'n_neighbors': 3}
0.9142857142857143

还有一个 乳腺癌的预测代码

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_breast_cancer
#加载数据集
data1 = load_breast_cancer()
#数据划分
x_train, x_test, y_train, y_test = train_test_split(data1.data,data1.target,train_size=0.2,random_state=10)
# 数据预处理(标准化)
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)
# 实例化模型
estimator = KNeighborsClassifier()
# 交叉验证
estimator = GridSearchCV(estimator=estimator, param_grid={'n_neighbors': range(1,10)}, cv=5)
estimator.fit(x_train, y_train)
print(f'{estimator.best_params_}')
# 模型评估
cvresults = pd.DataFrame(estimator.cv_results_)
cvresults.to_csv(path_or_buf='./cvresult.csv')
score = estimator.score(x_test, y_test)
print(f'{score}')

结果与参数相关,可自行尝试。

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值