Intro to Machine Learning

응방·2022년 3월 14일
0

Kaggle Courses

목록 보기
1/3

예전에 공부했던 내용들을 복습하는 차원에서 기록을 남긴다. 잊을 수 있는 내용들을 복습하기 위한 차원이므로 최대한 자세하게 서술하려고 해보자.

  1. Dataset을 import하고 불러오는 과정
import pandas as pd
from datetime import datetime

# Path of the file to read
iowa_file_path = '../input/home-data-for-ml-course/train.csv'

# Fill in the line below to read the file into a variable home_data
home_data = pd.read_csv(iowa_file_path)


# Print summary statistics in next line
home_data.describe()

hdd = home_data.describe()

# What is the average lot size (rounded to nearest integer)?
avg_lot_size = round(hdd['LotArea']['mean'])

# As of today, how old is the newest home (current year - the date in which it was built)
newest_home_age = datetime.now().year - round(hdd['YearBuilt']['max'])
  • 현재 해를 가져오기 위하여 datetime을 import하였다.
  • describe()를 통하여 dataset의 요약된 정보에 접근 가능하다.
  1. Model을 생성하고 fit하는 과정
from sklearn.tree import DecisionTreeRegressor

y = home_data.SalePrice
print(y)

# Create the list of features below
feature_names = ['LotArea','YearBuilt','1stFlrSF','2ndFlrSF','FullBath','BedroomAbvGr','TotRmsAbvGrd']

# Select data corresponding to features in feature_names
X = home_data[feature_names]

#specify the model. 
#For model reproducibility, set a numeric value for random_state when specifying the model
iowa_model = DecisionTreeRegressor(random_state=1)

# Fit the model
iowa_model.fit(X,y)

predictions = iowa_model.predict(X)
  • 예측하고자 하는 대상 가격을 y로 설정한다.
  • 가격에 영향을 끼친다고 여기는 feature들을 feature_names로 설정한다.
  • DecisionTreeRegressor를 사용하여 모델을 학습한다.

cf) DecisionTreeRegressor : https://velog.io/@eueueuu/Decision-Tree

  1. Model Validation
    Model을 학습시키는 과정에서 모든 데이터를 train에 사용하게 되면 Model이 test data에 overfitting 되는 문제가 발생한다. 따라서 일부 데이터를 분리하여 validation 데이터로 사용한다.
# Import the train_test_split function and uncomment
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error

# fill in and uncomment
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)

# Specify the model
iowa_model = DecisionTreeRegressor(random_state=1)

# Fit iowa_model with the training data.
iowa_model.fit(train_X, train_y)

# Predict with all validation observations
val_predictions = iowa_model.predict(val_X)

# print the top few validation predictions
print(val_predictions[:5])

# print the top few actual prices from validation data
print(val_y.head().tolist())

val_mae = mean_absolute_error(val_predictions, val_y)

# uncomment following line to see the validation_mae
print(val_mae)
  • 에러를 측정하기 위하여 MAE(mean_absolute_error)를 사용하였다.

cf) MAE=1ni=1nxixMAE = \frac{1}{n}\displaystyle\sum_{i=1}^{n}|x_i - x|

  1. 최적의 leaf_node 개수 찾기
    DecisionTreeRegressor Model을 사용하는 경우, max_leaf_node의 수가 지나치게 많으면 각각의 leaf_node에 해당되는 데이터의 숫자가 지나치게 적어 train_data에 overfitting되는 경우가 발생하고 이러한 경우에는 train data에 대해서는 성능이 좋지만 새로운 데이터를 집어넣었을 때 오차가 크게 발생한다. 반면, max_leaf_node의 수가 지나치게 적은 경우에도 leaf_node에 너무 많은 데이터가 포함되어 underfitting이 발생한다. 따라서 우리는 그 사이 균형점을 찾아 MAE를 최소로 만드는 max_leaf_node의 값을 계산해야 한다.
def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
    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)
    
    
candidate_max_leaf_nodes = [5, 25, 50, 100, 250, 500]
# Write loop to find the ideal tree size from candidate_max_leaf_nodes

for num in candidate_max_leaf_nodes:
    print(get_mae(num, train_X, val_X, train_y, val_y))

# Store the best value of max_leaf_nodes (it will be either 5, 25, 50, 100, 250 or 500)
best_tree_size = 100

# Fill in argument to make optimal size and uncomment
final_model = DecisionTreeRegressor(max_leaf_nodes = 100, random_state=0)

# fit the final model and uncomment the next two lines
final_model.fit(X, y)
  • max_leaf_node의 수를 변화시키며 MAE를 측정해야하므로 MAE 측정함수 get_mae를 정의하였다.
  • 그 결과 MAE를 최소로 만드는 max_leaf_node를 찾고 이를 이용하여 모델을 학습한다.
  1. Random Forest 사용
    지금까지 사용한 DecisionTreeRegressor 모델 대신 Random Forest 모델을 사용하여 학습을 진행한다. 대체로 Single Decision Tree를 사용하는 것보다 Random Forest를 사용하는 경우의 오차가 적게 나온다.
from sklearn.ensemble import RandomForestRegressor

# Define the model. Set random_state to 1
rf_model = RandomForestRegressor(random_state = 1)

# fit your model
rf_model.fit(train_X, train_y)

# Calculate the mean absolute error of your Random Forest model on the validation data
rf_val_mae = mean_absolute_error(rf_model.predict(val_X), val_y)

print("Validation MAE for Random Forest Model: {}".format(rf_val_mae))

cf) Random Forest:

(출처) Kaggle Course

profile
시작이 반이다

0개의 댓글