Kaggle进阶系列:zillow竞赛特征提取与模型融合(LB~0.644)

本文介绍Kaggle平台上Zillow房价预测比赛的解决方案,主要是介绍
特征工程(Feature Enginering)
模型融合(Model Ensemble)部分,感兴趣的同学可以深挖这两个环节,预祝大家取得好成绩。

1.Zillow简介

Zillow是美国最大的在线房产交易平台。Zestimate房屋定价模型是zillow的核心竞争力之一,该模型的median margin of error从11年前的 14%提升到了今年的5%。

参赛者通过建立新的模型来帮助zillow提高Zestimate模型的准确率。

《Kaggle进阶系列:zillow竞赛特征提取与模型融合(LB~0.644)》
《Kaggle进阶系列:zillow竞赛特征提取与模型融合(LB~0.644)》

比赛分为两个阶段:

  • 阶段1:2017-5-24 至 2018-1-17
  • 阶段2:2018-2-1 至 2019-1-15

比赛规则:

  • 每天可以提交5次
  • 禁止使用外部数据

数据探索部分在Kaggle平台上有很多比较好的Kernel,本文主要介绍
特征工程
模型融合部分。

注:本文使用Python语言,需要安装Numpy、Pandas、Matplotlib、sciket-learn以及目前非常火的XGBOOST和微软的LightGBM。

2.特征工程(Feature Engineering)

特征工程分为两部分:特征变换和添加特征。

我们用pandas自带info()函数来大概看一下数据类型信息:

这里直接贴我的代码了,我根据代码来讲我的思路。

def load_data():
    train = pd.read_csv('../input/train_2016_v2.csv')
    properties = pd.read_csv('../input/properties_2016.csv')
    sample = pd.read_csv('../input/sample_submission.csv')
    
    print("Preprocessing...")
    for c, dtype in zip(properties.columns, properties.dtypes):
        if dtype == np.float64:
            properties[c] = properties[c].astype(np.float32)
            
    print("Set train/test data...")
    id_feature = ['heatingorsystemtypeid','propertylandusetypeid', 'storytypeid', 'airconditioningtypeid',
        'architecturalstyletypeid', 'buildingclasstypeid', 'buildingqualitytypeid', 'typeconstructiontypeid']
    for c in properties.columns:
        properties[c]=properties[c].fillna(-1)
        if properties[c].dtype == 'object':
            lbl = LabelEncoder()
            lbl.fit(list(properties[c].values))
            properties[c] = lbl.transform(list(properties[c].values))
        if c in id_feature:
            lbl = LabelEncoder()
            lbl.fit(list(properties[c].values))
            properties[c] = lbl.transform(list(properties[c].values))
            dum_df = pd.get_dummies(properties[c])
            dum_df = dum_df.rename(columns=lambda x:c+str(x))
            properties = pd.concat([properties,dum_df],axis=1)
            #print np.get_dummies(properties[c])
            
    #
    # Add Feature
    #
    # error in calculation of the finished living area of home
    properties['N-LivingAreaError'] = properties['calculatedfinishedsquarefeet'] / properties[
        'finishedsquarefeet12']
    # proportion of living area
    
    properties['N-LivingAreaProp'] = properties['calculatedfinishedsquarefeet'] / properties[
        'lotsizesquarefeet']
    properties['N-LivingAreaProp2'] = properties['finishedsquarefeet12'] / properties[
        'finishedsquarefeet15']
    # Total number of rooms
    properties['N-TotalRooms'] = properties['bathroomcnt'] + properties['bedroomcnt']
    # Average room size
    #properties['N-AvRoomSize'] = properties['calculatedfinishedsquarefeet'] / properties['roomcnt']

    properties["N-location-2"] = properties["latitude"] * properties["longitude"]

    # Ratio of tax of property over parcel
    properties['N-ValueRatio'] = properties['taxvaluedollarcnt'] / properties['taxamount']

    # TotalTaxScore
    properties['N-TaxScore'] = properties['taxvaluedollarcnt'] * properties['taxamount']
    
    
    #
    # Make train and test dataframe
    #
    train = train.merge(properties, on='parcelid', how='left')
    sample['parcelid'] = sample['ParcelId']
    test = sample.merge(properties, on='parcelid', how='left')

    # drop out ouliers
    train = train[train.logerror > -0.4]
    train = train[train.logerror < 0.42]

    train["transactiondate"] = pd.to_datetime(train["transactiondate"])
    train["Month"] = train["transactiondate"].dt.month

    x_train = train.drop(['parcelid', 'logerror','transactiondate', 'propertyzoningdesc', 'propertycountylandusecode'], axis=1)
    y_train = train["logerror"].values
    test["Month"] = 10
    x_test = test[x_train.columns]
    del test, train    
    print(x_train.shape, y_train.shape, x_test.shape)
    
    return x_train, y_train, x_test

我定义了一个load_data函数,将特征工程相关的代码都放在这个函数里面。

第一部分 特征变换

(1)读取数据

有三个文件需要读取:train_2016.csv、propertie_2016.csv和sample_submission.csv。可以用pandas 的read_csv()将数据读取为dataframe。

文件描述
Properties_2016.csv:包含2016年房屋特征的所有内容。
Train_2016_v2.csv:2016年1月到2016年12月的训练数据集
Sample_submission.csv:正确提交文件的实例

(2)类型转换

我们大部分的模型都只支持数值型的数据,所以,我们需要将非数值类型的数据转换为我们数值类型。这里,我使用了两种方案:

第一种方案:将‘object’类型的数据进行Label Encode

第二种方案:将id类型的数据首先进行Labe lEncode,然后进行One Hot编码。

