[ Architecture, Technology ,Web ] SSO(Single Sign On) 그리고 SAML에 대해

이미지
이번 프로젝트 내부에서 어쩌다보니  유저 인증 관련 업무를 담당하게 되었고, 해야하는 업무는 내부에 사용했던 적이 없던  새로운 개발 플랫폼에서  SSO의 프로토콜 중  SAML을 이용해 앱의 인증을 구현해야만 했다. SSO를 생각해본적 조차 없는 상황에 이를 새로운 개발 플랫폼에 도입해야 했기 때문에 많은 시행착오를 겪었으나 구현에 성공하였으며 덕분에 SSO에 대한 전반적인 지식을 쌓을 수 있었다. 이번에는 그러한 과정에서 나온 지식들과 경험을  공유하고자 한다. SSO에 대한 정의 먼저 사전적 정의 부터 살펴보자. 다만, 기술적인 용어다보니 자주 사용하는 옥스포드 사전에 정의를 찾을 수 없기 때문에  검색으로 찾을 수 있는 정의를 몇 가지 살펴보고 교차 검증을 해보자. 첫 번째 정의를 살펴보자. Single sign-on (SSO) is an identification method that enables users to log in to multiple applications and websites with one set of credentials.  SSO는 웹사이트에서 한 번의 인증(one set of credentials)으로 복수의 어플리케이션에 로그인 할 수 있는 인증(identification) 방법(method) 이다. 두 번째는 위키피디아의 정의이다. Single sign-on (SSO) is an authentication scheme that allows a user to log in with a single ID to any of several related, yet independent, software systems. SSO는 독립적이지만 연관되어있는 몇몇 소프트웨어에 대해 하나의 ID로 로그인을 할 수 있도록 하는 인증 구조(scheme) 세부 설명에 조금 차이가 있어 보이지만 전체적인 틀은 매우 비슷해 보인다.  몇 가지 포인트가 되는 단어를 추출해 이를 연결해보자면 아래와 같은 의미를 산출 할 수 있다. 독립적이지만 연관되어 있

[ Neural Network, Python] Python에서 뉴럴 네트워크는 어떻게 표현되는가? : 뉴럴 네트워크의 모듈(객체)화


이전 포스팅에서 오류률을 최소화하기 위해서
역전파를 구현해 수직, 나선 분포 데이터의 테스트 까지 완료하였다.

물론 여기서 끊을 수도 있겠지만,
좀 더 욕심을 내서 모듈화(객체화)까지 완성해보자.

현재 코드의 가장 큰 문제점은 
하드 코딩으로 레이어와 활성화 함수를 고정 시켰다는 점에 있다.

좋은 코드가 되기 위해서는
레이어의 선택과 활성화 함수 선택까지 할 수 있어야 하며
코드 또한 간결할 필요가 있다.

이번에는 코드의 최적화를 하여,
레이어 생성 부터 시작해 최적화(역전파)를 비롯한
전체 과정을 객체로 불러올 수 있게 최적화 해보자.

이것으로 꽤 나 길었던 포스팅이 끝이 날 것이다.

레이어의 모듈화

이번 모듈화는 따로 소스 파일 까지 분리 하였다.

먼저 레이어에 관련된 소스 코드의 모듈화다.


1
2
3
4
5
6
7
8
9
10
#layer.py
class Layer:
    def __init__(self):
        pass
 
    def forward(self):
        pass
 
    def backward(self):
        pass
cs

이 파일은 단순히 상속하기 위한 코드이다.

대부분 파일에서 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#layer_dense.py
from layer import Layer
import numpy as np
 
class Layer_Dense(Layer):
    def __init__(self, n_inputs, n_neurons):
        #randn : 0으로 중심으로한 가우스 분포를 무작위 생성
        #실제 randn 함수는 1을 초과한 값을 출력하기 때문에 0.10을 곱함
        self.weights = 0.10 * np.random.randn(n_inputs, n_neurons)
        #뉴런 수만 큼 무작위로 편향(값) 생성
        self.biases = np.random.rand(1,n_neurons)
        self.type = 'layer'
 
    def forward(self, inputs):
        self.input = inputs
        #순방향 전파 수식을 표현
        self.output = np.dot(inputs, self.weights) + self.biases
 
        return self.output
 
    def backward(self, d_activation, learning_rate):
        #learning_rate = 0.15
        #delta
        d_input = np.dot(d_activation,self.weights.T)
        #가중치 오류률 산출
        d_weight = np.dot(self.input.T,d_activation)
        #편향 오류률 산출
        d_bias = d_activation.mean(axis=0,keepdims=True)
 
        #가중치, 편향 업데이트
        self.weights -= learning_rate * d_weight
        self.biases -= learning_rate * d_bias
 
        return d_input
 
