donut

'Classification'에 해당되는 글 1건

  1. Python Logistic Regression

Python Logistic Regression

Tensorflow/ML

 

 

 

Logistic_Regression(Classification)

로지스틱 회귀(분류)

안녕하세요. 이번 포스팅은 로지스틱 회귀에대해 포스팅을 진행하겠습니다.
로지스틱 회귀란 = 독립 변수의 선형 결합을 이용하여 사건의 발생 가능성을 예측하는 통계기법(출처 나무위키)

흔히 로지스틱 회귀는 종속변수가 2개(이항, boolean, True or False)인경우를 말하며, 이를 Classification 분류 기법이라고 한다.

종속변수가 2개이상일 경우 다항로지스틱 회귀라고 한다.(Multinormial logisitic regression).

이번 포스팅은 Classification에 관한 포스팅입니다.

필요한 모듈 세팅 및 tensorflow버전 확인

In [1]:
import numpy as pn
import matplotlib.pyplot as plt
import tensorflow as tf

tf.random.set_seed(0)
print(tf.__version__)
 
2.1.0
 

데이터 세팅

In [2]:
#x1, x2를 각각 x_train의 2차원배열로 정의해줍니다.
x_train = [[1., 6.],
          [2., 5.],
          [3., 4.],
          [4., 3.],
          [5., 2.],
          [6., 1.]]

#각 배열의 도출 값을 선언합니다.
#1,6 -> 0
#6,1 -> 1

y_train = [[0.],
          [0.],
          [0.],
          [1.],
          [1.],
          [1.]]
In [5]:
#데이터 확인
print(x_train, y_train)
 
[[1.0, 6.0], [2.0, 5.0], [3.0, 4.0], [4.0, 3.0], [5.0, 2.0], [6.0, 1.0]] [[0.0], [0.0], [0.0], [1.0], [1.0], [1.0]]
 

테스트 할 데이터 세팅

In [36]:
#test할 데이터를 세팅해 줍니다.
#2,6이 1인지 확인하기 위합니다.
x_test = [[2.,6.]]
y_test = [[0.]]
In [37]:
x_test,y_test
Out[37]:
([[2.0, 6.0]], [[0.0]])
 

x값 할당해 주기

x_train에 있던 값들을 각각 x1, x2로 할당해 주겠습니다. 이때, 리스트 형식으로 할당해 주는데요,
복습차원에서 리스트 컴프리헨션과, append방법 두가지를 활용해 보겠습니다.

In [38]:
x1 = [x[0] for x in x_train]
x1
Out[38]:
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
In [39]:
x1=[]
for x in range(len(x_train)):
    x1.append(x_train[x][0])
x1
Out[39]:
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
In [40]:
x2 = [x[1] for x in x_train]
x2
Out[40]:
[6.0, 5.0, 4.0, 3.0, 2.0, 1.0]
In [41]:
x2=[]
for x in range(len(x_train)):
    x2.append(x_train[x][1])
x2
Out[41]:
[6.0, 5.0, 4.0, 3.0, 2.0, 1.0]
 

데이터 그래프로 확인하기

현재까지 할당된, 데이터를 그래프에서 확인해 보겠습니다.
데이터각각에 색을 입혀줄껀데요, 이것도 역시 리스트컴프리헨션을 복습하겠습니다.

In [42]:
colors = []
for y in range(len(y_train)):
    colors.append(int(y_train[y][0]))
colors
Out[42]:
[0, 0, 0, 1, 1, 1]
In [43]:
colors = [int(y[0]) for y in y_train]
colors
Out[43]:
[0, 0, 0, 1, 1, 1]
In [44]:
#0은 보라색, 1은 노란색으로 표시가 됩니다.
colors = [int(y[0]) for y in y_train]

#x1, x2에 해당되는 값들은 삼각형으로 표시
plt.scatter(x1,x2, c= colors, marker='^')

#제가 찾고자 했던 x_test값 (2,6)은 빨간색으로 표시했습니다.
plt.scatter(x_test[0][0], x_test[0][1], c='red')

plt.xlabel("x1")
plt.ylabel("x2")
plt.show()
 
 

Logistic Classification모델 만들기

In [93]:
#dataset 만들기
#학습시킬 값을 dataset에 담아준다.
dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset
Out[93]:
<TensorSliceDataset shapes: ((2,), (1,)), types: (tf.float32, tf.float32)>
 

dataset 살펴보기

현재 dataset은 6슬라이스로 이루어져 있다.
1슬라이스 => [1,6],[0]
2슬라이스 => [2,5],[0] ....

In [95]:
#리스트 컴프리헨션
elem = [i for i in dataset]
print(elem)
print(len(elem))
 
