predict.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from config import *
  2. from utils import *
  3. from model import make_model
  4. import torch
  5. from torch.nn.utils.rnn import pad_sequence
  6. if __name__ == '__main__':
  7. en_id2vocab, en_vocab2id = get_vocab('en')
  8. zh_id2vocab, zh_vocab2id = get_vocab('zh')
  9. SRC_VOCAB_SIZE = len(en_id2vocab)
  10. TGT_VOCAB_SIZE = len(zh_id2vocab)
  11. model = make_model(SRC_VOCAB_SIZE, TGT_VOCAB_SIZE, D_MODEL, N_HEAD, D_FF, N, DROPOUT).to(device)
  12. model.load_state_dict(
  13. torch.load("./transformer_code/params/best.pt",
  14. map_location=device))
  15. model.eval()
  16. # "其一是不久前做出的对本可用于住宅开发的未利用土地征税的决策。"
  17. # "投资不足最终会削弱经济增长并减少就业机会。"
  18. # "其真正的目标是引导构建一个包容性和合作的一体化过程,令所有参与者都能从中受益。"
  19. # test_clean.json中的数据
  20. texts = [
  21. "I like playing basketball",
  22. "He is a doctor",
  23. "I am a student",
  24. "What is particularly problematic in the EU is the clash between radical politics and mainstream governance.",
  25. # "欧洲问题的严重之处在于激进政治与主流治理之间的碰撞。"
  26. "Such a resounding collapse of the Nuclear Non-Proliferation Treaty would pose a formidable challenge to the world community, particularly to the Middle East.",
  27. # "《核不扩散条约》如此引人瞩目的崩溃会给国际社会,特别是中东国家带来可怕的挑战。"
  28. "It certainly would deal a devastating blow to the EU’s credibility, both in its member states and abroad.",
  29. # "这无疑会在欧盟成员国及海外对欧盟的信誉造成毁灭性的打击。"
  30. "Its real goal is to lead an inclusive and cooperative integration process that benefits all participants.",
  31. # "其真正的目标是引导构建一个包容性和合作的一体化过程,令所有参与者都能从中受益。"
  32. ]
  33. #把词转成对应的索引
  34. batch_src_token = [[en_vocab2id.get(v.lower(), UNK_ID) for v in divided_en(text)] for text in texts]
  35. batch_src = [torch.LongTensor(src) for src in batch_src_token]
  36. #每句话加上padding
  37. src_x = pad_sequence(batch_src, True, PAD_ID)
  38. src_mask = get_padding_mask(src_x, PAD_ID)
  39. prob_sent = batch_greedy_decode(model, src_x, src_mask)
  40. print(prob_sent)