cs

레이어의 객체이다.

이전 소스와 큰 차이는 없으나, 
역전파 과정에서 learning rate를 설정할 수 있게 수정하였다.

활성화 함수의 모듈화


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#activation_layer.py
import numpy as np
from layer import Layer
 
class Softmax(Layer):
    def __init__(self, output_cnt):
 
        self.units = output_cnt
        self.type = 'Softmax'
 
    def forward(self,inputs):
        #오버플로우를 방지하기 위해 최대값을 빼줌
        exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True))
        probabilities = exp_values / np.sum(exp_values, axis=1, keepdims=True)
 
        self.output = probabilities
 
        return self.output
 
    def backward(self,gradient):
        forward_soft = self.output
        self.output_back = forward_soft * (gradient -( gradient * forward_soft).sum(axis=1, keepdims=True))
 
        return self.output_back
 
class ReLU(Layer):
    def __init__(self, output_cnt):
 
        self.units = output_cnt
        self.type = 'ReLU'
 
    def forward(self,inputs):
        self.output = np.maximum(0, inputs)
        return self.output
 
    def backward(self,gradient):
        foward_ReLU = self.output
 
        self.output_back = gradient * np.where(foward_ReLU<=001)
        #self.output_back = gradient * np.heaviside(foward_ReLU,0)
 
        return self.output_back
 
cs

활성화 함수 관련 소스 코드가 들어가 있는 파일이다.

소스의 변화는 없다.

손실 함수의 모듈화




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#losses.py
import numpy as np
 
class Loss_CCE():
    def forward(self, output, y):
        #예측된 확률 분포의 갯수
        n = output.shape[0]
        #상속 받은 범주형 교차 엔트로피를 계산
        cce_matrix = self.CCE_forward(output, y)
        loss_cce = cce_matrix/n
        return loss_cce
 
    def backward(self, output, y):
        return self.CCE_backward(output,y)
 
class Loss_CategoricalCrossentropy(Loss_CCE):
 
    def CCE_forward(self, y_pred, y_true):
        #오버플로우 방지를 위해 값을 조정
        y_pred_clipped = np.clip(y_pred, 1e-71-1e-7)
 
        loss_cce = -np.sum(y_true*np.log(y_pred_clipped))
 
        return loss_cce
 
    def CCE_backward(self,y_pred, y_true):
        n = y_true.shape[0]
 
        # 실제 확률 분포가 one-HotEncoding화 되어있지 않을때
        if len(y_true.shape) == 1:
            gradient = y_pred
            gradient[range(n),y_true] -= 1
            gradient = gradient/n
        #실제 확률 분포가 one-HotEncoding화 되어있을때
        elif len(y_true.shape) == 2:
            gradient = (y_pred-y_true)/n
 
        return gradient
 
cs

손실 함수의 관련 코드가 들어가 있는 파일이다.

소스 코드의 변화는 없다.

뉴럴 네트워크의 모듈화





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#model.py
class Model:
    def __init__(self):
        self.layers = []
        self.loss_value = []
        self.loss = None
 
    def add(self, layer):
        self.layers.append(layer)
 
    def setLoss(self, loss_function):
        self.loss = loss_function
 
    def predict(self, n_inputs):
        for i, _ in enumerate(self.layers):
            layer_forward = self.layers[i].forward(n_inputs)
            n_inputs = layer_forward
 
        return layer_forward
 
    def predict_loss(self, n_inputs, y_true):
 
        predict_result = self.predict(n_inputs)
        loss = self.loss.forward(predict_result, y_true)
 
        return loss
 
    def train(self, x_train, y_train, iteration, learning_rate):
 
        for i in range(iteration):
 
            #순방향 전파
            layer_forward = self.predict(x_train)
 
            #순방향 값의 손실 값 계산
            loss = self.loss.forward(layer_forward, y_train)
 
            self.loss_value.append(loss)
 
            gradient = self.loss.backward(layer_forward, y_train)
 
            #역전파
            for z, _ in reversed(list(enumerate(self.layers))):
                #print("z:",z)
                if self.layers[z].type == 'layer':
                    gradient = self.layers[z].backward(gradient,learning_rate)
                else:
                    gradient = self.layers[z].backward(gradient)
 
            print('iteration %d/%d   loss=%f' % (i+1, iteration, loss))
 
