텍스트용 LSTM 모델 구축
PyBooks 팀은 최신 기술 발전을 활용해 사용자 경험을 지속적으로 향상하고자 합니다. 이 비전에 따라, 여러분께 중요한 과제가 맡겨졌어요. 팀은 데이터 패턴의 더 복잡한 특성을 포착하는 것으로 알려진 강력한 도구인 LSTM의 가능성을 탐색해 보길 원합니다. 여러분은 동일한 Newsgroup 데이터셋을 사용하며, 목표는 변하지 않았습니다. 뉴스 기사를 다음 세 가지 범주로 분류하세요:
rec.autos, sci.med, comp.graphics.
다음 패키지는 미리 로드되어 있습니다: torch, nn, optim.
이 연습은 강의의 일부입니다
PyTorch로 배우는 텍스트 딥러닝
연습 안내
- 필요한 매개변수로 LSTM과 선형 계층을 완성해 LSTM 모델을 설정하세요.
- 필요한 매개변수로 모델을 초기화하세요.
- 경사를 0으로 초기화하고 입력 데이터
X_train_seq를 모델에 전달하여 LSTM 모델을 학습하세요. - 예측한
outputs와 실제 레이블을 바탕으로 손실을 계산하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Initialize the LSTM and the output layer with parameters
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(LSTMModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(____, ____, ____, batch_first=True)
self.fc = nn.Linear(____, ____)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
out, _ = self.lstm(x, (h0, c0))
out = out[:, -1, :]
out = self.fc(out)
return out
# Initialize model with required parameters
lstm_model = LSTMModel(____, ____, ____, ____)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(lstm_model.parameters(), lr=0.01)
# Train the model by passing the correct parameters and zeroing the gradient
for epoch in range(10):
optimizer.____
outputs = lstm_model(____)
loss = criterion(____, y_train_seq)
loss.backward()
optimizer.step()
print(f'Epoch: {epoch+1}, Loss: {loss.item()}')