You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
sentence= ("if you want to build a ship, don't drum up people together to ""collect wood and don't assign them tasks and work, but rather ""teach them to long for the endless immensity of the sea.")
(3) sequence dataset
x_data->y_data"if you wan"->"f you want""f you want"->" you want "" you want "->"you want t""you want t"->"ou want to""ou want to"->"u want to "
3. 긴 문장을 조각 데이터로 만들기 코드
# 데이터 담을 리스트x_data= []
y_data= []
foriinrange(0, len(sentence) -sequence_length): # 문장의 인덱스 0부터, '전체 문장 길이 - 윈도우 길이'만큼 for문을 돈다.x_str=sentence[i : i+sequence_length] # x_str = i 부터 'i + 윈도우 길이'y_str=sentence[i+1 : i+sequence_length+1] # y_str = i+1 부터 'i + 1 + 윈도우 길이'print(i, x_str, '->', y_str)
x_data.append([char_dic[c] forcinx_str]) # 문장을 인덱스로 바꿔준다.y_data.append([char_dic[c] forciny_str])
x_one_hot= [np.eye(dic_size)[x] forxinx_data] # One_hot encodingX=torch.FloatTensor(x_one_hot)
Y=torch.LongTensor(y_data)
4. RNN 레이어 쌓기 실습하기
RNN 레이어를 2개 쌓고(stacking), FC layer를 추가 해 보자.
# RNN 모델 만들어 놓기classNet(torch.nn.Module): # PyTorch 모듈을 상속받아서 lass 정의def__init__(self, input_dim, hidden_dim, layers): # 하위 모듈 이용 정의super(Net, self).__init__()
self.rnn=torch.nn.RNN(input_dim, hidden_dim, num_layers=layers, batch_first=True) # N개의 레이어를 갖는 RNNself.fc=torch.nn.Linear(hidden_dim, hidden_dim, bias=True) # FC Layerdefforward(self, x):
x, _status=self.rnn(x) # RNNx=self.fc(x) # FC Layerreturnx# RNN 모델 이용net=Net(dic_size, hidden_size, 2) # 모델은 2개의 RNN 레이어와 FC Layer를 갖는다!# Loss와 Optimizer 정의criterion=torch.nn.CrossEntropyLoss()
optimizer=optim.Adam(net.parameters(), learning_rate)
# RNN 모델 학습 시작foriinrange(100):
outputs=net(X) # 예측값loss=criterion(outputs.view(-1, dic_size), Y.view(-1)) # 예측값과 실제값으로 loss 구하기optimizer.zero_grad() # gradient 초기화loss.backward() # BPoptimizer.step() # weight 업데이트# RNN 모델이 예측한 결과물을 사람이 알아보게 해석하기results=outputs.argmax(dim=2) # argmax로 prediction 확률이 가장 높은 것을 구한다.predict_str=""forj, resultinenumerate(results): # 반복문을 돌며 print(i, j, ''.join([char_set[t] fortinresult]), loss.item())
ifj==0:
predict_str+=''.join([char_set[t] fortinresult]) # 처음에는 result 중 windows 크기만큼 가져오고else:
predict_str+=char_set[result[-1]] # 그 이후에는 result의 마지막 부분만 반복하여 가져온다.