오답노트
[ML] 로지스틱 회귀 모델링 - LogisticRegression 본문
# 라이브러리 호출
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import *
# 데이터 read
path = "Attrition_simple2.CSV"
data = pd.read_csv(path)
data.head()
# 불필요 데이터 삭제
data.drop('EmployeeNumber', axis = 1, inplace = True)
# 타겟 선언 및 target, feature 분리
target = 'Attrition'
x = data.drop(target, axis = 1)
y = data.loc[:, target]
# 가변수화
cat_cols = ['Gender','JobSatisfaction','MaritalStatus','OverTime']
x = pd.get_dummies(x, columns = cat_cols, drop_first = True)
# train 데이터 , validation 데이터 분리
x_train, x_val, y_train, y_val = train_test_split(x, y, test_size = .3, random_state = 2022)
# 모델링 및 예측
model = LogisticRegression()
model.fit(x_train,y_train)
pred = model.predict(x_val)
# 로지스틱 해석
print(list(x))
print(model.coef_)
'''
['Age', 'DistanceFromHome', 'MonthlyIncome', 'PercentSalaryHike', 'TotalWorkingYears',
'Gender_Male', 'JobSatisfaction_2', 'JobSatisfaction_3', 'JobSatisfaction_4',
'MaritalStatus_Married', 'MaritalStatus_Single', 'OverTime_Yes']
array([[-3.93412690e-02, 3.78546332e-02, -6.12306070e-05,
-2.74992213e-02, -4.30054246e-02, 2.30777605e-01,
-2.19177781e-01, -1.05323122e-01, -3.12101843e-01,
-4.12848207e-01, 8.42849707e-01, 1.27030048e+00]])
'''
#모델 평가
print(confusion_matrix(y_val, pred))
'''
array([[293, 7],
[ 45, 14]], dtype=int64)
'''
print(accuracy_score(y_val,pred))
print(recall_score(y_val,pred))
print(precision_score(y_val,pred))
print(f1_score(y_val,pred))
'''
0.8551532033426184
0.23728813559322035
0.6666666666666666
0.35
'''
print(classification_report(y_val,pred))
'''
precision recall f1-score support
0 0.87 0.98 0.92 300
1 0.67 0.24 0.35 59
accuracy 0.86 359
macro avg 0.77 0.61 0.63 359
weighted avg 0.83 0.86 0.83 359
'''
위 코드중 모델 평가 부분을 보면
confusion_matrix 함수로 모델의 confusion matrix를 확인할수 있다
또 Accuracy, Recall, Precision, f1-score를 확인할 수 있는 함수가 존재한다.
이 수치들을 한번에 볼 수 있는 classification_report 함수는 위 수치들을 소수점 둘째자리 까지 표시한다.
관심 예측 결과에 대해서 Recall, Precision, f1-score 수치와 accuracy 를 확인 하면 된다.
수치가 클 수록 모델의 성능이 좋다고 할 수 있다.
'Python > ML' 카테고리의 다른 글
[ML] 의사결정 트리 (Decision Tree) (0) | 2022.08.24 |
---|---|
[ML] KNN - KNeighborsClassifier (0) | 2022.08.23 |
[ML] 범주형 데이터 모델 평가 방법 (0) | 2022.08.23 |
[ML] 로지스틱 회귀(Logistic Regression) (0) | 2022.08.23 |
[ML] KNN - KNeighborsRegressor (0) | 2022.08.23 |