아래는 주어진 조건에 따라 모델을 구현한 Python 코드와 총 파라미터 개수를 계산한 결과입니다:
모델 구현
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, SimpleRNN, Dense
# 모델 파라미터
vocab_size = 5000 # 단어 집합 크기
embedding_dim = 100 # 임베딩 벡터 차원
sequence_length = 30 # 샘플 길이
hidden_units = 128 # SimpleRNN 은닉 상태 크기
# 모델 생성
model = Sequential([
Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=sequence_length),
SimpleRNN(units=hidden_units, activation='tanh'),
Dense(1, activation='sigmoid')
])
# 모델 요약 출력
model.summary()
총 파라미터 계산
- Embedding Layer:
- vocab_size×embedding_dim=5000×100=500,000\text{vocab\_size} \times \text{embedding\_dim} = 5000 \times 100 = 500,000
- SimpleRNN Layer:
- SimpleRNN의 파라미터 계산 공식: RNN 파라미터 수=(input_dim+units+1)×units\text{RNN 파라미터 수} = (\text{input\_dim} + \text{units} + 1) \times \text{units} 여기서,
- input_dim=embedding_dim=100\text{input\_dim} = \text{embedding\_dim} = 100
- units=128\text{units} = 128
- 11은 bias 항목
- SimpleRNN의 파라미터 계산 공식: RNN 파라미터 수=(input_dim+units+1)×units\text{RNN 파라미터 수} = (\text{input\_dim} + \text{units} + 1) \times \text{units} 여기서,
- Dense Layer:
- units_in×units_out+bias=128×1+1=129\text{units\_in} \times \text{units\_out} + \text{bias} = 128 \times 1 + 1 = 129
총 파라미터
- Embedding Layer: 500,000
- SimpleRNN Layer: 29,312
- Dense Layer: 129
- 총 파라미터: 500,000+29,312+129=529,441500,000 + 29,312 + 129 = 529,441
출력
model.summary()를 실행하면 다음과 유사한 출력이 나타납니다:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding (Embedding) (None, 30, 100) 500000
simple_rnn (SimpleRNN) (None, 128) 29312
dense (Dense) (None, 1) 129
=================================================================
Total params: 529,441
Trainable params: 529,441
Non-trainable params: 0
_________________________________________________________________
아래는 주어진 조건을 만족하는 PyTorch 기반 모델 구현 코드입니다.
import torch
import torch.nn as nn
class SimpleRNNBinaryClassifier(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_units):
super(SimpleRNNBinaryClassifier, self).__init__()
self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)
self.rnn = nn.RNN(input_size=embedding_dim, hidden_size=hidden_units, batch_first=True)
self.fc = nn.Linear(in_features=hidden_units, out_features=1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
# Embedding layer
x = self.embedding(x) # Shape: (batch_size, sequence_length, embedding_dim)
# RNN layer
output, hidden = self.rnn(x) # hidden has shape (1, batch_size, hidden_units)
# Fully connected layer
x = self.fc(hidden.squeeze(0)) # Shape: (batch_size, 1)
# Sigmoid activation
x = self.sigmoid(x)
return x
# 모델 파라미터
vocab_size = 5000
embedding_dim = 100
sequence_length = 30
hidden_units = 128
# 모델 생성
model = SimpleRNNBinaryClassifier(vocab_size, embedding_dim, hidden_units)
# 모델 요약 출력 (파라미터 개수 포함)
print(model)
# 총 파라미터 개수 계산
total_params = sum(p.numel() for p in model.parameters())
print(f"Total parameters: {total_params}")
주요 변경점
- Embedding Layer:
- nn.Embedding을 사용하여 단어 집합 크기와 임베딩 벡터 차원 설정.
- SimpleRNN Layer:
- nn.RNN을 사용하여 은닉 상태 크기와 입력 크기 정의.
- batch_first=True를 설정해 입력 텐서를 (batch_size, sequence_length, embedding_dim) 형태로 맞춤.
- Dense Layer:
- nn.Linear을 사용해 은닉 상태의 마지막 출력에서 1차원 출력 생성.
- Sigmoid Activation:
- 이진 분류 문제를 위해 nn.Sigmoid를 적용.
출력 예시
위 코드를 실행하면 모델 구조와 총 파라미터 개수를 확인할 수 있습니다.
예:
SimpleRNNBinaryClassifier(
(embedding): Embedding(5000, 100)
(rnn): RNN(100, 128, batch_first=True)
(fc): Linear(in_features=128, out_features=1, bias=True)
(sigmoid): Sigmoid()
)
Total parameters: 529441
'Python, PySpark' 카테고리의 다른 글
torch.nn.Embedding() (0) | 2025.01.04 |
---|---|
NewsClassifier (0) | 2025.01.04 |
Python Scheduler (0) | 2024.12.10 |
networkx - sql과 함께 (0) | 2024.10.24 |
Python networkx (1) | 2024.10.10 |