精确率和召回率、模型的选择和调优(交叉验证、网格搜索)

文章介绍了精确率与召回率在评估分类模型中的作用,以及如何使用混淆矩阵来理解模型性能。接着,文章探讨了交叉验证作为模型选择和调优的一种方法,并详细阐述了网格搜索在超参数调优中的应用,以K-近邻模型为例展示了如何进行参数搜索。此外,还涉及了数据预处理步骤,如时间戳转换和特征工程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

精确率与召回率

模型的选择和调优

交叉验证

网格搜索-超参数搜索


精确率与召回率

混淆矩阵:

精确率和召回率:

 其他分类标准,F1-score,反映了模型的稳健性

分类模型评估:

模型的选择和调优

交叉验证

交叉验证:为了让被评估的模型更加准确可信

网格搜索-超参数搜索

网格搜索:调参数 K-近邻:超参数K

超参数搜索-网格搜索API

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

def knncls():
    """K-近邻预测用户签到位置"""

    # 读取数据
    data = pd.read_csv("./data/FBlocation/tain.csv")
    print(data.head(10))
    # 处理数据
    # 1.缩小数据
    data.query("x > 1.0 & x < 1.25 & y > 2.5 & y < 2.75")

    # 处理时间的数据
    time_value = pd.to_datetime(data['time'],unit='s')
    print(time_value)

    # 把日期格式转换成字典格式
    time_value = pd.DatetimeIndex(time_value)

    # 构造一些特征
    data['day'] = time_value.day
    data['hour'] = time_value.hour
    data['weekday'] = time_value.weekday

    # 把时间戳特征删除
    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)]

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

    # 进行数据的分割训练集和测试集
    x_train,x_test, y_train, y_test = train_test_split(x,y,test_size=0.25)

    # 特征工程(标准化)
    std = StandardScaler()

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

    # 进行算法流程 # 超参数
    knn = KNeighborsClassifier()

    ## fit, predict,score
    # knn.fit(x_train, y_train)

    ## 得出预测结果
    #y_predict = knn.predict(x_test)

    #print("预测的目标签到位置为:", y_predict)

    ## 得出准确率
    #print("预测的准确率:", knn.score(x_test,y_test))

    # 构造一些参数的值进行搜索
    params = {"n_neighbors":[3,5,10]}

    # 进行网格搜索
    gc = GridSearchCV(knn, param_grid=param, cv=10)

    gc.fit(x_train, y_train)

    # 预测准确率
    print("在测试集上准确率:",gc.score(x_test, y_test))

    print("在交叉验证当中最好的结果:", gc.best_score_)

    print("选择最好的模型是:", gc.best_estimator_)

    print("每个超参数每次交叉验证的结果:", gc.cv_results_)

    return None

if _name_ == "_main_":
    knncls()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值