在Zillow比赛给出的数据描述文件“zillow_data_dictionary.xlsx”

第二部分 构造新特征

我对原始的特征进行加、乘、除运算构造了一些新的特征,对成绩是有一定帮助的。

到此,我的特征工程基本结束,最终使用的特征差不多有130个左右。特征工程是Kaggle竞赛里最为重要的一步,需要我们花大量的时间和精力来尝试,我80%的精力几乎都是用在特征工程上。

3.模型融合(Model Ensemble)

特征工程决定我们机器学习的上限,而模型让我们不断去逼近这个上限。

在kaggle比赛中,如果我们没有其他很好的思路,那么一个很好的选择就是模型融合

关于模型融合,网上有很多讲解非常好的文章。模型融合的理论知识不是本篇文章的重点,这里介绍几篇写的不错的文章,供大家参考。

模型融合的方法也很多,我采用的是Stacking,相关的理论上面的提到文章写的比较清晰,我就直接上我的代码了。

class Ensemble(object):
    def __init__(self, n_splits, stacker, base_models):
        self.n_splits = n_splits
        self.stacker = stacker
        self.base_models = base_models

    def fit_predict(self, X, y, T):
        X = np.array(X)
        y = np.array(y)
        T = np.array(T)

        folds = list(KFold(n_splits=self.n_splits, shuffle=True, random_state=2016).split(X, y))

        S_train = np.zeros((X.shape[0], len(self.base_models)))
        S_test = np.zeros((T.shape[0], len(self.base_models)))
        for i, clf in enumerate(self.base_models):

            S_test_i = np.zeros((T.shape[0], self.n_splits))

            for j, (train_idx, test_idx) in enumerate(folds):
                X_train = X[train_idx]
                y_train = y[train_idx]
                X_holdout = X[test_idx]
                y_holdout = y[test_idx]
                print ("Fit Model %d fold %d" % (i, j))
                clf.fit(X_train, y_train)
                y_pred = clf.predict(X_holdout)[:]                

                S_train[test_idx, i] = y_pred
                S_test_i[:, j] = clf.predict(T)[:]
            S_test[:, i] = S_test_i.mean(axis=1)

        # results = cross_val_score(self.stacker, S_train, y, cv=5, scoring='r2')
        # print("Stacker score: %.4f (%.4f)" % (results.mean(), results.std()))
        # exit()

        self.stacker.fit(S_train, y)
        res = self.stacker.predict(S_test)[:]
        return res

# rf params
rf_params = {}
rf_params['n_estimators'] = 50
rf_params['max_depth'] = 8
rf_params['min_samples_split'] = 100
rf_params['min_samples_leaf'] = 30

# xgb params
xgb_params = {}
xgb_params['n_estimators'] = 50
xgb_params['min_child_weight'] = 12
xgb_params['learning_rate'] = 0.27
xgb_params['max_depth'] = 6
xgb_params['subsample'] = 0.77
xgb_params['reg_lambda'] = 0.8
xgb_params['reg_alpha'] = 0.4
xgb_params['base_score'] = 0
#xgb_params['seed'] = 400
xgb_params['silent'] = 1


# lgb params
lgb_params = {}
lgb_params['n_estimators'] = 50
lgb_params['max_bin'] = 10
lgb_params['learning_rate'] = 0.321 # shrinkage_rate
lgb_params['metric'] = 'l1'          # or 'mae'
lgb_params['sub_feature'] = 0.34    
lgb_params['bagging_fraction'] = 0.85 # sub_row
lgb_params['bagging_freq'] = 40
lgb_params['num_leaves'] = 512        # num_leaf
lgb_params['min_data'] = 500         # min_data_in_leaf
lgb_params['min_hessian'] = 0.05     # min_sum_hessian_in_leaf
lgb_params['verbose'] = 0
lgb_params['feature_fraction_seed'] = 2
lgb_params['bagging_seed'] = 3


# XGB model
xgb_model = XGBRegressor(**xgb_params)

# lgb model
lgb_model = LGBMRegressor(**lgb_params)

# RF model
rf_model = RandomForestRegressor(**rf_params)

# ET model
et_model = ExtraTreesRegressor()

# SVR model
# SVM is too slow in more then 10000 set
#svr_model = SVR(kernel='rbf', C=1.0, epsilon=0.05)

# DecsionTree model
dt_model = DecisionTreeRegressor()

# AdaBoost model
ada_model = AdaBoostRegressor()

stack = Ensemble(n_splits=5,
        stacker=LinearRegression(),
        base_models=(rf_model, xgb_model, lgb_model, et_model, ada_model, dt_model))

y_test = stack.fit_predict(x_train, y_train, x_test)

这些代码看起来很长,其实非常简单。

核心思想:我用了两层的模型融合,Level 1使用了:XGBoost、LightGBM、RandomForest、ExtraTrees、DecisionTree、AdaBoost,一共6个模型,Level 2使用了LinearRegression来拟合第一层的结果。

代码实现:

  • 定义一个Ensemble对象。我们将模型和数据扔进去它就会返回给我们预测值。文章篇幅有限,这个算法具体的实现方式以后再说
  • 设定模型参数,构造模型。
  • 将我们的模型和数据,传到Ensemble对象里就可以得到预测结果。

最后一步就是提交我们的结果了。

结束语

我写这篇文章的时候,我的zillow排名在400名13%。新手入门,第一次参赛,欢迎交流。

我用到的代码在kaggle上公开了。
https://www.kaggle.com/wangsg/ensemble-stacking-lb-0-644

微信公众号:kaggle数据分析

    原文作者:王十二的
    原文地址: https://zhuanlan.zhihu.com/p/29794651
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