tensorflow로 시작해서 그런지 keras쪽이 더 눈에 익기는 한데, PyTorch도 쓰다보면 익숙해지겠지.
전 회사 다닐때 비해서 많은 발전이 있기는 했지만, 아직도 많이 부족하다는 것을 느낀다. 언제쯤이면 어느 정도 괜찮다 싶다는 생각이 들려나. 
 
 
 
1. Embedding을 사용하며, 단어 집합(vocabulary)의 크기가 5,000이고 임베딩 벡터의 차원 100
 
2. 은닉층에서는 SimpleRNN을 사용하며, 은닉 상태의 크기는 128입니다.
 
3. 훈련에 사용하는 모든 샘플의 길이는 30으로 가정합니다.
 
4. 이진 분류를 수행하는 모델로, 출력층의 뉴런은 1개로 시그모이드 함수를 사용합니다.
 
5. 은닉층은 1개입니다.
 
위의 정보를 이용해서 tensorflow.keras를 이용해서 모델 생성하는 파이썬 코드를 만들어주고 총 파라미터 개수를 알려주세요.

 

아래는 주어진 조건에 따라 모델을 구현한 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()

 

총 파라미터 계산

  1. Embedding Layer:
    • vocab_size×embedding_dim=5000×100=500,000\text{vocab\_size} \times \text{embedding\_dim} = 5000 \times 100 = 500,000
  2. 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 항목
      (input_dim+units+1)×units=(100+128+1)×128=229×128=29,312(\text{input\_dim} + \text{units} + 1) \times \text{units} = (100 + 128 + 1) \times 128 = 229 \times 128 = 29,312
  3. 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}")

 

주요 변경점

  1. Embedding Layer:
    • nn.Embedding을 사용하여 단어 집합 크기와 임베딩 벡터 차원 설정.
  2. SimpleRNN Layer:
    • nn.RNN을 사용하여 은닉 상태 크기와 입력 크기 정의.
    • batch_first=True를 설정해 입력 텐서를 (batch_size, sequence_length, embedding_dim) 형태로 맞춤.
  3. Dense Layer:
    • nn.Linear을 사용해 은닉 상태의 마지막 출력에서 1차원 출력 생성.
  4. 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' 카테고리의 다른 글

Python FAISS  (5) 2025.08.10
torch.nn.Embedding()  (0) 2025.01.04
NewsClassifier  (0) 2025.01.04
Python Scheduler  (0) 2024.12.10
networkx - sql과 함께  (1) 2024.10.24

+ Recent posts