TCN-based Seq2Seq prediction task

username: Wangqf
cooked: <p>There is a Seq2Seq prediction problem, and the task is to predicit a time-series data y from time-series data x,z1,z2,z3.<br>
The lengths of squences of x,z1,z2,z3 and y are all 100.</p>
<p>There is no problem in the dataset, because I have done the prediction work in the traditional RNN form based on the encoder-decoder model.<br>
But when I turned to the TCN model, the training loss didn’t go down. And the most annoying thing is that the predition is always 0! Each time and each batch, all predictions are zero.</p>
<p>Can somebody help me? thanks you very much!<br>
<img src="https://discuss.pytorch.org/uploads/default/original/3X/c/e/ce5ac9e22fbe12a2fba1c805e5450caa8c5fab5a.png" alt="Training prediction 1" data-base62-sha1="truS6iICmcD5kusaKmdQYvxJ6Lo" width="320" height="240"></p>
<pre><code class="lang-auto">&gt; import os
&gt; import time
&gt; import torch
&gt; import numpy as np
&gt; from torch import nn
&gt; import torch.utils.data as Data
&gt; from torch.nn.utils import weight_norm
&gt; from sklearn.metrics import r2_score
&gt; import matplotlib.pyplot as plt
&gt; 
&gt; Inj_meas = 1
&gt; Injuries = ['Acc', 'Cdisp','NForce', 'NMoment']
&gt; inj = Injuries[Inj_meas - 1] 
&gt; 
&gt; start_time = time.time()
&gt; X_train = torch.from_numpy(np.load('PROCESSED_DATA\X_train' + inj + '.npy')).long().data.cuda()  #[3500*8*0.8,100]
&gt; y_train = torch.from_numpy(np.load('PROCESSED_DATA\y_train' + inj + '.npy')-1000).long().data.cuda()  #[3500*8*0.8,100] (max=533)
&gt; z1_train = torch.from_numpy(np.load('PROCESSED_DATA\z1_train' + inj + '.npy')/500).long().data.cuda()  #[3500*8*0.8,100]
&gt; z2_train = torch.from_numpy(np.load('PROCESSED_DATA\z2_train' + inj + '.npy')/100).long().data.cuda()  #[3500*8*0.8,100]
&gt; z3_train = torch.from_numpy(np.load('PROCESSED_DATA\z3_train' + inj + '.npy')/200).long().data.cuda()  #[3500*8*0.8,100]
&gt; print('Loading dataset duration:',time.time() - start_time,'s')
&gt; 
&gt; ##########################################################
&gt; class Chomp1d(nn.Module):
&gt;     def __init__(self, chomp_size):
&gt;         super(Chomp1d, self).__init__()
&gt;         self.chomp_size = chomp_size
&gt; 
&gt;     def forward(self, x):
&gt;         return x[:, :, :-self.chomp_size].contiguous()
&gt; 
&gt; class TemporalBlock(nn.Module):
&gt;     def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation, padding, dropout=0.2):
&gt;         super(TemporalBlock, self).__init__()
&gt;         self.conv1 = weight_norm(nn.Conv1d(n_inputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation))
&gt;         self.chomp1 = Chomp1d(padding)
&gt;         self.relu1 = nn.ReLU()
&gt;         self.dropout1 = nn.Dropout(dropout)
&gt; 
&gt;         self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation))
&gt;         self.chomp2 = Chomp1d(padding)
&gt;         self.relu2 = nn.ReLU()
&gt;         self.dropout2 = nn.Dropout(dropout)
&gt; 
&gt;         self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.dropout1, self.conv2, self.chomp2, self.relu2, self.dropout2)
&gt;         self.downsample = nn.Conv1d(n_inputs, n_outputs, 1) if n_inputs != n_outputs else None
&gt;         self.relu = nn.ReLU()
&gt;         self.init_weights()
&gt; 
&gt;     def init_weights(self):
&gt;         self.conv1.weight.data.normal_(0, 0.01)
&gt;         self.conv2.weight.data.normal_(0, 0.01)
&gt;         if self.downsample is not None:
&gt;             self.downsample.weight.data.normal_(0, 0.01)
&gt; 
&gt;     def forward(self, x):
&gt;         out = self.net(x)
&gt;         res = x if self.downsample is None else self.downsample(x)
&gt;         return self.relu(out + res)
&gt; 
&gt; class TemporalConvNet(nn.Module):
&gt;     def __init__(self, num_inputs, num_channels, kernel_size=2, dropout=0.2):
&gt;         super(TemporalConvNet, self).__init__()
&gt;         layers = []
&gt;         num_levels = len(num_channels)
&gt;         for i in range(num_levels):
&gt;             dilation_size = 2 ** i
&gt;             in_channels = num_inputs if i == 0 else num_channels[i-1]
&gt;             out_channels = num_channels[i]
&gt;             layers += [TemporalBlock(in_channels, out_channels, kernel_size, stride=1, dilation=dilation_size,
&gt;                                      padding=(kernel_size-1) * dilation_size, dropout=dropout)]
&gt;         self.network = nn.Sequential(*layers)
&gt; 
&gt;     def forward(self, x):
&gt;         return self.network(x)
&gt; ##########################################################
&gt; class TCN(nn.Module):
&gt;     def __init__(self, embed_size, inputFeat_size, output_size, num_channels, kernel_size=2, dropout=0.3, emb_dropout=0.1):
&gt;         super(TCN, self).__init__()
&gt;         self.encoder_x = nn.Embedding(output_size, embed_size)
&gt;         self.encoder_z1 = nn.Embedding(inputFeat_size, embed_size)
&gt;         self.encoder_z2 = nn.Embedding(inputFeat_size, embed_size)
&gt;         self.encoder_z3 = nn.Embedding(inputFeat_size, embed_size)
&gt;         self.tcn = TemporalConvNet(embed_size, num_channels, kernel_size, dropout=dropout)
&gt;         self.decoder = nn.Linear(num_channels[-1], output_size)
&gt;         self.drop = nn.Dropout(emb_dropout)
&gt;         self.emb_dropout = emb_dropout
&gt;         self.init_weights()
&gt; 
&gt;     def init_weights(self):
&gt;         self.encoder_x.weight.data.normal_(0, 0.01)
&gt;         self.encoder_z1.weight.data.normal_(0, 0.01)
&gt;         self.encoder_z2.weight.data.normal_(0, 0.01)
&gt;         self.encoder_z3.weight.data.normal_(0, 0.01)
&gt;         self.decoder.bias.data.fill_(0)
&gt;         self.decoder.weight.data.normal_(0, 0.01)
&gt; 
&gt;     def forward(self, x, z1, z2, z3):
&gt;         """Input ought to have dimension (N, C_in, L_in), where L_in is the seq_len; here the input is (N, L, C)"""
&gt;         emb_x = self.drop(self.encoder_x(x))
&gt;         emb_z1 = self.encoder_z1(z1)
&gt;         emb_z2 = self.encoder_z2(z2)
&gt;         emb_z3 = self.encoder_z3(z3)
&gt;         emb_extended = emb_x + emb_z1 + emb_z2 + emb_z3
&gt;         y = self.tcn(emb_extended.transpose(1, 2)).transpose(1, 2)
&gt;         y = self.decoder(y)
&gt;         return y.contiguous()
&gt; ##########################################################
&gt; Batch_size = 64
&gt; Emb_size = 64
&gt; InputFeat_size = 2
&gt; Hidden_size = 128
&gt; Level_Size = 5
&gt; Num_Chans = [Hidden_size] * (Level_Size - 1) + [Emb_size]
&gt; Output_Size = 1000
&gt; K_size = 3
&gt; CNN_dropout = 0.0
&gt; Emb_dropout = 0.0
&gt; Clip = 0.35
&gt; Learning_rate = 0.01
&gt; Epochs = 10
&gt; ##########################################################
&gt; dataset = Data.TensorDataset(X_train, z1_train, z2_train, z3_train, y_train)
&gt; loader = Data.DataLoader(dataset=dataset, batch_size=Batch_size, shuffle=True)
&gt; ##########################################################
&gt; model = TCN(Emb_size, InputFeat_size, Output_Size, Num_Chans, dropout=CNN_dropout, emb_dropout=Emb_dropout, kernel_size=K_size).cuda()
&gt; optimizer = torch.optim.Adam(model.parameters(), lr= Learning_rate)
&gt; scheduler_lr = torch.optim.lr_scheduler.MultiStepLR(optimizer, [5,18,45], gamma=0.3, last_epoch=-1)
&gt; criterion = nn.CrossEntropyLoss().cuda()
&gt; 
&gt; LossCurve = []
&gt; R2Curve = []
&gt; 
&gt; for epoch in range(Epochs):
&gt;     epoch_start_time = time.time()
&gt;     loss_batch = []
&gt;     model.train()
&gt;     for step, (batch_x, batch_z1, batch_z2, batch_z3, batch_y) in enumerate(loader):   # batch_x.shape = batch_z1.shape =[Bat_S, 100]
&gt;         prediction = model(batch_x, batch_z1, batch_z2, batch_z3)    #[Bat_S, 100, 1000]
&gt;         loss = criterion(prediction.reshape(-1, Output_Size), batch_y.reshape(-1))  # batch_y.shape = [Bat_S, 100]
&gt;         loss.backward()
&gt;         optimizer.step()
&gt;         loss_batch.append(loss.detach().data.cpu().numpy())
&gt;         if step % 10 == 0:
&gt;             print('Epoch: ', epoch+1, '/', Epochs,'| Step:', step, '/', len(loader),'| Batch_Loss:', loss.detach().data.cpu().numpy())
&gt;         if step == 50:
&gt;             break
&gt; 
&gt;     loss = np.mean(loss_batch)
&gt;     print('Epoch: ', epoch + 1, '/', Epochs, '| Loss:', loss, '| Epoch duration:', time.time() - epoch_start_time, 's | Lr:',
&gt;           optimizer.state_dict()['param_groups'][0]['lr'])
&gt;     Num = 0
&gt;     Real = (batch_y[Num]).data.cpu().numpy()
&gt;     Pred = (prediction[Num].data.max(1)[1]).data.cpu().numpy()
&gt;     plt.plot(np.arange(0, 200, 2), Real, 'r', label='Actual')
&gt;     plt.plot(np.arange(0, 200, 2), Pred, 'b--', label='Prediction')
&gt;     plt.title('Training prediction %d.png' % (epoch + 1))
&gt;     R22 = r2_score(Real, Pred)
&gt;     plt.legend()
&gt;     LossCurve.append(loss)
&gt;     R2Curve.append(round(R22, 1))
&gt;     plt.savefig(os.path.join('Prediction_IMAGE', 'Training prediction %d.png' % (epoch + 1)))
&gt;     plt.close()
&gt; 
&gt; plt.plot(LossCurve, label='Loss')
&gt; plt.plot(R2Curve, label='R2 sample')
&gt; plt.title('Training Progress')
&gt; plt.legend()
&gt; plt.savefig(os.path.join('Prediction_IMAGE', 'Loss and R2.png'))
&gt; plt.close()
</code></pre>