本文主要研究pytorch版本的LSTM对数据进行单步预测
下面展示LSTM的主要代码结构
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size, batch_size,args) :
super().__init__()
self.input_size = input_size # input 特征的维度
self.hidden_size = hidden_size # 隐藏层节点个数。
self.num_layers = num_layers # 层数,默认为1
self.output_size = output_size #
self.num_directions = 1 # 单向LSTM
self.batch_size = batch_size
self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True)
self.linear = nn.Linear(self.hidden_size, self.output_size)
def forward(self, input_seq):
input_seq = input_seq.to(args.device)
batch_size, seq_len = input_seq.shape[0], input_seq.shape[1]
h_0 = torch.randn(self.num_directions * self.num_layers, input_seq.size(0), self.hidden_size).to(args.device)
c_0 = torch.randn(self.num_directions * self.num_layers, input_seq.size(0), self.hidden_size).to(args.device)
# output(batch_size, seq_len, num_directions * hidden_size)
output, _ = self.lstm(input_seq, (h_0, c_0)) #
pred = self.linear(output)
pred = pred[:, -1, :]
return pred
主函数代码
def run(args):
# create data
dataset = get_data(args.data_file_path)
data,label = create_dataset(dataset,args.time_step,args.pre_len)
data,label,mm_y = normalization(data,label)
x_data,y_data,x_train,y_train,x_test,y_test = split_data(data,label,args.split_ratio)
train_loader,test_loader,num_epochs = data_generator(x_train,y_train,x_test,y_test,args.num_n_iters,args.batch_size)
model=LSTM(args.input_size,args.hidden_size,args.num_layers,args.output_size,args.batch_size,args).to(args.device)
loss_function = torch.nn.MSELoss().to(args.device)
optimizer = torch.optim.Adam(model.parameters(),lr=args.lr)
print(model)
train(model,train_loader,num_epochs,loss_function,optimizer,args)
model.load_state_dict(torch.load(os.path.join(args.model_save_path, "best.pt")))
# test_all(model,x_data,y_data,mm_y,args)
print("test\n")
test(model,test_loader,mm_y,args)
if __name__ == '__main__':
args = parse_args()
args.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# args.device = "cpu"
args.n_gpu = torch.cuda.device_count()
print(f'args.n_gpu:{args.n_gpu}\n')
set_seed(args)
run(args)
运行代码
#!/bin/bash
set -euxo pipefail
python3 origin_lstm.py \
--seed=123 \
--num_n_iters=1000 \
--batch_size=64 \
--time_step=3 \
--pre_len=1 \
--split_ratio="0.85" \
--input_size="1" \
--num_layers=6 \
--hidden_size=64 \
--output_size 1 \
需要源代码和数据集,或者想要沟通交流,请私聊,谢谢.