220615(수) TIL

재은·2022년 6월 15일
0

멋사 AI 6기

목록 보기
1/36

오늘 뭘 했니?

회귀를 사용하여 인슐린이 0인 값 예측(어제는 당뇨병 예측)
교차검증 cross validation으로 오차 측정하고 평가
회귀의 평가방법(MAE, MAPE, MSE, RMSE, R square score)
실습파일: 0603-pima-regression-input.ipynb

하이퍼파라미터 튜닝으로 모델의 성능 개선하기(수동튜닝, GridSearchCV, RandomizedSearchCV )
실습파일: pima-parameter-tunning-input.ipynn

뭘 배웠니?(new)

  • 파라메터 튜닝은 가장 마지막에 하는 편

하이퍼파라미터 튜닝

하이퍼 파라미터 최적화

알고리즘의 하이퍼 파라미터 값을 지정하고 지정 된 값 중 좋은 성능을 내는 파라미터를 찾는 과정
모델의 성능을 개선

교차검증(Cross Validation)

  • 교차검증은 모의고사다!
# model_selection의 cross_val_predict 로 cv 로 조각을 나눠 valid 데이터의 학습결과 측정하기
from sklearn.model_selection import cross_val_predict
cross_val_predict(model, X_train, y_train, cv=5, n_jobs=-1)
  • cv 조각의 갯수
    즉, cv=5라고 하면 split당 4/5데이터로 훈련하고 1/5로 검증하는 것
  • n_jobs=-1 사용할 코어의 갯수 -1은 전체
  • verbose 로그 진행 과정 찍을려
    • verbose=0(default)면 메시지 출력 안함
    • verbose=1이면 간단한 메시지 출력
    • verbose=2이면 하이퍼 파라미터별 메시지 출력
  • 교차검증의 과정
  • fold 잘게 나누면 나눌수록
  • split은모델의 성능을 정확하게 평가하기 위한 목적임
    자체가 모델의 성능이 올라가는건 아님.
  • residplot 의 잔차(오차값) 실제값과 얼마나 차이 나나 볼 때 유용
    실제값과는 좀 차이가 있긴하대 why,..?
  • facetgrid 서브플롯으로 그린거다

Grid Search 그리드서치

  • 지정된 구간에 대한 값에 대해서 탐색
  • 지정해 준 값 그대로 격자형태로 값찾는다
from sklearn.model_selection import GridSearchCV
max_depth_list=[2,3,5,7,9,10]
max_features_list = [0.4, 0.5, 0.6]
parameters = {'max_depth':max_depth_list, 'max_features':max_features_list}
clf = GridSearchCV(model, param_grid=parameters,n_jobs=-1,scoring="accuracy", cv=3)
clf.fit(X_train, y_train)

#베스트점수
clf.best_score_

#베스트 파라미터
clf.best_estimator_

#결과 데이터프레임으로 보기
pd.DataFrame(clf.cv_results_)
  • clf.bestscore
  • clf.bestestimator
  • pd.DataFrame(clf.cvresults)
#랜덤하게 파라미터 값 주고 싶을 떄는 np.random 사용
max_depth_list = np.random.randint(2,7,5)
max_features_list = np.random.uniform(0.3,0.7,5)
# GridSearchCV 없이 하는 법;
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_predict

max_depth_list=[2,3,5,7,9,10]
max_features_list = [0.4, 0.5, 0.7, 0.8, 0.9, 1]

accuracy_list=[]
for max_depth in max_depth_list:
    for max_features in max_features_list:
        acc_list = []
        model = DecisionTreeClassifier(max_depth=max_depth, max_features=max_features, random_state=42)
        y_predict = cross_val_predict(model, X_train, y_train, cv=3, n_jobs=-1)
        acc = (y_train == y_predict).mean()
        
        acc_list.append(max_depth)
        acc_list.append(max_features)
        acc_list.append(acc)
    #     print(f"max_depth : {max_depth}, max_feature: {max_feature},acc:{acc}")
        accuracy_list.append(acc_list)

df_acc = pd.DataFrame(accuracy_list, columns=["max_depth", "max_features", "accuracy"])
df_acc.nlargest(5, "accuracy")

Random Search 랜덤서치

  • 지정된 구간 외에 최적 값이 있을 때 그리드 서치로 찾지 못하는 단점을 보완하여 랜덤한 값들을 지정하여 성능을 평가하고 그 중 가장 좋은 성능을 나타내는 파라미터를 찾음. 좋은 성능을 내는 구간으로 점점 좁혀가며 파라미터를 찾음

