import torch
import numpy as np
import random

USE_CUDA = torch.cuda.is_available()

# 为了让实验结果可以复现,我们需要把各种random seed固定在某一个值
random.seed(53113)
np.random.seed(53113)
torch.manual_seed(53113)

if USE_CUDA:
torch.cuda.manual_seed(53113)

一些小技巧:

torch学习率下降:learning rate decay

scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, 0.5)
scheduler.step()

torch保存参数

torch.save(model.state_dict(), "lm-best.th")

定义模型和灌入参数

best_model = RNNModel("LSTM", VOCAB_SIZE, EMBEDDING_SIZE, EMBEDDING_SIZE, 2, dropout=0.5)

best_model.load_state_dict(torch.load("lm-best.th"))