대학원 일기

Deep Learning Layer: Linear Layer 본문

AI/인공지능 기초

Deep Learning Layer: Linear Layer

대학원생(노예) 2023. 11. 20. 00:03

 

 

레이어(Layer)

여러 개의 논리적인 개체가 층을 이루어 하나의 물체를 구성하는 경우, 이러한 각각의 객체를 하나의 레이어라고 한다. 


딥러닝 모델에서 레이어(layer)는 입력 데이터로부터 출력 데이터를 생성하는 연산 단위를 말한다. 각 레이어는 모델의 가중치를 포함하며, 학습 과정에서 이 가중치가 조정되면서 모델이 주어진 작업을 수행한다. 레이어에는 다양한 유형이 있으며, 주로 신경망 모델의 구조를 형성합니다.

 

Linear Layer

Linear 레이어는 인공신경망의 한 종류인 피드포워드(Feed forward) 신경망에서 사용된는 기본적인 계층이다. 종류로는  Fully Connected Layer, Feedforward Neural Network, Multilayer Perceptrons, Dense Layer... 등 다양하며 모두 Linear 레이어라고 부른다. 

 

Linear 레이어의 동작은 주어진 입력에 대해 입력 특성(feature)에 대한 가중치를 곱하고 이를 모두 편향(bias)를 더한다. Linear 레이어 수식은 딥러닝 모델에서 기본이자 간단하며 다음과 같다.

$output = Wx + b$

위 식에서 $W$는 가중치 행렬(weight)이며 $b$는 편향 벡터(bias)이다. 위 같은 계산을 통해 입력과 가중치 간의 선형 조합이 이루어지며 활성화 함수를 통해 비선형성을  추가한다.

 

Linear Layer는 다양한 딥러닝 모델에서 사용되며, 특히 이미지 분류, 회귀, 자연어 처리 등 다양한 작업에서 효과적으로 적용된다. 

 

Code 1

import tensorflow as tf

batch_size = 64
boxes = tf.zeros((batch_size, 4, 2))     # Tensorflow는 Batch를 기반으로 동작하기에,
                                         # 우리는 사각형 2개 세트를 batch_size개만큼
                                         # 만든 후 처리를 하게 됩니다.
print("1단계 연산 준비:", boxes.shape)

first_linear = tf.keras.layers.Dense(units=1, use_bias=False) 
# units은 출력 차원 수를 의미합니다.
# Weight 행렬 속 실수를 인간의 뇌 속 하나의 뉴런 '유닛' 취급을 하는 거죠!

first_out = first_linear(boxes)
first_out = tf.squeeze(first_out, axis=-1) # (4, 1)을 (4,)로 변환해줍니다.
                                           # (불필요한 차원 축소)

print("1단계 연산 결과:", first_out.shape)
print("1단계 Linear Layer의 Weight 형태:", first_linear.weights[0].shape)
print("1단계 Linear Layer의 파라미터개수:", first_linear.count_params())
print("\n2단계 연산 준비:", first_out.shape)

second_linear = tf.keras.layers.Dense(units=1, use_bias=False)
second_out = second_linear(first_out)
second_out = tf.squeeze(second_out, axis=-1)

print("2단계 연산 결과:", second_out.shape)
print("2단계 Linear Layer의 Weight 형태:", second_linear.weights[0].shape)
print("2단계 Linear Layer의 파라미터개수:", second_linear.count_params())

 

 

Code 2

import tensorflow as tf

batch_size = 64
boxes = tf.zeros((batch_size, 4, 2))

print("1단계 연산 준비:", boxes.shape)

first_linear = tf.keras.layers.Dense(units=3, use_bias=False)
first_out = first_linear(boxes)

print("1단계 연산 결과:", first_out.shape)
print("1단계 Linear Layer의 Weight 형태:", first_linear.weights[0].shape)

print("\n2단계 연산 준비:", first_out.shape)

# Dense = Linear
second_linear = tf.keras.layers.Dense(units=1, use_bias=False)
second_out = second_linear(first_out)
second_out = tf.squeeze(second_out, axis=-1)

print("2단계 연산 결과:", second_out.shape)
print("2단계 Linear Layer의 Weight 형태:", second_linear.weights[0].shape)

print("\n3단계 연산 준비:", second_out.shape)

third_linear = tf.keras.layers.Dense(units=1, use_bias=False)
third_out = third_linear(second_out)
third_out = tf.squeeze(third_out, axis=-1)

print("3단계 연산 결과:", third_out.shape)
print("3단계 Linear Layer의 Weight 형태:", third_linear.weights[0].shape)

total_params = first_linear.count_params() + second_linear.count_params() + third_linear.count_params()

print("총 Parameters:", total_params)

 

'AI > 인공지능 기초' 카테고리의 다른 글

인공신경망과 딥러닝  (0) 2023.12.04
Deep Learning Layer: Convolution Layer  (0) 2023.11.20
Embedding, Recurrent Layer  (0) 2023.11.13
딥러닝 들여다보기  (0) 2023.11.13
MLP(Multi Layer Perceptron) 과정  (1) 2023.11.13
Comments