로지스틱 회귀에 대해서

로지스틱 회귀는, 분류를 위한 알고리즘입니다. (예: 전자기기를 고장내는 클래스 or 고장내지 않는 클래스로 나눈다).

단순한 알고리즘이므로 구현하기 편하지만, 특징량 공간 (독립변수가 되는 데이터가 있는 공간) 이 선형분리 가능한 경우만 높은 성능을 발휘합니다.

선형분리 가능이라는 것은, 독립변수가 2차원 평면상에 있다고 하면, 어느 클래스에 대응하는 독립변수 (의 값의 집합) 과, 다른 클래스에 대응하는 독립변수(의 값의 집합)을, 하나의 선을 그어 사이에 두는 것이 가능한 것을 말합니다.

로지스틱 회귀에서는, 로짓(logit)을 독립변수의 선형 합으로 표시합니다.

예측하고 싶은 것 (정사상)의 확률을 p로 했을 때, 확률은 p/((1-−p))라고 쓸 수 있고, 정상형의 일어나기 쉬움을 표현합니다.

오즈(odds)의 로그를 취한 것이, 로짓(logit)입니다.

1
2
3
from IPython.display import Image  # 주피터 노트북에 이미지 삽입
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211126_190246_1.png")

output_1_0

가중치 w0은 x0 =1로서 절편을 표시합니다.

로지스틱 회귀는, 로짓(logit)과 복수의 독립변수의 관계를 표현하는 모델의 가중치 Wi를 학습하는 것이 목적입니다.

다만, 로지스틱 회귀를 이용할 때에 관심이 있는 것은, 독립변수의 값을 부여했을 때의 정사상의 확률 p입니다.

여기서, 위의 식을 좌변이 p가 되도록 변형하면,

1
2
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211126_194304_1.png")

output_3_0

위 공식 시그모이드 함수 (로지스틱 함수의 일종)

1
2
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211126_200256_1.png")

output_5_0

  • 위 그래프처럼 0과 1 사이에 집약되어 있고 그 모양이 S 형태를 띄기 때문에 Sigmoid라는 이름이 붙는다.

  • 합격/불합격을 분류한 데이터를 학습 > 시그모이드 함수 > x값을 넣으면 y 값은 0~1 사이의 확률로 예측됨

선형회귀로 풀 수 없는 문제가 있다면?

  • 로지스틱 회귀는 두 개의 카테고리로 분류되는 범주형 데이터를 예측할 때 적합하다.

  • ex. 합격/불합격, 높음/낮음, 정답/오답 등

오즈비 vs 로짓변환

오즈비(Odds ratio) : 0(실패)에 대한 1(성공)의 비율 ( 0 : no, 1 : yes )

  • no인 상태와 비교하여 yes가 얼마나 높은지 낮은지 정량화한 것

  • 오즈비 = p (success) / 1-p (fail)

  • p : y=1이 나올 확률, 1-p : y=1의 여사건

로짓(logit) 변환

  • 오즈비에 log 함수 적용한 것

  • 로짓 = log( p / 1-p )

=> 로짓을 대상으로 회귀분석을 적용한 것이 로지스틱 회귀분석(Logistic Regression Analysis)

1
2
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211126_202845_1.png")

