aggregator_predict.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import json
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from torch.autograd import Variable
  6. import numpy as np
  7. from net_utils import run_lstm, col_name_encode
  8. class AggPredictor(nn.Module):
  9. def __init__(self, N_word, N_h, N_depth, use_ca):
  10. super(AggPredictor, self).__init__()
  11. self.use_ca = use_ca
  12. self.agg_lstm = nn.LSTM(input_size=N_word, hidden_size=N_h/2,
  13. num_layers=N_depth, batch_first=True,
  14. dropout=0.3, bidirectional=True)
  15. if use_ca:
  16. print "Using column attention on aggregator predicting"
  17. self.agg_col_name_enc = nn.LSTM(input_size=N_word,
  18. hidden_size=N_h/2, num_layers=N_depth,
  19. batch_first=True, dropout=0.3, bidirectional=True)
  20. self.agg_att = nn.Linear(N_h, N_h)
  21. else:
  22. print "Not using column attention on aggregator predicting"
  23. self.agg_att = nn.Linear(N_h, 1)
  24. self.agg_out = nn.Sequential(nn.Linear(N_h, N_h), nn.Tanh(), nn.Linear(N_h, 6))
  25. self.softmax = nn.Softmax(dim=-1)
  26. self.agg_out_K = nn.Linear(N_h, N_h)
  27. self.col_out_col = nn.Linear(N_h, N_h)
  28. def forward(self, x_emb_var, x_len, col_inp_var=None, col_name_len=None,
  29. col_len=None, col_num=None, gt_sel=None, gt_sel_num=None):
  30. B = len(x_emb_var)
  31. max_x_len = max(x_len)
  32. e_col, _ = col_name_encode(col_inp_var, col_name_len, col_len, self.agg_col_name_enc)
  33. h_enc, _ = run_lstm(self.agg_lstm, x_emb_var, x_len)
  34. col_emb = []
  35. for b in range(B):
  36. cur_col_emb = torch.stack([e_col[b,x] for x in gt_sel[b]] + [e_col[b,0]] * (4-len(gt_sel[b])))
  37. col_emb.append(cur_col_emb)
  38. col_emb = torch.stack(col_emb)
  39. att_val = torch.matmul(self.agg_att(h_enc).unsqueeze(1), col_emb.unsqueeze(3)).squeeze() # .transpose(1,2))
  40. for idx, num in enumerate(x_len):
  41. if num < max_x_len:
  42. att_val[idx, num:] = -100
  43. att = self.softmax(att_val.view(B*4, -1)).view(B, 4, -1)
  44. K_agg = (h_enc.unsqueeze(1) * att.unsqueeze(3)).sum(2)
  45. agg_score = self.agg_out(self.agg_out_K(K_agg) + self.col_out_col(col_emb)).squeeze()
  46. return agg_score