BP神经网络的工作流程为:首先输入层接收信息,并将信息传递给中间的隐藏层;各层通过激励函数对前一层的输出加权处理;最后汇聚到输出层,得到最终计算的结果。将输入结果与目标结果进行对比,根据计算误差的大小来反向调节各个连接的权重。
以历史轨迹数据为例,使用BP神经网络进行预测未来航迹走向。模型代码如下:
import torch
import torch.nn as nn
input_dim = 3
class LinearModel(nn.Module):
"""
LinearModel.
"""
def __init__(
self, seq_len=8, h_dim=64, use_cuda=0,embedding_dim=64
):
super(LinearModel, self).__init__()
self.h_dim = h_dim
self.layer1 = torch.nn.Linear(input_dim, h_dim)
self.layer2 = torch.nn.Linear(h_dim, input_dim)
def forward(self, obs_traj):
"""
Inputs:
- obs_traj: Tensor of shape (obs_len, batch, 3)
Output:
- final_h: Tensor of shape (self.num_layers, batch, self.h_dim)
"""
# Encode observed Trajectory
result = []
batch = obs_traj.size(1)
obs_traj_embedding = self.layer1(obs_traj.contiguous().view(-1, input_dim))
obs_traj_embedding = obs_traj_embedding.view(
-1, batch, self.h_dim
)
cur_pos = self.layer2(obs_traj_embedding.view(-1, self.h_dim))
cur_pos = cur_pos.view(-1, batch, input_dim)
return cur_pos
完整代码参见Github链接:https://github.com/ironartisan/trajectory-prediction/tree/master/linear