본문 바로가기
AI, 빅데이터/AI

[AI 개념 다지기] Affine Function

by Foxy현 2022. 8. 1.
728x90
반응형

안녕하세요 Foxy현입니다.

Articial Neuron을 만들기 위해  Activation Function과 Affine Function이라는 것이 필요합니다.

오늘은 그중 Affine Function에 대해 알아 보겠습니다.


Affine Function에 대해 설명하기 앞서 Weighted Sum(가중치 합)에 대해 알아 보겠습니다.

Weighted Sum은 가중치 w들을 각각의 feature x에 대해 곱하여 더하는 것을 의미합니다.

우리는 Weighted sum에 bias(b)를 더해준 것을 Affine Function이라고 부릅니다.

 

이때, 행 벡터  x와 열벡터 w가 하나씩 대응되어 곱해지며, 이 두 벡터의 dot product를 통해 스칼라 값을 도출하게 됩니다.

이에 bias를 더해 Affine Function을 연산할 수 있습니다.

 

따라서, x 벡터의 원소의 개수와 weight 벡터의 원소의 개수는 반드시 같아야 합니다.


import tensorflow as tf
from tensorflow.keras.layers import Dense

x=tf.constant([[10.]]) # input ==> matrix

dense=Dense(units=1,activation='linear') # an affine function

y=dense(x) #forward propagation 

W, B = dense.get_weights() # weight, bias

print('\n=== Input/Weight/Bias ===\n')
print("x: {}\n\n".format(x.shape,x.numpy()))
print("w: {}\n\n".format(W.shape,W))
print("b: {}\n\n".format(B.shape,B))

print('\n=== Output ===\n')
print("y: {}\n\n".format(y.shape,y.numpy()))

수작업으로 Affine Function을 만들 수 있지만, 우리는 tensorflow 라이브러리에서 제공하는 함수를 사용하여 구현합니다.

 

코드를 자세히 살펴보겠습니다.

x=tf.constant([[10.]]) # input ==> matrix

dense=Dense(units=1,activation='linear') # an affine function

y=dense(x) #forward propagation 

W, B = dense.get_weights() # weight, bias

y라는 함수를 만들기위해서 Dense 함수를 사용하여 클래스를 정의하고, x라는 행렬을 불러와 y라는 함수를 만듭니다.

W, B에는 keras의 get_weights() 메서드로 가중치를 복사하여 저장합니다.

https://www.tensorflow.org/guide/keras/save_and_serialize?hl=ko

print('\n=== Input/Weight/Bias ===\n')
print("x: {}\n\n".format(x.shape,x.numpy()))
print("w: {}\n\n".format(W.shape,W))
print("b: {}\n\n".format(B.shape,B))

x와 w가 같은 크기로서, 대응하여 곱해지며, b를 더합니다.

print('\n=== Output ===\n')
print("y: {}\n\n".format(y.shape,y.numpy()))

y라는 Output에 어떠한 스칼라 값이 저장됩니다.


정리하자면,

  • 가중치 합에 bias 를 더해준 것을 Affine Function이라고 부른다.
  • x와 열벡터 w가 하나씩 대응되어 곱해지며, bias를 더해 스칼라 값이 만들어진다.
  • AN을 만들기 위해서 Affine Function 과정이 필요하다.

감사합니다.

728x90
반응형