[(<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1., 6.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 5.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([3., 4.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([4., 3.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([5., 2.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([6., 1.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>)]
6
In [96]:
#append로 확인하기
elem2= []
for i in dataset:
    elem2.append(i)
print(elem2)
len(elem2)
 
[(<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1., 6.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 5.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([3., 4.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([4., 3.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([5., 2.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([6., 1.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>)]
Out[96]:
6
 

W, b 할당해 주기

W,b초기값을 할당해 줍니다. x가 x1,x2 2개의 변수였기 때문에 W는 2행1열의 배열을 선언해준다.
b는 1행 1열로 선언해 준다.

In [105]:
#초기값을 tf.random.normal로 설정해주기
W = tf.Variable(tf.random.normal((2, 1)))
b = tf.Variable(tf.random.normal((1,)))
print(W.numpy(),b.numpy())
 
[[-2.1278012 ]
 [ 0.42648628]] [-1.4933363]
In [111]:
#초기값을 tf.zeros로 설정해 주기
W = tf.Variable(tf.zeros([2,1]), name= 'weight')
b = tf.Variable(tf.zeros([1]), name='bias')
print(W.numpy(),b.numpy())
 
[[0.]
 [0.]] [0.]
 

시그모이드 함수 구현

In [106]:
def logistic_regression(features):
    hypothesis = tf.divide(1., 1. + tf.exp(tf.matmul(features, W) + b))
    return hypothesis
    
 

cost 함수 구현, 러닝레이트 선언

In [107]:
def loss_fn(hypothesis, features, labels):
    cost = -tf.reduce_mean(labels * tf.math.log(logistic_regression(features)) + (1-labels) * tf.math.log(1-hypothesis))
    return cost
optimizer = tf.keras.optimizers.SGD(learning_rate =0.01)
 

결과값 도출 함수 구현

시그모이드 함수로 도출된 hypothesis를 0 or 1로 cast해준다.

tf.cast => 조건이 참일경우 1, 거짓일 경우 0출력
tf.equal => 주어인 값이 같은경우 True, 다를경우 False
아래는 cast와 equal를 이해하기 쉽도록 예시를 작성 하였습니다.

In [119]:
test1 = 0.3
test2 = tf.cast(test1 > 0.5,dtype = tf.float32)
test2.numpy()
Out[119]:
0.0
In [129]:
test1 = 0.6
test2 = tf.cast(test1 > 0.5,dtype = tf.float32)
test2.numpy()
Out[129]:
1.0
In [130]:
test1 = 0.6
test2 = 0.6
test3 = tf.equal(test1,test2)
test3.numpy()
Out[130]:
True
In [131]:
test4 = 0.5
test5 = 0.6
test6 = tf.equal(test4,test5)
test6.numpy()
Out[131]:
False
In [136]:
test7 = tf.cast(tf.equal(test1,test2),dtype = tf.float32)
test7.numpy()
Out[136]:
1.0
In [137]:
test8 = tf.cast(tf.equal(test4,test5),dtype = tf.float32)
test8.numpy()
Out[137]:
0.0
In [141]:
def accuracy_fn(hypothesis, labels):
    predicted = tf.cast(hypothesis > 0.5, dtype =tf.float32)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, labels),dtype =tf.int32))
    return accuracy
 

경사하강법(미분)

In [142]:
def grad(features, labels):
    with tf.GradientTape() as tape:
        loss_value = loss_fn(logistic_regression(features),features,labels)
        return tape.gradient(loss_value, [W,b])
    
 

반복 및 결과 값 도출

어큐러시가 1이 나왔음으로,
위에서 제시했던 test값은 참임

In [144]:
#반복 횟수 선언
EPOCHS = 1001

for step in range(EPOCHS):
    #dataset을 몇 묶음씩 학습 시킬 것인지 정해준다
    #batch size를 선언해줄 수 있다.
    for features, labels in iter(dataset.batch(len(x_train))):
        #print(features)
        #print(labels)
        hypothesis = logistic_regression(features)
        grads = grad(features, labels)
        optimizer.apply_gradients(grads_and_vars =zip(grads,[W,b]))
        if step % 100 ==0:
            print("Iter : {}, Loss: {:.4f}".format(step, loss_fn(logistic_regression(features),features,labels)))
test_acc = accuracy_fn(logistic_regression(x_test),y_test)
print("Testset Accuracy: {:4f}".format(test_acc))
 
Iter : 0, Loss: 0.0908
Iter : 100, Loss: 0.0863
Iter : 200, Loss: 0.0823
Iter : 300, Loss: 0.0787
Iter : 400, Loss: 0.0755
Iter : 500, Loss: 0.0726
Iter : 600, Loss: 0.0699
Iter : 700, Loss: 0.0675
Iter : 800, Loss: 0.0652
Iter : 900, Loss: 0.0631
Iter : 1000, Loss: 0.0612
Testset Accuracy: 1.000000
 

test값 변환 후 결과 값 도출

어큐러시가 0이 나왔음으로 새롭게 제시한 test값은 거짓임

In [147]:
x_test2 = [[2.,6.]]
y_test2 = [[1.]]
In [148]:
#반복 횟수 선언
EPOCHS = 1001

for step in range(EPOCHS):
    #dataset을 몇 묶음씩 학습 시킬 것인지 정해준다
    #batch size를 선언해줄 수 있다.
    for features, labels in iter(dataset.batch(len(x_train))):
        #print(features)
        #print(labels)
        hypothesis = logistic_regression(features)
        grads = grad(features, labels)
        optimizer.apply_gradients(grads_and_vars =zip(grads,[W,b]))
        if step % 100 ==0:
            print("Iter : {}, Loss: {:.4f}".format(step, loss_fn(logistic_regression(features),features,labels)))
test_acc = accuracy_fn(logistic_regression(x_test2),y_test2)
print("Testset Accuracy: {:4f}".format(test_acc))
 
Iter : 0, Loss: 0.0470
Iter : 100, Loss: 0.0460
Iter : 200, Loss: 0.0450
Iter : 300, Loss: 0.0440
Iter : 400, Loss: 0.0431
Iter : 500, Loss: 0.0422
Iter : 600, Loss: 0.0414
Iter : 700, Loss: 0.0406
Iter : 800, Loss: 0.0398
Iter : 900, Loss: 0.0391
Iter : 1000, Loss: 0.0384
Testset Accuracy: 0.000000
 

batch값 설정

batch값을 2로 설정 하였는데,
아래 예 처럼 6개의 슬라이스를 3번에 나눠 각각 학습이 된다.

In [151]:
#반복 횟수 선언
EPOCHS = 1001

for step in range(EPOCHS):
    #dataset을 몇 묶음씩 학습 시킬 것인지 정해준다
    #batch size를 선언해줄 수 있다.
    for features, labels in iter(dataset.batch(2)):
        #print(features)
        #print(labels)
        hypothesis = logistic_regression(features)
        grads = grad(features, labels)
        optimizer.apply_gradients(grads_and_vars =zip(grads,[W,b]))
        if step % 100 ==0:
            print("Iter : {}, Loss: {:.4f}".format(step, loss_fn(logistic_regression(features),features,labels)))
test_acc = accuracy_fn(logistic_regression(x_test2),y_test2)
print("Testset Accuracy: {:4f}".format(test_acc))
 
Iter : 0, Loss: 0.0009
Iter : 0, Loss: 0.1133
Iter : 0, Loss: 0.0009
Iter : 100, Loss: 0.0007
Iter : 100, Loss: 0.1076
Iter : 100, Loss: 0.0007
Iter : 200, Loss: 0.0006
Iter : 200, Loss: 0.1024
Iter : 200, Loss: 0.0006
Iter : 300, Loss: 0.0005
Iter : 300, Loss: 0.0977
Iter : 300, Loss: 0.0005
Iter : 400, Loss: 0.0005
Iter : 400, Loss: 0.0934
Iter : 400, Loss: 0.0005
Iter : 500, Loss: 0.0004
Iter : 500, Loss: 0.0895
Iter : 500, Loss: 0.0004
Iter : 600, Loss: 0.0004
Iter : 600, Loss: 0.0858
Iter : 600, Loss: 0.0004
Iter : 700, Loss: 0.0003
Iter : 700, Loss: 0.0825
Iter : 700, Loss: 0.0003
Iter : 800, Loss: 0.0003
Iter : 800, Loss: 0.0794
Iter : 800, Loss: 0.0003
Iter : 900, Loss: 0.0003
Iter : 900, Loss: 0.0765
Iter : 900, Loss: 0.0003
Iter : 1000, Loss: 0.0002
Iter : 1000, Loss: 0.0739
Iter : 1000, Loss: 0.0002
Testset Accuracy: 0.000000
 

해당 포스팅은 부스트코스 강의와, 텐서플로우공식 홈페이지를 참고하여 작성하였습니다.

'Tensorflow > ML' 카테고리의 다른 글

Tensorflow 다중선형회귀 공부  (0) 2020.08.07
Python Tensorflow 다중선형회귀  (0) 2020.07.25
Python Tensorflow 단순선형회귀  (0) 2020.07.20