Lv2. Data Preprocessing
1. 결측치 대체 - 평균값
df.fillna({'칼럼명':int(df['칼럼명'].mean())}, inplace=True)
# 결측치가 있는 feature 살펴보기
print(train.isnull().sum())
train.info()
# 결측치 평균값으로 대체하기
train.fillna({'hour_bef_temperature':int(train['hour_bef_temperature'].mean())}, inplace=True)
# 결과 확인
print(train.isnull().sum())
2. 결측치 대체 - 보간법¶
보간법이란?
알려진 데이터의 지점의 고립점 내에서 새로운 데이터 지점을 구하는 방식
독립 변수의 중간값에 대한 해당 함수의 값을 예측하는 등에 사용
Python pandas 의 interpolate() method 를 사용해 구현
df.interpolate(inplace=True)
print(train.isnull().sum())
id 0
hour 0
hour_bef_temperature 2
hour_bef_precipitation 2
hour_bef_windspeed 9
hour_bef_humidity 2
hour_bef_visibility 2
hour_bef_ozone 76
hour_bef_pm10 90
hour_bef_pm2.5 117
count 0
dtype: int64
train.interpolate(inplace=True)
print(train.isnull().sum())
id 0
hour 0
hour_bef_temperature 0
hour_bef_precipitation 0
hour_bef_windspeed 0
hour_bef_humidity 0
hour_bef_visibility 0
hour_bef_ozone 0
hour_bef_pm10 0
hour_bef_pm2.5 0
count 0
dtype: int64
데이터에 따라서 결측치를 어떻게 대체할지 결정하는 것은 엔지니어의 몫!
Lv2. Modeling - RandomForest
1. 개념 및 선언
랜덤포레스트는 여러 개의 의사결정나무를 만들어서 이들의 평균으로 예측의 성능을 높이는 방법.
해당 기법을 앙상블(Ensemble)기법이라고 한다.
각 의사결정나무의 데이터로부터 여러 개의 랜덤한 샘플 데이터셋을 추출해, 각 데이터셋을 통해 모델 여러 개를 만들어 추론할 수 있다.
#랜덤포레스트 회귀 모델 선언
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor()
2. Criterion ; 평가척도에 맞게 학습
랜덤포레스트 모듈의 옵션 중 criterion 옵션을 통해 어떤 평가척도를 기준으로 훈련할 것인지 정할 수 있다.
따릉이 대회의 평가지표는 RMSE로, MSE 평가 지표에 루트를 씌운 것이다.
모델 선언시 criterioin = 'mse'
옵션으로 구현 가능
평균 제곱근 편차(Root Mean Square Deviation; RMSD) 또는 평균 제곱근 오차(Root Mean Square Error; RMSE)는 추정 값 또는 모델이 예측한 값과 실제 환경에서 관찰되는 값의 차이를 다룰 때 흔히 사용하는 측도
MSE(mean square error)란? 오차(잔차)의 제곱에 대한 평균을 취한 값으로 통계적 추정의 정확성에 대한 질적인 척도로 많이 사용됨
#라이브러리 불러오기
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
#데이터 불러오기
train = pd.read_csv('train.csv 경로')
#결측치 전처리(보간)
print(train.isnull().sum())
train.interpolate(inplace=True)
#train.fillna({['columnName']:int(train['columnName'].mean())}, inplace=True) #평균값 대체
#conut feature 제거한 X_train df생성 / 훈련값
X_train = train.dropna(['count'], axis=1)
#count feature 만 가진 Y_train df생성 / 결과값
Y_train = train['count']
#랜덤포레스트 모델 훈련_평가척도
model = RandomForestRegressor(criterion='mse')
model.fit(X_train, Y_train)
Lv2. Tunning - RandomForest
1. 변수중요도 확인
fit()으로 모델이 학습되고 나면 feature_importances_속성(attribute)으로 변수의 중요도 파악 가능
변수의 중요도란, 예측변수를 결정할 때 각 feature가 얼마나 중요한 역할을 하는지에 대한 척도
변수의 중요도가 낮다면 해당 feature를 제거하는 것이 모델의 성능을 높일 수 있다.
model.feature_importances_
#id hour hour_bef_temperature hour_bef_precipitation hour_bef_windspeed
# hour_bef_humidity hour_bef_visibility hour_bef_ozone hour_bef_pm10 hour_bef_pm2.5 count
array([0.02444425, 0.59261167, 0.18402489, 0.01904059, 0.02619953,
0.03595049, 0.03113678, 0.03421576, 0.03176295, 0.0206131 ])
2. drop ; 변수제거
변수중요도가 낮은 feature를 제거하여 모델을 훈련할 수 있다.
예측에 의미가 없는 feature를 drop, 훈련 df와 예측 df는 동일한 feature를 가져야 한다.
# X_train 에서 drop 할 피쳐의 경우에 수 대로 3개의 X_train 을 생성하세요.
# 각 train 에 따라 동일하게 피쳐를 drop 한 test 셋들을 생성하세요.
#count와 id drop
X_train_1 = X_train.drop(['id'], axis=1)
#동일한 feature test data set
test_1 = test.drop(['id'],axis=1)
#hour_bef_windspeed drop
X_train_2 = X_train_1.drop(['hour_bef_windspeed'], axis=1)
test_2 = test_1.drop(['hour_bef_windspeed'],axis=1)
#hour_bef_windspeed drop
X_train_3 = X_train_2.drop(['hour_bef_pm2.5'], axis=1)
test_3 = test_2.drop(['hour_bef_pm2.5'],axis=1)
# 각 X_train에 대해 모델 훈련을 해주세요.
model_input_var1 = RandomForestRegressor(criterion='mse')
model_input_var2 = RandomForestRegressor(criterion='mse')
# model_input_var3 = model_input_var1
# 이렇게 선언하면 1과 같은 index값을 가지게 되는지 궁금
# python 은 pointer는 없지만 `id(객체)`로 객체의 주소값을 확인할 수 있다.
# 위처럼 변수를 선언하면 같은 주소값을 가지게 된다.
model_input_var3 = RandomForestRegressor(criterion='mse')
model_input_var1.fit(X_train_1, Y_train)
model_input_var2.fit(X_train_2, Y_train)
model_input_var3.fit(X_train_3, Y_train)
/usr/local/lib/python3.7/dist-packages/sklearn/ensemble/_forest.py:400: FutureWarning: Criterion 'mse' was deprecated in v1.0 and will be removed in version 1.2. Use `criterion='squared_error'` which is equivalent.
FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/ensemble/_forest.py:400: FutureWarning: Criterion 'mse' was deprecated in v1.0 and will be removed in version 1.2. Use `criterion='squared_error'` which is equivalent.
FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/ensemble/_forest.py:400: FutureWarning: Criterion 'mse' was deprecated in v1.0 and will be removed in version 1.2. Use `criterion='squared_error'` which is equivalent.
FutureWarning,
[python의 pointer]
a,b의 값을 swich하려면 java, c같은 경우 빈 곳에 하나의 값을 둔 후, 두 값을 바꾸게 된다.
a=5
b=10
c=a
a=b
b=c
print('a='+str(a)+', b='+str(b))
a=10, b=5
python은 해당 코드를 한줄로 줄일 수 있다.
python은 타 언어의 static memory형식이 아닌 allocated memory 형식이기 때문이라고 한다.
a,b=b,a
print('a='+str(a)+', b='+str(b))
a=5, b=10
# 각 모델로 test 셋들을 예측해주세요.
y_pred_1 = model_input_var1.predict(test_1)
y_pred_2 = model_input_var2.predict(test_2)
y_pred_3 = model_input_var3.predict(test_3)
# 각 결과들을 submission 파일로 저장해주세요.
sub_1 = pd.read_csv('/content/submission.csv')
sub_2 = pd.read_csv('/content/submission.csv')
sub_3 = pd.read_csv('/content/submission.csv')
sub_1['count'] = y_pred_1
sub_2['count'] = y_pred_2
sub_3['count'] = y_pred_3
sub_1.to_csv('sub_1.csv', index=False)
sub_2.to_csv('sub_2.csv', index=False)
sub_3.to_csv('sub_3.csv', index=False)
3. 하이퍼파라미터 | GridSearch
하이퍼파라미터 튜닝은 정지규칙 값들을 설정하는 것을 의미한다.
의사결정나무에는 정지규칙(stopping criteria)이라는 개념이 있다.
정지규칙이 없다면 학습데이터를 완벽하게 학습하기위해 어느샌가 과적합이 발생해 테스트 데이터에는 성능이 낮게나온다. 때문에 어느정도 선에서 끊어주는 것이 필요하고 이것을 정지규칙이라고 한다.
정지규칙_의사결정나무 인자의 종류
- 최대깊이(max_depth) 뿌리 노드로부터 내려갈 수 있는 깊이를 지정하며 값이 작을수록 트리는 작아진다.
- 최소 노드크기(min_samples_split) 노드를 분할하기 위한 데이터 수.
해당 노드에 이 값보다 적은 확률변수 수가 있다면 stop. 값이 작을수록 트리는 커진다.- 최소 향상도(min_impurity_decrease) 노드를 분할하기 위한 최소 향상도. 향상도가 설정값 이하라면 더 이상 분할하지 않는다. 값이 작을수록 트리는 커진다.
- 비용복잡도(Cost-complexity) 트리가 커지는 것에 대해 패널티 계수를 설정해서 불순도와 트리가 커지는 것에 대해 복잡도를 계산하는 것
정치규칙을 종합적으로 고려해 최적의 조건값을 설정할 수 있으며 이를 하이퍼파라미터 튜닝 이라고 한다.
하이터파라미트 튜닝에는 다양한 방법론이 있다. 그 중 Best 성능을 나타내는 GridSearch 는 완전 탐색(Exhaustive Search)을 사용한다.
가능한 모든 조합 중에서 가장 우수한 조합을 찾아준다.
하지만, 완전 탐색이기 때문에 Best조합을 찾을 때까지 시간이 매우 오래 걸린다는 단점이 있다.
#모델 선언 및 훈련
from sklearn.model_selection import GridSearchCV
model = RandomForestRegressor(criterion='mse', random_state=2020)
params ={'n_estimators' : [200,300,500],
'max_features' : [5,6,8],
'min_samples_leaf' : [1,3,5]}
greedy_CY=GridSearchCV(model, param_grid=params, cv=3, n_jobs=-1)
greedy_CY.fit(X_train,Y_train)
#모델을 통해 test값 예측
pred = greedy_CY.predict(test)
#pred 값 출력
pred
submission = pd.read_csv('submission.csv 경로')
#pred 값 튜닝
import numpy as np
submission['count'] = np.round(pred, 2)
#튜닝 값 확인
submission.head()
submission.to_csv('sub.csv',index=False)
하이퍼 파라미터
- random_state : 데이터를 일정하게 나누어 섞는 파라미터(seed)를 설정하는 값
- n_estimators : 추론할 의사결정 나무 수
- max_features : 각 트리에 제공되는 최대 feature(column) 수
- min_samples_leaf : 노드를 분할한 후,리프 노드에 있어야하는 최소 샘플 수
- cv : Cross Validation 교차검증을 위해 분할되는 폴드 수
- n_jobs : 디폴트 값은 1. 이 값을 증가시키면 내부적으로 멀티 프로세스를 사용하여 그리드서치를 수행. 만약 CPU 코어의 수가 충분하다면 n_jobs를 늘릴 수록 속도가 증가. n_jobs=-1로 지정하면 컴퓨터의 모든 코어를 사용
출처
- https://dacon.io/competitions/open/235698/talkboard/403458?page=1&dtype=recent
- https://iskim3068.tistory.com/35
- https://rroundtable.github.io/FastPages/python/pointer/2019/08/03/Python-%EB%B3%80%EC%88%98%ED%95%A0%EB%8B%B9%EC%9D%98-%EA%B0%9C%EB%85%90.html
- https://lucian-blog.tistory.com/44
- https://continuous-development.tistory.com/166
'Study > Python' 카테고리의 다른 글
Python | 데이터 전처리 (0) | 2022.03.23 |
---|---|
Python | Dacon Lv3 | CV & LGBM (0) | 2022.03.21 |
Python | Dacon Lv1 | Review (0) | 2022.03.15 |
Python | Dacon Lv1 | EDA, Data Preprocessing, Modeling (0) | 2022.03.15 |
Python | Dacon 머신러닝 기초 (ipynb to html) (0) | 2022.03.14 |