티스토리 뷰

Programming/Data

Kaggle - Intro to Machine Learning

prograsshopper_ 2020. 2. 24. 16:00

결정 트리(Decision Tree) :

- 예상한 값을 주는 아랫부분을 리프라 하고, 리프의 값과 나누는 기준은 데이터로 결정된다.

 

Data Frame : 테이블형의 데이터 타입. 액셀 시트같은걸 생각하면 된다,

 

Pandas

- 설치 : 링크

*데이터등을 불러올 때 random_state는 실행시마다 같은 값이 나오게 할지 여부를 정해주는 파라미터다.

 

read_csv(path) : path에 있는 파일을 읽어온다.

describe() : 읽어온 값을 보여준다.

columns: 해당 파일의 컬럼들을 보여준다. 각 컬럼은 dot notation으로 불러올 수 있다.

 

만약 불러온 값에서 특정 컬럼들만 보고 싶다면 data[selected_columns] 식으로 불러오면 된다. 이 때 selected_columns는 리스트 형식.

 

Skitlearn : 데이터 프레임에 저장된 데이터타입을 모델링하는데 쓰이는 가장 유명한 라이브러리. 

 

보통 데이터 모델링을 할 때는 Define - Fit  - Predict - Evaluate 의 네 스탭을 거쳐서 모델링을 하게 된다,

 

Model Validation

예상의 정확성을 추측할 때 저지르는 큰 실수가 있는데, 어떤 데이터를 통해 예상을 만들고 예상을 해당 데이터의 값과 비교하는 행위가 바로 그것이다. 

Mean Absolute Error (MAE) :  error=actual−predicted 를 사용해서 정확성 측정

 

Underfitting and overfitting

트리의 level에 따라, 2의 level 제곱만큼의 그룹이 생긴다.

Overfitting: 레벨이 높아질 수록 실제 값에 가까워지지만 새로운 데이터에 적용하면 부정확해질 가능성도 높아진다. 이를 오버피팅이라고 부른다. 정확한 예측을 이끌어내는데 방해된다.
Underfitting: 적절한 패턴을 집어내는 데에 실패한다. 역시 정확한 예측을 이끌어내는데 방해된다.

# Write loop to find the ideal tree size from candidate_max_leaf_nodes
# Store the best value of max_leaf_nodes (it will be either 5, 25, 50, 100, 250 or 500)
candidate_max_leaf_nodes = [5, 25, 50, 100, 250, 500]

# 내가 짠 것인데 정말 pythonic하지 않고 쓸데없이 길다. 
# pythonic한 코드에 대한 고민을 하나도 안한 스스로에게 실망..

max_leaf_nodes = None
best_tree = None
for node in candidate_max_leaf_nodes:
    current_nodes = get_mae(node, train_X, val_X, train_y, val_y)
    if not max_leaf_nodes:
        max_leaf_nodes = current_nodes
        best_tree = node
        continue
    else:
        if max_leaf_nodes > current_nodes:
            max_leaf_nodes = current_nodes
            best_tree = node
best_tree_size = best_tree

# 예시 답안인데 훨씬 깔끔하고 예쁘다.
scores = {leaf_size: get_mae(leaf_size, train_X, val_X, train_y, val_y) for leaf_size in candidate_max_leaf_nodes}
best_tree_size = min(scores, key=scores.get)

 

Random Forest

- 많은 트리를 사용하고, 각 컴포넌트 트리에 대한 예측의 평균들을 바탕으로 예측을 만들어낸다. (The random forest uses many trees, and it makes a prediction by averaging the predictions of each component tree. )

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error

forest_model = RandomForestRegressor(random_state=1)
forest_model.fit(train_X, train_y)
melb_preds = forest_model.predict(val_X)
print(mean_absolute_error(val_y, melb_preds))

결과

202888.18157951365
/opt/conda/lib/python3.6/site-packages/sklearn/ensemble/forest.py:245: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.
  "10 in version 0.20 to 100 in 0.22.", FutureWarning)

 

 

끝낸 소감

- 이걸 끝냈다고 머신러닝을 할 수 있겠다 는 아니고 일단 판다스와 사이킷런에 대해서 살펴봐야겠다. 이 튜토리얼은 머신러닝이 이런 과정으로 이뤄지는 구나.. 정도로 알아가면 될 듯.

 

반응형

'Programming > Data' 카테고리의 다른 글

PySpark : 2. Spark Dataframe Basics 1, 2  (0) 2024.02.01
PySpark : 1. Hadoop, Mapreduce, Spark  (0) 2024.01.28
Datacamp SQL Fundamentals <1>  (0) 2019.09.24
Numpy <1>  (0) 2019.01.03
댓글