머신러닝

Logistic Regression의 개념과 구매 여부 분류 하기

728x90

Logistic Regression이란? 

빨간점은 데이터이고, 액션의 0과 1은 y값, 레이블이다.

y값이 있다는것은 곧 supervised leaning이란 뜻이다.

 

위의 그래프와 비슷하게 생긴 Sigmoid함수가 존재한다.

linear Regression 의 식을 Sigmoid에 대입하여 일차방정식으로 만들면 다음과 같아진다.

 

위와 같은 식을 가진 regression을 Logistic Regression이라 한다.

 

Logistic Regression을 통해 구매할지 안 할지, 클릭을 할 지 안 할지 여러가지 조건들을 확률로 나타낼 수 있다.

p는 확률값을 나타낸다.

위의 시그모이드 함수를 적용한 그래프를 보면 20대는 클릭할 확률이 0.7%, 40대는 85%, 50대는 99.4%이다.

최종 예측 값은, 0.5를 기준으로 두 개의 부류로 나눈다. 그 값은 0 과 1 이다.

 

기준점 = Threshord

 

Logistic Regression으로 나이대와 연봉 정보를 통해 물건의 구매 여부를 예측해보겠다.

 

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
df= pd.read_csv('Social_Network_Ads.csv') #Social_Network_Ads.csv 불러오기 불러오기

df.head() # df 컬럼 및 앞부분 내용 확인하기df 컬럼 및 앞부분 내용 확인하기
df.isna().sum() # Nan 데이터 여부 확인하기

X = df.iloc[:,2:3+1] # X 로 
X.head()

y =df['Purchased'] 
y.head()

Feature Scaling 시행

sc = StandardScaler()
X = sc.fit_transform(X)
X

 

학습을 위해 training set와 test set나누기.

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

#shape 확인
X.shape
X_train.shape
X_test.shape

classifier = LogisticRegression(random_state = 0)

classifier.fit(X_train, y_train) #학습
y_pred = classifier.predict(X_test)
y_pred

y_test.values

confusion metrics로 성능을 검증해본다.

confusion_matrix(y_test, y_pred)

(57+17)/cm.sum() # = 0.925             ## 정확도
 17/(1+17) # = 0.9444444444444444      ## 정밀도
 17/(5+17) # = 0.7727272727272727      ## 적중률

 

예측을 해봅시다.

36세에 38000달러를 버는 사람은 구매를 할까요 안할까요?

new = np.array([36,38000]).reshape(1,-1)

new

new1 = sc.transform(new)
y_pred1 = classifier.predict(new1)
y_pred1

안산다 라는 결과를 도출할 수 있다. 

728x90

'머신러닝' 카테고리의 다른 글

SVM - Support Vector Machine  (0) 2021.04.01
K-NN  (0) 2021.04.01
Multiple_Linear_Regression으로 회사의 이익 예측하기  (0) 2021.03.28
Linear_Regression  (0) 2021.03.26