Chapter6
https://www.researchgate.net/figure/Data-preprocessing-in-the-machine-learning-process_fig4_342536324
https://www.analytixlabs.co.in/blog/data-preprocessing-in-machine-learning/
sklearn의 Pipeline class는 연속된 변환 단계를 순차적으로 처리하도록 돕는 tool로, 분류(또는 예측)을 위한 새로운 수학적 algorithm이 아님.
Sklearn_pipeline의 장점
### Pipeline 사용법
# 1. data set load
import pandas as pd
df = pd.read_csv('https://archive.ics.uci.edu/ml/'
'machine-learning-databases'
'/breast-cancer-wisconsin/wdbc.data', header=None)
df.head(20)
# 2. label encode
from sklearn.preprocessing import LabelEncoder
X = df.loc[:, 2:].values
y = df.loc[:, 1].values
le = LabelEncoder()
y = le.fit_transform(y)
le.classes_
le.transform(['M', 'B'])
# 3. split data set(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.20,
stratify=y,
random_state=1)
# 4. create pipeline *** main
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
pipe_lr = make_pipeline(StandardScaler(),
PCA(n_components=2),
LogisticRegression(random_state=1))
pipe_lr.fit(X_train, y_train)
y_pred = pipe_lr.predict(X_test)
print('test accuracy: %.3f' % pipe_lr.score(X_test, y_test))
함수 설명:
1) make_pipeline(): sklearn transformers와 sklearn estimator를 연결.
2) pipeline.fit(): 순차적으로 각 변환기의 fit_transform()이 실행되고, 각 단계의 output을 그 다음 단계의 input으로 전달. 가장 마지막 단계에서는 fit() method만 호출.
3) pipeline.predict(): 매개변수로 전달된 데이터가 각 단계의 transform() method를 통과. 가장 마지막 단계에서는 변환된 데이터에 대한 예측 값 return.
https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html
https://medium.com/@mannem16/a-simple-example-of-pipeline-in-ml-and-why-do-you-need-to-learn-it-6736795df72a
https://pythonsimplified.com/what-is-a-scikit-learn-pipeline/
https://dnai-deny.tistory.com/21
https://mindsee-ai.tistory.com/61
https://gils-lab.tistory.com/70
Pipeline 사용/미사용 비교
Evaluation Metric은 일반적으로 모델이 Classification이냐 Regression이냐에 따라 다름.
구축한 모델(Classifier)의 예측 결과가 얼마나 confusion한지 보여주는 지표.
Type 1 error 와 Type 2 error 예시) 귀무가설: 메일은 스팸이 아니다’
Type 1 error: 스팸이 아닌 메일이 스팸 박스로 보내진 경우(즉, 잘못된 인정)
Type 2 error: 스팸이 맞는 메일이 스팸 박스로 보내지지 않은 경우(즉, 잘못된 부정)
전체 문제 중, 정답을 맞춘 비율.
정확도만으로는 모델의 성능을 정확하게 판단하기 어려움.
예측을 Positive로 한 대상 중, 예측 값과 실제 값이 Positive로 일치한 데이터의 비율
실제 값이 Positive인 대상 중, 예측 값과 실제 값이 Positive로 일치한 데이터의 비율.
F1 score sort of maintains a balance between the precision and recall for your classifier.
https://medium.com/analytics-vidhya/what-is-a-confusion-matrix-d1c0f8feda5
계산 예)
TP: 3 TN: 2
FP: 2 FN: 1
sensitivity = TP / (TP + FN) = 3 / (3 + 1) = 3/4 = 0.75
specificity = TN / (TN + FP) = 2 / (2 + 2) = 2/4 = 0.5
FPR = FP / (FP + TN) = 0.5
참고) TPR 과 FPR의 관계.
True: 잘된 답을 찾았음을 의미.
False: 잘못된 답을 찾았음을 의미.
Positive: 질문에 대한 답을 YES라고 했음을 의미.
ROC curve의 필요성
https://towardsdatascience.com/understanding-the-roc-curve-and-auc-dd4f9a192ecb
ROC curve 곡선 밑부분, 1에 가까울수록 성능이 좋다고 판단.
https://www.analyticsvidhya.com/blog/2020/06/auc-roc-curve-machine-learning/
https://derangedphysiology.com/main/cicm-primary-exam/required-reading/research-methods-and-statistics/Chapter%203.0.5/receiver-operating-characteristic-roc-curve
추가)
https://angeloyeo.github.io/2020/08/05/ROC.html
https://funmi.tistory.com/6
https://www.kdnuggets.com/2022/08/type-type-ii-errors-difference.html
=> 교차 검증의 목적: overfitting을 피하면서 parameter를 튜닝하고 general한 모델을 만들고 더 신뢰성 있는 모델 평가를 하기 위해.
=> Holdout cross-validation과 K-fold cross-validation은 대표적인 cross-validation 방법.
Cross-validation을 이해하기에 앞서 training set / validation set / test set에 대해 알아야 함.
train set과 test set으로만 data를 분리하면(validation set 없이), 모델을 검증하기 위해 test set만 사용하게 됨.
=> 즉, training set으로 모델을 만들고, validation set으로 parameter을 튜닝하고 사용할 모델을 선택, test set으로 선택한 모델을 최종적으로 평가.
https://modern-manual.tistory.com/19
https://www.statology.org/validation-set-vs-test-set/
https://towardsdatascience.com/train-validation-and-test-sets-72cb40cba9e7
https://wkddmswh99.tistory.com/m/10
https://for-my-wealthy-life.tistory.com/m/19
가장 기초적인 방법으로 전체 data set을 설정한 비율에 맞춰 아래와 같이 나누는 것.
1) train set : test set
2) train set : validation set : test set
K개의 fold를 만들어서 진행하는 cross-validation(즉, k개의 data set을 구성하고 각각 학습).
The algorithm of the k-Fold technique
1) Pick a number of folds – k. Usually, k is 5 or 10 but you can choose any number which is less than the dataset’s length.
2) Split the dataset into k equal (if possible) parts (they are called folds)
3) Choose k – 1 folds as the training set. The remaining fold will be the test set
4) Train the model on the training set. On each iteration of cross-validation, you must train a new model independently of the model trained on the previous iteration
5) Validate on the test set
6) Save the result of the validation
7) Repeat steps 3 – 6 k times. Each time use the remaining fold as the test set. In the end, you should have validated the model on every fold that you have.
8) To get the final score average the results that you got on step 6.
K-fold Cross Validation의 변형된 방식으로 data가 편항되어 있는 경우(즉, imbalanced data의 경우) 사용됨.
Leave-one-out сross-validation (LOOCV) is an extreme case of k-Fold CV. Imagine if k is equal to n where n is the number of samples in the dataset. Such k-Fold case is equivalent to Leave-one-out technique.
Recommended approach for working with vert small data sets.
https://neptune.ai/blog/cross-validation-in-machine-learning-how-to-do-it-right
https://blog.naver.com/winddori2002/221850530979
parameter와 hyper parameter의 차이.
parameter: A model parameter is a configuration variable that is internal to the model and whose value can be estimated from data.
hyper parameter: A model hyperparameter is a configuration that is external to the model and whose value cannot be estimated from data.
=> 사용자가 직접 설정하면 하이퍼 파라미터, 모델 혹은 데이터에 의해 결정되면 파라미터
https://machinelearningmastery.com/difference-between-a-parameter-and-a-hyperparameter/
Grid search의 경우 hyper parameter의 후보군이 될 수 있는 값들을 바탕으로 경우의 수를 전부 따지기 때문에 후보군이 많을 수록, 시간이 오래 걸림. 속도면에서 장점이 있는 Randomized search 방법이 있음.
n_iter: Number of parameter settings that are sampled
https://cori.tistory.com/167
http://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf
참고)
Halving Grid seach
https://bobrupakroy.medium.com/halving-gridsearch-736b13898327
Bayesian Optimization
https://shinminyong.tistory.com/37
https://data-scientist-brian-kim.tistory.com/88
https://vitalflux.com/python-nested-cross-validation-algorithm-selection/
Outer loop 각각의 fold는 train set과 test set으로 구성되어 있음. 여기서, train set에 Inner loop가 작동함. Inner loop는 train set(Outer loop에 있는)을 train set’과 validation set으로 분리한 뒤, 평가 과정을 통해 parameter를 튜닝. 그 후 Optimal한 parameter를 찾고 이 optimal한 parameter을 통해 outer loop의 test set을 평가. 이 과정을 k번 반복(k-fold).
=> 요약하면, inner loop는 각 fold의 parameter를 튜닝하고 outer loop는 test set에 대한 평가.
=> nested cross-validation은 각 fold에 맞는 optimal한 parameter가 적용된 여러 test set의 평가 정보를 바탕으로 보다 일반화된 model을 구하고자 함.
class가 imbalance한 데이터를 그대로 ML model에 적용하면 안됨(예, y=1이 전체 데이터의 90%, y=0가 10%인 불균형한 데이터가 주어졌을 때, 항상 y=1로 분류하는 model의 정확도는 90%).
Class imbalance 해소 방법.
1) downsampling the majority class
2) upsampling the minority class
3) the generation of symthetic training examples.
This is an excellent and detailed guide for aspiring Python developers! Python’s versatility, especially in fields like data science training in Delhi and AI, makes it a must-learn skill. Courses like 360 Data Science provide comprehensive learning, while data analytics courses in Gurgaon help professionals specialize further. The demand for Python across industries ensures great career opportunities for learners!
Visit our site - https://www.trainingya.com