![output_90](https://drive.google.com/uc?export=view&id=1AhM-TKkcxIAtMY7hvRGn-BhGA3VrJ5k)

1
2
3
# sigmoid 함수 예제
def model(self,x):
        return 1/(1+np.exp(-x))

아래 코드 에서 나오듯 이항 분류의 식으로 sigmoid(‘coef_*X+intercept_‘)를 사용한 것이다.

1
2
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211126_202948_1.png")

output_12_0

학습결과

1
2
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211126_203504_1.png")

output_14_0

1
2
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211126_203504_2.png")

output_15_0

로지스틱 회귀 모델

Scikit-learn으로 로지스틱 회귀를 하는 것은, linear_model의 LogisticRegression모델 (공식 문서 : https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html )를 사용합니다.

주로 이용하는 메소드는 아래와 같습니다.

fit 메소드 : 로지스틱 회귀 모델의 가중치를 학습

predict 메소드 : 독립변수의 값으로부터 클래스를 예측

  • from sklearn.linear_model import LogisticRegression # 모델 생성

실습 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'''
문) load_wine() 함수를 이용하여 와인 데이터를 다항분류하는 로지스틱 회귀모델을 생성하시오.
  조건1> train/test - 7:3비울
  조건2> y 변수 : wine.data
  조건3> x 변수 : wine.data
  조건4> 모델 평가 : confusion_matrix, 분류정확도[accuracy]
'''

from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics




1
2
3
# 1. wine 데이터셋
wine = load_wine()
print(wine)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{'data': array([[1.423e+01, 1.710e+00, 2.430e+00, ..., 1.040e+00, 3.920e+00,
        1.065e+03],
       [1.320e+01, 1.780e+00, 2.140e+00, ..., 1.050e+00, 3.400e+00,
        1.050e+03],
       [1.316e+01, 2.360e+00, 2.670e+00, ..., 1.030e+00, 3.170e+00,
        1.185e+03],
       ...,
       [1.327e+01, 4.280e+00, 2.260e+00, ..., 5.900e-01, 1.560e+00,
        8.350e+02],
       [1.317e+01, 2.590e+00, 2.370e+00, ..., 6.000e-01, 1.620e+00,
        8.400e+02],
       [1.413e+01, 4.100e+00, 2.740e+00, ..., 6.100e-01, 1.600e+00,
        5.600e+02]]), 'target': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2]), 'frame': None, 'target_names': array(['class_0', 'class_1', 'class_2'], dtype='<U7'), 'DESCR': '.. _wine_dataset:\n\nWine recognition dataset\n------------------------\n\n**Data Set Characteristics:**\n\n    :Number of Instances: 178 (50 in each of three classes)\n    :Number of Attributes: 13 numeric, predictive attributes and the class\n    :Attribute Information:\n \t\t- Alcohol\n \t\t- Malic acid\n \t\t- Ash\n\t\t- Alcalinity of ash  \n \t\t- Magnesium\n\t\t- Total phenols\n \t\t- Flavanoids\n \t\t- Nonflavanoid phenols\n \t\t- Proanthocyanins\n\t\t- Color intensity\n \t\t- Hue\n \t\t- OD280/OD315 of diluted wines\n \t\t- Proline\n\n    - class:\n            - class_0\n            - class_1\n            - class_2\n\t\t\n    :Summary Statistics:\n    \n    ============================= ==== ===== ======= =====\n                                   Min   Max   Mean     SD\n    ============================= ==== ===== ======= =====\n    Alcohol:                      11.0  14.8    13.0   0.8\n    Malic Acid:                   0.74  5.80    2.34  1.12\n    Ash:                          1.36  3.23    2.36  0.27\n    Alcalinity of Ash:            10.6  30.0    19.5   3.3\n    Magnesium:                    70.0 162.0    99.7  14.3\n    Total Phenols:                0.98  3.88    2.29  0.63\n    Flavanoids:                   0.34  5.08    2.03  1.00\n    Nonflavanoid Phenols:         0.13  0.66    0.36  0.12\n    Proanthocyanins:              0.41  3.58    1.59  0.57\n    Colour Intensity:              1.3  13.0     5.1   2.3\n    Hue:                          0.48  1.71    0.96  0.23\n    OD280/OD315 of diluted wines: 1.27  4.00    2.61  0.71\n    Proline:                       278  1680     746   315\n    ============================= ==== ===== ======= =====\n\n    :Missing Attribute Values: None\n    :Class Distribution: class_0 (59), class_1 (71), class_2 (48)\n    :Creator: R.A. Fisher\n    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\n    :Date: July, 1988\n\nThis is a copy of UCI ML Wine recognition datasets.\nhttps://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data\n\nThe data is the results of a chemical analysis of wines grown in the same\nregion in Italy by three different cultivators. There are thirteen different\nmeasurements taken for different constituents found in the three types of\nwine.\n\nOriginal Owners: \n\nForina, M. et al, PARVUS - \nAn Extendible Package for Data Exploration, Classification and Correlation. \nInstitute of Pharmaceutical and Food Analysis and Technologies,\nVia Brigata Salerno, 16147 Genoa, Italy.\n\nCitation:\n\nLichman, M. (2013). UCI Machine Learning Repository\n[https://archive.ics.uci.edu/ml]. Irvine, CA: University of California,\nSchool of Information and Computer Science. \n\n.. topic:: References\n\n  (1) S. Aeberhard, D. Coomans and O. de Vel, \n  Comparison of Classifiers in High Dimensional Settings, \n  Tech. Rep. no. 92-02, (1992), Dept. of Computer Science and Dept. of  \n  Mathematics and Statistics, James Cook University of North Queensland. \n  (Also submitted to Technometrics). \n\n  The data was used with many others for comparing various \n  classifiers. The classes are separable, though only RDA \n  has achieved 100% correct classification. \n  (RDA : 100%, QDA 99.4%, LDA 98.9%, 1NN 96.1% (z-transformed data)) \n  (All results using the leave-one-out technique) \n\n  (2) S. Aeberhard, D. Coomans and O. de Vel, \n  "THE CLASSIFICATION PERFORMANCE OF RDA" \n  Tech. Rep. no. 92-01, (1992), Dept. of Computer Science and Dept. of \n  Mathematics and Statistics, James Cook University of North Queensland. \n  (Also submitted to Journal of Chemometrics).\n', 'feature_names': ['alcohol', 'malic_acid', 'ash', 'alcalinity_of_ash', 'magnesium', 'total_phenols', 'flavanoids', 'nonflavanoid_phenols', 'proanthocyanins', 'color_intensity', 'hue', 'od280/od315_of_diluted_wines', 'proline']}
1
print(wine.target)
1
2
3
4
5
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
1
2
3
4
5
6
7
8
9
# 2. 변수 선택
wine_x = wine.data # x변수
wine_y = wine.target # y변수

# 3. train/test split(7:3)
x_train, x_test, y_train, y_test = train_test_split(
        wine_x, wine_y, test_size=0.3, random_state=123)


1
2
x_train.shape # (124, 13)
y_train.shape # (124,)
1
(124,)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 4. model 생성  : solver='lbfgs', multi_class='multinomial'
model = LogisticRegression(solver='lbfgs', multi_class='multinomial')
model.fit(X = x_train, y=y_train)

model.coef_ # 기울기 : x변수
model.intercept_ # 절편 : [-0.0417784 ,  0.09551054, -0.05373213] - y변수
model.score(X=x_train, y=y_train) # 분류정확도 점수


# 5. 모델 평가 : accuracy, confusion matrix
y_pred = model.predict(x_test)

acc = metrics.accuracy_score(y_test, y_pred)

con_mat = metrics.confusion_matrix(y_test, y_pred)

acc # 0.9629629629629629
con_mat





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
C:\Users\MyCom\anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(





array([[13,  1,  0],
       [ 0, 18,  0],
       [ 0,  1, 21]], dtype=int64)

Meta Info

Categories: ,

Published At:

Modified At:

Leave a comment