数据集
加载数据集:
house_trainset_path = '/path/to/train.csv' |
Index(['Id', 'MSSubClass', 'MSZoning', 'LotFrontage', 'LotArea', 'Street', |
数据处理
columns_x = ['LotArea', 'LotFrontage', 'MSSubClass', 'LotFrontage', 'LotShape', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd', 'MasVnrArea', |
drop NaN:
filtered_trainset = house_trainset[columns_of_interest].dropna(axis=0) |
string 类型转换, 以 LotShape 为例:
lot_shape_map = {"Reg": 1, "IR1": 2, "IR2": 3, "IR3": 4} |
切分数据集:
split_train_X, split_val_X, split_train_y, split_val_y = train_test_split( |
model 选择
对数据集有了大概的了解, 接下来就是选择模型进行训练和预测, 从中选出误差最小的.
决策树支持数值型和类别型的数据, 容易理解和解释, 模型属于非黑箱, 只要对数据进行较好的标注, 就能较快的从已有数据进行学习和分类 .
但对未知的数据不一定有好的效果, 容易发生过拟合.
而随机森林是解决这个问题的一种有效方法, 其他的还有剪枝、Bagging、Boosting Tree、Rotation forest 等方法.
随机森林, 顾名思义:
随机森林是一个包含多个决策树的分类器,并且其输出的类别是由个别树输出的类别的众数而定。
不过, 我们还是需要实际动手去测试一下结果.
决策树
首先分别对不同叶子数的决策树进行测试评估.
def decision_tree_train(): |
这里使用 平均绝对误差 MAE 来测量模型结果。
def get_mae(max_leaf_nodes, train_x1, val_x, train_y1, val_y): |
result:
Max leaf nodes: 5 Mean Absolute Error: 32983 |
随机森林
def random_forest_train(): |
result:
random forest: |
最后
从测试结果来看, 随机森林的效果比单纯决策树的效果要好。
参考
随机森林
https://zh.wikipedia.org/wiki/%E5%86%B3%E7%AD%96%E6%A0%91%E5%AD%A6%E4%B9%A0
https://clyyuanzi.gitbooks.io/julymlnotes/content/rf.html