Day 5 [Python ML] 欠拟合(Underfitting)和过拟合(Overfitting)

实验不同的模型

若是是太多分支,会造成leaf太多,而每一个leaf都只是用其中一笔资料建立出来的,因此对model来说,会过度拟和(overfitting)

因此在验证(validation)的时候,需要测试较多的情况,并且用不同的参数来验证

得到最好的值之後,再利用这个参数,对所有资料建模

# 读取资料
import pandas as pd
    
melbourne_file_path = './Dataset/melb_data.csv'
melbourne_data = pd.read_csv(melbourne_file_path) 
# 处理缺失值
filtered_melbourne_data = melbourne_data.dropna(axis=0)
# 选择目标和特徵
y = filtered_melbourne_data.Price
melbourne_features = ['Rooms', 'Bathroom', 'Landsize', 'BuildingArea', 
                        'YearBuilt', 'Lattitude', 'Longtitude']
X = filtered_melbourne_data[melbourne_features]

# 切割资料成训练资料和验证资料
from sklearn.model_selection import train_test_split
train_X, val_X, train_y, val_y = train_test_split(X, y,random_state = 0)
# 汇入决策树和平均绝对误差
from sklearn.metrics import mean_absolute_error
from sklearn.tree import DecisionTreeRegressor

# 写一个叫做取得平均绝对误差的function,get_mae
# input有树的最大节点数量(max_leaf_nodes)、训练资料和验证资料
def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
    # 创建一个决策树的model,并且将最大节点数量设为max_leaf_nodes
    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)
    # 训练资料
    model.fit(train_X, train_y)
    # 取得预测结果
    preds_val = model.predict(val_X)
    # 算出平均绝对误差
    mae = mean_absolute_error(val_y, preds_val)
    return(mae)
# 求出不同的最大节点的平均绝对误差
for max_leaf_nodes in [5, 50, 500, 5000]:
    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
    print("Max leaf nodes: %d  \t\t Mean Absolute Error:  %d" %(max_leaf_nodes, my_mae))
Max leaf nodes: 5  		 Mean Absolute Error:  347380
Max leaf nodes: 50  		 Mean Absolute Error:  258171
Max leaf nodes: 500  		 Mean Absolute Error:  243495
Max leaf nodes: 5000  		 Mean Absolute Error:  254983

在这边发现max_leaf_node=500对这个模型来说是相对好的参数

因此使用这个参数对全部的资料做建模

结论

Overfitting: 太过吻合训练资料,导致在验证的时候准确度降低

Underfitting: 不够吻合训练资料,导致预测的时候不准确


<<:  【Day 03】- 打针!打针!从 R0 注入的那件事!

>>:  [Day3]资料库连线及新增使用者

Day20 Vue元件中的网页模板

我们现在应该大概了元件到底在干嘛了,今天的话我们就来聊聊HTML模板怎麽写在我们的元件里面,通常我们...

30天程序语言研究

今天是30天程序语言研究的第二十五天,由於最近写unix语言的东西用到很多,所以做了很多笔记,就想说...

Day 10:Component, Component, Component

前面的文章匆忙带过 MainWindow,建议从官方的文件再深入理解 JUCE Applicatio...

Day25 在麦块用手持式电脑玩魔术方块

今天来玩 CC: Tweaked Pocket Computer 在工具箱有一排各式各样 Pocke...

台南的空气是甜的吧

本篇来分享笔者打比赛的经验! 第一次打比赛 我参加的第一个资讯竞赛是由成大协办的 ITSA Geek...