分类算法-模型选择与调优

一 交叉验证目的

为了让被评估的模型更加准确可信

二 交叉验证(cross validation)

交叉验证:将拿到的训练数据,分为训练和验证集。以下图为例:将数据分成5份,其中一份作为验证集。然后经过5次(组)的测试,每次都更换不同的验证集。即得到5组模型的结果,取平均值作为最终结果。又称5折交叉验证。

2.1 分析

在这里插入图片描述

三 超参数搜索-网格搜索(Grid Search)

通常情况下,有很多参数是需要手动指定的(如k-近邻算法中的K值),**这种叫超参数。**但是手动过程繁杂,所以需要对模型预设几种超参数组合。每组超参数都采用交叉验证来进行评估。最后选出最优参数组合建立模型。

在这里插入图片描述

3.1 模型选择与调优

sklearn.model_selection.GridSearchCV(estimator, param_grid=None,cv=None)

  • 对估计器的指定参数值进行详尽搜索
  • estimator:估计器对象
  • param_grid:估计器参数(dict){“n_neighbors”:[1,3,5]}
  • cv:指定几折交叉验证
  • fit:输入训练数据
  • score:准确率
  • 结果分析:
    bestscore:在交叉验证中验证的最好结果_
    bestestimator:最好的参数模型
    cvresults:每次交叉验证后的验证集准确率结果和训练集准确率结果

四 Facebook签到位置预测K值调优

from sklearn.model_selection import train_test_split,GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
import pandas as pd


"""
k-紧邻 预测用户签到位置
"""
# 1.读取数据
data = pd.read_csv("./facebook-v-predicting-check-ins/train.csv")
print(data.head(10))

#处理数据
# 1.缩小数据 比如 pladc_id 入住位置,每个都不一样,但是可能某些位置就一两个人,
# 查询数据晒讯
data = data.query("x > 1.0 & x < 1.25 & y > 2.5 & y < 2.75")

# 2.处理时间 -时间戳日期  1990-01-01 10:25:10
timevalue = pd.to_datetime(data['time'], unit='s')
# 把时间格式转换成 字典格式
timevalue = pd.DatetimeIndex(timevalue)
# 构造特征 加入时间的其它的特征
data['day'] = timevalue.day
data['hour'] = timevalue.hour
data['weekday'] = timevalue.weekday

# 把时间戳特征删除  pd里1表示列 ske里0表示列
data = data.drop(['time'], axis=1)

# 把签到数量少于n个目标位置删除
place_count = data.groupby('place_id').count()
tf = place_count[place_count.row_id > 3].reset_index()

data = data[data['place_id'].isin(tf.place_id)]

# 3.取出特征值和目标值 去除数据中的特征值 和 目标值
y = data['place_id']
x = data.drop(['place_id'], axis=1)

# 4.数据分割
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)

# 5. 标准化 - 特征工程
std = StandardScaler()
#对测试集和训练集的特征值进行标准化
x_train = std.fit_transform(x_train)
x_test = std.fit_transform(x_test)

# 二 进行算法流程
# K值:算法传入参数不定的值    理论上:k = 根号(样本数)
# K值:后面会使用参数调优方法,去轮流试出最好的参数[1,3,5,10,20,100,200]
knn = KNeighborsClassifier()

param = {"n_neighbors": [3, 5, 10]}

gc = GridSearchCV(knn, param_grid=param, cv=2)

gc.fit(x_train, y_train)

print("选择了某个模型测试集当中预测的准确率为:", gc.score(x_test, y_test))

# 训练验证集的结果
print("在交叉验证当中验证的最好结果:", gc.best_score_)
print("gc选择了的模型K值是:", gc.best_estimator_)
print("每次交叉验证的结果为:", gc.cv_results_)
发布了107 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/beishanyingluo/article/details/104866840
今日推荐