You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

train_lstm.py 2.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # 首先需要加入以下的路径到环境变量,因为当前只对内部测试开放,所以需要手动申明一下路径
  2. import os
  3. os.environ['FASTNLP_BASE_URL'] = 'http://10.141.222.118:8888/file/download/'
  4. os.environ['FASTNLP_CACHE_DIR'] = '/remote-home/hyan01/fastnlp_caches'
  5. import torch.nn as nn
  6. from data.IMDBLoader import IMDBLoader
  7. from fastNLP.modules.encoder.embedding import StaticEmbedding
  8. from model.lstm import BiLSTMSentiment
  9. from fastNLP.core.const import Const as C
  10. from fastNLP import CrossEntropyLoss, AccuracyMetric
  11. from fastNLP import Trainer, Tester
  12. from torch.optim import Adam
  13. from fastNLP.io.model_io import ModelLoader, ModelSaver
  14. import argparse
  15. class Config():
  16. train_epoch= 10
  17. lr=0.001
  18. num_classes=2
  19. hidden_dim=256
  20. num_layers=1
  21. nfc=128
  22. task_name = "IMDB"
  23. datapath={"train":"IMDB_data/train.csv", "test":"IMDB_data/test.csv"}
  24. save_model_path="./result_IMDB_test/"
  25. opt=Config()
  26. # load data
  27. dataloader=IMDBLoader()
  28. datainfo=dataloader.process(opt.datapath)
  29. # print(datainfo.datasets["train"])
  30. # print(datainfo)
  31. # define model
  32. vocab=datainfo.vocabs['words']
  33. embed = StaticEmbedding(vocab, model_dir_or_name='en-glove-840b-300', requires_grad=True)
  34. model=BiLSTMSentiment(init_embed=embed, num_classes=opt.num_classes, hidden_dim=opt.hidden_dim, num_layers=opt.num_layers, nfc=opt.nfc)
  35. # define loss_function and metrics
  36. loss=CrossEntropyLoss()
  37. metrics=AccuracyMetric()
  38. optimizer= Adam([param for param in model.parameters() if param.requires_grad==True], lr=opt.lr)
  39. def train(datainfo, model, optimizer, loss, metrics, opt):
  40. trainer = Trainer(datainfo.datasets['train'], model, optimizer=optimizer, loss=loss,
  41. metrics=metrics, dev_data=datainfo.datasets['test'], device=0, check_code_level=-1,
  42. n_epochs=opt.train_epoch, save_path=opt.save_model_path)
  43. trainer.train()
  44. if __name__ == "__main__":
  45. train(datainfo, model, optimizer, loss, metrics, opt)