cs

이번에 추가된 소스 코드로 
모델 생성을 통해 하나의 뉴럴 네트워크 객체를 생성할 수 있다.

add 함수를 통해 레이어를 추가,
setLoss 함수를 통해 손실 함수를 설정,
predict 함수를 통해 전체 레이어의 순방향 전파를 산출,
prediect_Loss 함수를 통해 현재 뉴럴 네트워크의 손실 값을 산출,
train 함수를 통해 해당 뉴럴 네트워크 객체의 
편향(Bias)와 가중치(Weight)를 최적화 할 수 있다.

train 함수의 경우 learning rate 매개 변수를 통해
훈련 비율을 설정할 수 있는데
적절한 값을 설정하지 않는다면
이전 포스팅의 결과 값 처럼 손실 값이 원만하게 줄어들지 않고
증가와 감소를 반복하거나, 아무리 훈련을 해도 
손실값이 줄어들지 않는 결과를 낳을 수 있기 때문에
각별한 주의가 필요하다.

테스트


그렇다면 실제 Model 객체를 생성하고 
레이어와 활성화 함수를 추가 및 훈련을 해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#NN_main.py
import numpy as np
 
from model import Model
from layer_dense import *
from activation_layer import *
from losses import *
from tools import NN_tools
 
import nnfs
from nnfs.datasets import spiral_data
from nnfs.datasets import vertical_data
 
#X, y = spiral_data(samples=100, classes=3)
X, y = vertical_data(samples=100, classes=3)
 
y_true = NN_tools.oneHotEncoding(y)
 
loss_function = Loss_CategoricalCrossentropy()
 
# model 객체 생성
model = Model()
model.add(Layer_Dense(2,4))
model.add(ReLU(4))
model.add(Layer_Dense(4,3))
model.add(Softmax(3))
 
#범주형 교차 엔트로피로 손실 함수 설정
model.setLoss(loss_function)
 
#모델 훈련
model.train(X, y_true, iteration = 1000, learning_rate = 0.15)
 
#테스트
out = model.predict_loss(X, y_true)
print(out)
cs

이전 코드는 굉장히 지저분 했지만,
모듈화를 통해 깔끔해진 실행 코드를 가진 것을 볼 수 있다.

그렇다면 이제 코드를 실행해보자.

실행 결과(시작 부분)


반복 횟수는 1000번으로 설정했고, learning rate는 0.15로 설정했다.

조금씩 손실이 줄어드는 것을 확인할 수 있다.


실행 결과(끝 부분)

반복 1000번째 부분의 결과 값이다.

훈련 결과 손실 값이 약 1.1에서 0.3 정도로 
약 60%정도 최적화가 이루어진 것을 확인할 수 있다.  


마치며

이것으로 Python에서 뉴럴 네트워크 구현이라는 
긴 포스팅을 마무리 할 수 있게 되었다.

잘 최적화된 코드라고는 할 수 없지만,
이 코드를 기반으로 좀 더 최적화 하거나
활성화 함수 파일에 Sigmoid나 Tahn과 같은 소스를 추가하고
손실 함수 파일에는 이진 교차 엔트로피(Binary Cross Entropy)를 추가해 
하나의 옵션을 추가해볼 수 있을 것이다.

이 경우 테스트 코드에 활성화 함수를 바꿔주고 
setLoss 함수로 손실 함수를 설정해 주면 된다.
 
또한 INPUT 데이터를 샘플 데이터가 아니라 MNIST 등의 
유명한 데이터 셋을 활용해 뉴럴 네트워크를 훈련시키고
활용하는 토이 프로젝트를 진행 해볼 수도 있을 것이다.

후에 시간이 된다면 MNIST를 입력 데이터로 
활용하는 포스팅도 다루어보도록 하겠다.





이 블로그의 인기 게시물

[ Web ] 웹 애플리케이션 아키텍처 (Web Application Architecture)

[ Web ] 서버 사이드(Sever Side) ? 클라이언트 사이드(Client Side)? 1 [서론, 클라이언트 사이드(Client Side)]

[ Web ] 웹 애플리케이션? 웹 사이트?(Web Application? Web Site?)