import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable
# 莎士比亚的诗 test_sentence = """When forty winters shall besiege thy brow, And dig deep trenches in thy beauty's field, Thy youth's proud livery so gazed on now, Will be a totter'd weed of small worth held: Then being asked, where all thy beauty lies, Where all the treasure of thy lusty days; To say, within thine own deep sunken eyes, Were an all-eating shame, and thriftless praise. How much more praise deserv'd thy beauty's use, If thou couldst answer 'This fair child of mine Shall sum my count, and make my old excuse,' Proving his beauty by succession thine! This were to be new made when thou art old, And see thy blood warm when thou feel'st it cold.""".split()
# 建立每个词与数字的编码,据此构建词嵌入 vocb = set(test_sentence) # 使用 set 将重复的元素去掉 word_to_idx = {word: i for i, word inenumerate(vocb)} # {词语: 索引} idx_to_word = {word_to_idx[word]: word for word in word_to_idx} # {索引: 词语}
word = torch.LongTensor([word_to_idx[i] for i in word]) out = net(word) # a = out.max(1)
# 预测值的索引 pred_label_idx = out.max(1).indices.item() # 预测的单词 predict_word = idx_to_word[pred_label_idx] print('real word is "{}", predicted word is "{}"'.format(label, predict_word))