建模调参

前期准备

减少数据在内存占用空间

reduce_mem_usage 函数通过调整数据类型,帮助我们减少数据在内存中占用的空间

def reduce_mem_usage(df):
    """ iterate through all the columns of a dataframe and modify the data type
        to reduce memory usage.        
    """
    start_mem = df.memory_usage().sum() 
    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
    
    for col in df.columns:
        col_type = df[col].dtype
        
        if col_type != object:
            c_min = df[col].min()
            c_max = df[col].max()
            if str(col_type)[:3] == 'int':
                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
                    df[col] = df[col].astype(np.int8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
                    df[col] = df[col].astype(np.int16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
                    df[col] = df[col].astype(np.int32)
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
                    df[col] = df[col].astype(np.int64)  
            else:
                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
                    df[col] = df[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
                    df[col] = df[col].astype(np.float32)
                else:
                    df[col] = df[col].astype(np.float64)
        else:
            df[col] = df[col].astype('category')

    end_mem = df.memory_usage().sum() 
    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))
    return df

知识点

N折交叉验证

整个训练集可分为三部分:训练集(train)、评估集(valid)、测试集(test),N折交叉验证将数据集分为N组,选取一组作为验证集,剩余N-1组作为训练集,得到N个验证集分类准确率score,取平均后作为此模型在此N折交叉验证下的性能指标。

1 建立模型及相关属性和方法

步骤
(1)模型api实例化
(2)分类器:通过fit方法,使用训练集训练模型,得到分类器
(3)分类器的属性:可以输出截距、回归系数等
(4)可使用该分类器预测test样本,进行结果可视化观测

详见: Liner-Regression 线性回归.

2 评价模型

2.1常用评价函数

平均绝对误差MAE
Mean absolute error

mean_absolute_error(y_true, y_pred, *, sample_weight=None, multioutput=‘uniform_average’)
返回:loss:non-negative float or ndarray of non-negative floats

multioutput:
(1)选择’uniform_average’代表输出所有误差的等权均值,non-negative float型
(2)选择‘raw_values’代表输出误差原始值,返回一个ndarray
(3)选择array-like of shape (n_outputs)代表定义了各输出值的权重,进行加权值输出,non-negative float型

2.2 选择模型评估工具

例如: grid_search.GridSearchCV 和 cross_validation.cross_val_score

2.3 设计模型评价函数

设计scoring参数:需要使用make_scorer()生成一个scorer对象

API

sklearn.metrics.make_scorer()
两种用法:
(1)直接将metrics函数转换成可调用的scorer对象
(2)自定义函数,参数包括score_func(y, y_pred, **kwargs),返回值为float

make_scorer(score_func, *, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs)
返回:scorer:a callable object

主要参数

Parameter数据类型含义
score_funcscore function or loss function以_score结尾的函数,值越大越好;以_error结尾的函数,越小越好;也可以自己构建函数输入
greater is betterbool是否值越大代表越好

2.4 N折交叉验证

整个训练集可分为三部分:训练集(train)、评估集(valid)、测试集(test),N折交叉验证将数据集分为N组,选取一组作为验证集,剩余N-1组作为训练集,得到N个验证集分类准确率score,取平均后作为此模型在此N折交叉验证下的性能指标。

API

sklearn.model_selection.cross_val_score()

cross_val_score(estimator, X, y=None, , groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2n_jobs’, error_score=nan)
返回:array,shape=(len(list(cv)),)

Parameters

参数数据类型含义
estimatorestimator选择的模型实例
Xarray-like of shape (n_samples, n_features)
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

estimator:模型的实例
X:特征,list或array
y:标签
scoring:用以评价的函数
cv:几折交叉验证,默认五折
n_jobs:同时工作的cpu个数(-1代表全部)

2.5 可视化

学习曲线

自变量:训练集的大小
因变量:交叉验证的训练集分数和验证集分数
variance:estimator随着训练集变化的改变程度
学习曲线反映bias和variance的平衡关系,当训练集很小时,会出现训练集低bias高variance、验证集高bias低variance的情况;随着训练集增大,训练集bias逐渐增大variance逐渐降低,验证集bias逐渐降低variance逐渐增大。学习曲线可以找到bias和variance的平衡点。
sklearn.model_selection.learning_curve

sklearn.model_selection.learning_curve(estimator, X, y, *, groups=None, train_sizes=array([0.1, 0.33, 0.55, 0.78, 1. ]), cv=None, scoring=None, exploit_incremental_learning=False, n_jobs=None, pre_dispatch=‘all’, verbose=0, shuffle=False, random_state=None, error_score=nan, return_times=False)
返回:
train_size_abs:ndarray
train_scores:ndarray shape like cv_size
test_scires:ndarray shape like cv_size

3 调参

在这里插入图片描述

3.1 贪心算法

可能会调到局部最优,而不是全局最优

3.2 贝叶斯调参

API
安装包:bayesian-optimization
调用:bayes_opt.BayesianOptimization()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个基于Python和Scikit-learn库的多属性价格预测建模调参的示例代码。这里使用了随机森林回归模型,你可以根据自己的需求选择其他的模型。 首先,我们需要导入必要的库和数据集: ```python import pandas as pd import numpy as np from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split, RandomizedSearchCV # 读取数据集 df = pd.read_csv('data.csv') ``` 然后,我们需要对数据集进行预处理,包括处理缺失值、转换数据类型、划分训练集和测试集等: ```python # 处理缺失值 df = df.dropna() # 转换数据类型 df['age'] = pd.to_numeric(df['age'], errors='coerce') df['mileage'] = pd.to_numeric(df['mileage'], errors='coerce') df['price'] = pd.to_numeric(df['price'], errors='coerce') # 划分训练集和测试集 X = df.drop(['price'], axis=1) y = df['price'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 接着,我们需要对模型进行调参。这里我们使用了随机搜索(RandomizedSearchCV)方法来搜索最优的超参数,包括n_estimators(决策树个数)、max_depth(决策树深度)、min_samples_split(内部节点再划分所需最小样本数)等: ```python # 定义模型和超参数搜索空间 rf = RandomForestRegressor() params = { 'n_estimators': [100, 200, 300, 400, 500], 'max_depth': [10, 20, 30, 40, 50], 'min_samples_split': [2, 5, 10, 20, 30] } # 随机搜索最优超参数 random_search = RandomizedSearchCV(rf, param_distributions=params, n_iter=10, cv=5, n_jobs=-1, random_state=42) random_search.fit(X_train, y_train) # 输出最优超参数和训练集上的得分 print('Best Params:', random_search.best_params_) print('Training Score:', random_search.best_score_) ``` 最后,我们使用得到的最优超参数来训练模型,并在测试集上进行评估: ```python # 训练模型 rf = RandomForestRegressor(n_estimators=300, max_depth=30, min_samples_split=2) rf.fit(X_train, y_train) # 在测试集上进行评估 y_pred = rf.predict(X_test) score = rf.score(X_test, y_test) print('Test Score:', score) ``` 至此,我们完成了多属性价格预测建模调参的代码。当然,这只是一个简单的示例,实际应用中需要根据具体情况进行调整

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值