数据挖掘训练营建模调参笔记

 本学习笔记为阿里云天池龙珠计划数据挖掘训练营的学习内容,学习链接为:https://tianchi.aliyun.com/specials/activity/promotion/aicampdm

一、学习知识点概要

         了解常用的机器学习模型,并掌握机器学习模型的建模与调参流

二、学习内容

1.读取数据

        当数据内存占用特别大时,在处理过程中可能会爆内存,因此我们先减少数据占用的空间。

'''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

sample_feature = reduce_mem_usage(pd.read_csv('data_for_tree.csv'))

2.交叉验证

        要考虑时间顺序问题,比如不能用2018年去预测2017年的数据。

3.建模

        如果预测值与实际值偏差较大,考虑是否由于长尾分布引起的,然后转化为正态分布。

4.模型调参

## LGB的参数集合:

objective = ['regression', 'regression_l1', 'mape', 'huber', 'fair']

num_leaves = [3,5,10,15,20,40, 55]
max_depth = [3,5,10,15,20,40, 55]
bagging_fraction = []
feature_fraction = []
drop_rate = []

(1)贪心调参(局部最优)

best_obj = dict()
for obj in objective:
    model = LGBMRegressor(objective=obj)
    score = np.mean(cross_val_score(model, X=train_X, y=train_y_ln, verbose=0, cv = 5, scoring=make_scorer(mean_absolute_error)))
    best_obj[obj] = score
    
best_leaves = dict()
for leaves in num_leaves:
    model = LGBMRegressor(objective=min(best_obj.items(), key=lambda x:x[1])[0], num_leaves=leaves)
    score = np.mean(cross_val_score(model, X=train_X, y=train_y_ln, verbose=0, cv = 5, scoring=make_scorer(mean_absolute_error)))
    best_leaves[leaves] = score
    
best_depth = dict()
for depth in max_depth:
    model = LGBMRegressor(objective=min(best_obj.items(), key=lambda x:x[1])[0],
                          num_leaves=min(best_leaves.items(), key=lambda x:x[1])[0],
                          max_depth=depth)
    score = np.mean(cross_val_score(model, X=train_X, y=train_y_ln, verbose=0, cv = 5, scoring=make_scorer(mean_absolute_error)))
    best_depth[depth] = score

sns.lineplot(x=['0_initial','1_turning_obj','2_turning_leaves','3_turning_depth'], y=[0.143 ,min(best_obj.values()), min(best_leaves.values()), min(best_depth.values())])

(2) Grid Search 调参

from sklearn.model_selection import GridSearchCV

parameters = {'objective': objective , 'num_leaves': num_leaves, 'max_depth': max_depth}
model = LGBMRegressor()
clf = GridSearchCV(model, parameters, cv=5)
clf = clf.fit(train_X, train_y)
model = LGBMRegressor(objective='regression',
                          num_leaves=55,
                          max_depth=15)

np.mean(cross_val_score(model, X=train_X, y=train_y_ln, verbose=0, cv = 5, scoring=make_scorer(mean_absolute_error)))

(3)贝叶斯调参

from bayes_opt import BayesianOptimization

def rf_cv(num_leaves, max_depth, subsample, min_child_samples):
    val = cross_val_score(
        LGBMRegressor(objective = 'regression_l1',
            num_leaves=int(num_leaves),
            max_depth=int(max_depth),
            subsample = subsample,
            min_child_samples = int(min_child_samples)
        ),
        X=train_X, y=train_y_ln, verbose=0, cv = 5, scoring=make_scorer(mean_absolute_error)
    ).mean()
    return 1 - val

rf_bo = BayesianOptimization(
    rf_cv,
    {
    'num_leaves': (2, 100),
    'max_depth': (2, 100),
    'subsample': (0.1, 1),
    'min_child_samples' : (2, 100)
    }
)

rf_bo.maximize()

三、学习问题与解答

        对正则化有了更深的理解,L1与L2正则化,L1正则化是指权值向量 w 中各个元素的绝对值之和,且能把特征压缩至零。而L2正则化是指权值向量中各个元素的平方和然后再求平方根。

四、学习思考与总结

可以用了一些基本方法来提高预测的精度,如下:

plt.figure(figsize=(13,5))
sns.lineplot(x=['0_origin','1_log_transfer','2_L1_&_L2','3_change_model','4_parameter_turning'], y=[1.36 ,0.19, 0.19, 0.14, 0.13])

  • 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、付费专栏及课程。

余额充值