max_depth_list = np.random.uniform(2,7,10)
max_depth_list = np.unique(max_depth_list)
max_features_list = np.random.uniform(0.3, 0.7, 5)

from sklearn.model_selection import RandomizedSearchCV

param_distributions = {"max_depth":max_depth_list, "max_features":max_features_list}
clf = RandomizedSearchCV(model_selection, param_distributions,n_iter=5, cv=3,
                        n_jobs=-1, verbose=2,)

distributions = 파람 지정

n_iter

회귀의 평가 방법

  • r2_score 기울기 구하는 것
    1에 가까울수록 정확함
  • 비즈니스에 따라 사용하는 알고리즘 다름
# 오차값 구하기
# 실제값-예측값
error = y_train - y_valid_predict

#오차의 절대값 구하고 describe 보기/ 평균이나 편차 등 보게
abs(error).describe()

뒤에서부터 읽으면 쉽지롱

mae, mse, rmse가 많이 쓰임

  • MAE(Mean Absolute Error) 평균절대오차
    error (실제값과 예측값의 차이)에 Absolute(절대값) 하고 Mean(평균)
# 예측값과 실제값의 차이에 대한 절대값의 평균
# mae
error = y_train-y_valid_predict
mae = abs(error).mean()
mae

mape 는 demand data에 0값이 있을경우 사용불가

  • MAPE(Mean Absolute Percentage Error)
    절대값에 대한 평균
    ```python
    # (실제값 - 예측값 / 실제값)의 절대값에 대한 평균
    # mape
    error=y_train - y_valid_predict
    mape = abs(error/y_train).mean()
    mape
    ```
  • MSE (Mean Squared Error)
    # 실제값 - 예측값의 차이의 제곱의 평균
    # MAE와 비슷해 보이나 제곱을 통해 음수를 양수로 변환함
    # 분산과 유사한 공식
    # square() 제곱
    error = y_train-y_valid_predict
    mse = np.square(error).mean()
    mse
  • RMSE (Root Mean Squared Error)
    # MSE에
    # sqrt() 제곱근(square-root) 
    rmse = np.sqrt(mse)
    rmse
    

nunique 값이 작은 건 범주로 볼 가능성 높 ex 0아니며 1

label 제거하고 feature에 넣기 컬럼명을 리스트로 가져오고 사용하지 않을 컬럼을 제거

홀덥벨리데이션? 빠르게 측정가넝

holdout?

  • train_test_split
# train_test_split 으로 무작위로 데이터셋을 train 과 test 로 나눕니다.
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,
stratify=y, random_state=42)
#stratify 데이터 균형있게 노나줌

# 데이터의 행과 열의 개수를 확인합니다.
X_train.shape, X_test.shape, y_train.shape, y_test.shape

staratify 층화표집 : 데이터를 클래스별로 균형있게 노나줌

부족한 것

cv 교차검증의 과정 다시 이해하기

jointplot, residplot

  • residplot 의 잔차(오차값) 실제값과 얼마나 차이 나나 볼 때 유용
    실제값과는 좀 차이가 있긴하대 why,..?

분산에 루트 씌운게 표준편차임

mse 오차의 분산의 정도

rmse 표준편차

싸이파이는 뭐더라..


  • 나머지공부ㅠㅠ

편차 = 변량-평균

분산 = 편차 제곱의 평균

n_iter?

오늘 배운 것들이 어렵더라도, 콩나물에 물을 주듯 계속 상기시켜보세요
나중에 면접 준비를 따로 할 필요가 없을 거에요
오늘 배웠던 교차검증이나, metrics(평가지표), 하이퍼 파라미터 튜닝에 대해 정리해보시는 게 정말 도움이 많이 될 거 같아요

3F

사실(Fact) : 회귀모델을 사용해봤고 교차검증 cross validation으로 오차 측정하고 평가했으며
회귀의 평가방법(MAE, MAPE, MSE, RMSE, R square score)에 대해 배웠다.
하이퍼파라미터 튜닝으로 모델의 성능 개선하는 법에 대해 배웠다.(수동튜닝, GridSearchCV, RandomizedSearchCV )
느낌(Feeling) : 혼돈의 카오스 그자체. 많이 접해보고 익숙해지는 법 밖엔 없겠지
교훈(Finding) : 매니저님이 말씀하신 것 처럼 콩나물에 물을 주듯… 자라나라 머리머리

profile
데린이여요

0개의 댓글