Skip to content

Latest commit

 

History

History
259 lines (220 loc) · 7.91 KB

220406.md

File metadata and controls

259 lines (220 loc) · 7.91 KB

패스트캠퍼스의 강의를 정리한 것

링크

Chapter 3

Missing Value 확인 및 처리

Missing value 제거

.dropna()는 Missing value가 있는 행을 전부 삭제한다.

data.dropna()

하지만 업데이트가 되는 것은 아니기 때문에 새로 대입하거나 inplace 옵션을 true로 주면 된다.

Mssing Value를 대체

.fillna()는 missing value를 괄호 안의 값으로 대체한다.

마찬가지로 업데이트가 되는 것은 아니다.

data.fillna(35)

너무 많은 value가 missing value라면 drop을 하는 것이 낫다.

Train, Test Set 나누기

필요한 컬럼만을 사용한다.

from sklearn.model_selection import train_test_split

X = data[['Daily Time Spent on Site', 'Age', 'Area Income', 'Daily Internet Usage', 'Male']]
y = data['Clicked on Ad']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100)

20%를 테스트 데이터로 사용한다.

Logistic Regression 모델 만들고 평가하기

모델 만들기

from sklearn.linear_model import LogisticRegression

model = LogisticRegression()
model.fit(X_train, y_train)

model.coef_

array([[-6.59696436e-02, 2.66415108e-01, -1.21279185e-05,
-2.43248337e-02, 2.15771923e-03]])

예측 및 평가

from sklearn.metrics import accuracy_score, confusion_matrix

pred = model.predict(X_test)
accuracy_score(y_test, pred)

0.91

confusion_matrix(y_test, pred)
array([[93,  7],\
       [11, 89]], dtype=int64)

2x2 배열이 나옴

93과 89는 맞춘 개수, 7과 11은 틀린 개수

93은 0인데 0이라고 예측한 것들, 89는 1인데 1이라고 예측한 것들
7은 실제로는 0인데 1이라고 예측한 것들, 11은 실제로는 1인데 0이라고 예측한 것들

Unique, Value Counts

고유값의 갯수

data['Country'].nunique()

237

고유값들 전체 출력

data['Country'].unique()

array(['Tunisia', 'Nauru', 'San Marino', 'Italy', 'Iceland', 'Norway',
...

등장한 횟수

data['Country'].value_counts().head(5)
France            9
Czech Republic    9
Peru              8
Turkey            8
Greece            8
Name: Country, dtype: int64

Logistic Regression의 원리

Logistic은 이진 분류 같이 두 값으로 나뉘어 질 때 사용한다.

Binary Classification과 Confusion Matrix

Binary Classification

2가지의 값으로 분류하는 것

0과 1로 나타내며, 예측치는 %로 표현 가능

Confusion Matrix

- 0 1
0 93 7
1 12 88

아까 전의 결과를 가져온 것이다.

여기서 1행은 예측값, 1열은 실제값을 의미한다.

[0, 0]은 TN, [0, 1]은 FP, [1, 0]은 FN, [1, 1]은 TP라고 한다.

T/F는 True, False고, N/P는 Negative(0)와 Positive(1)이다.

Negative와 Positive는 예측값 기준으로 붙인 이름이다.

TN과 FP는 경우에 따라 누가 중요한지가 달라진다.

Chapter 4

KNN 알고리즘으로 고객 이탈 예측

  • 이탈 한다/ 안한다로 나뉨
  • Binary Classification

KNN의 원리

가까운 관측치를 고려해서 결정한다.

K를 얼마로 설정하느냐에 따라 분석의 결과, 모델의 결과가 크게 달라짐

모듈, 데이터 로딩 및 데이터 확인

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

data = pd.read_csv('data/churn.csv')
pd.set_option('display.max_columns', 30)
data.head()

이번 데이터는 컬럼이 21개로 너무 많아서 생략되어 보인다.

그때 set_option을 통해 해결할 수 있다.

data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7043 entries, 0 to 7042
Data columns (total 21 columns):
 #   Column            Non-Null Count  Dtype  
---  ------            --------------  -----  
 0   customerID        7043 non-null   object 
 1   gender            7043 non-null   object 
 2   SeniorCitizen     7043 non-null   int64  
 3   Partner           7043 non-null   object 
 4   Dependents        7043 non-null   object 
 5   tenure            7043 non-null   int64  
 6   PhoneService      7043 non-null   object 
 7   MultipleLines     7043 non-null   object 
 8   InternetService   7043 non-null   object 
 9   OnlineSecurity    7043 non-null   object 
 10  OnlineBackup      7043 non-null   object 
 11  DeviceProtection  7043 non-null   object 
 12  TechSupport       7043 non-null   object 
 13  StreamingTV       7043 non-null   object 
 14  StreamingMovies   7043 non-null   object 
 15  Contract          7043 non-null   object 
 16  PaperlessBilling  7043 non-null   object 
 17  PaymentMethod     7043 non-null   object 
 18  MonthlyCharges    7043 non-null   float64
 19  TotalCharges      7043 non-null   object 
 20  Churn             7043 non-null   object 
dtypes: float64(1), int64(2), object(18)
memory usage: 1.1+ MB

여기서 TotalCharges는 숫자 형태의 타입이어야 할텐데 문자형인 것을 확인할 수 있다.

그래서 아래와 같이 입력하여 데이터 타입을 바꾸려고 하면 에러가 발생한다.

pd.to_numeric(data['TotalCharges'])
ValueError: Unable to parse string " " at position 488

해당 행을 확인해보면 빈 값이지만 위의 에러를 바탕으로 봤을 때 공백 문자가 들어가 있는 것으로 추측할 수 있다.

data.iloc[488]
customerID                         4472-LVYGI
gender                                 Female
SeniorCitizen                               0
Partner                                   Yes
Dependents                                Yes
tenure                                      0
PhoneService                               No
MultipleLines                No phone service
InternetService                           DSL
OnlineSecurity                            Yes
OnlineBackup                               No
DeviceProtection                          Yes
TechSupport                               Yes
StreamingTV                               Yes
StreamingMovies                            No
Contract                             Two year
PaperlessBilling                          Yes
PaymentMethod       Bank transfer (automatic)
MonthlyCharges                          52.55
TotalCharges                                 
Churn                                      No
Name: 488, dtype: object

그러면 공백을 제거하고 타입을 바꿔주면 된다.

data['TotalCharges'] = data['TotalCharges'].replace(' ', '')

data['TotalCharges'] = pd.to_numeric(data['TotalCharges'])

data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7043 entries, 0 to 7042
Data columns (total 21 columns):
 #   Column            Non-Null Count  Dtype  
---  ------            --------------  -----  
 0   customerID        7043 non-null   object 
 1   gender            7043 non-null   object 
 2   SeniorCitizen     7043 non-null   int64  
 3   Partner           7043 non-null   object 
 4   Dependents        7043 non-null   object 
 5   tenure            7043 non-null   int64  
 6   PhoneService      7043 non-null   object 
 7   MultipleLines     7043 non-null   object 
 8   InternetService   7043 non-null   object 
 9   OnlineSecurity    7043 non-null   object 
 10  OnlineBackup      7043 non-null   object 
 11  DeviceProtection  7043 non-null   object 
 12  TechSupport       7043 non-null   object 
 13  StreamingTV       7043 non-null   object 
 14  StreamingMovies   7043 non-null   object 
 15  Contract          7043 non-null   object 
 16  PaperlessBilling  7043 non-null   object 
 17  PaymentMethod     7043 non-null   object 
 18  MonthlyCharges    7043 non-null   float64
 19  TotalCharges      7032 non-null   float64
 20  Churn             7043 non-null   object 
dtypes: float64(2), int64(2), object(17)
memory usage: 1.1+ MB

TotalCharges를 확인해 보면 데이터가 한쪽으로 치우쳐진 것을 확인할 수 있다.