/
model.py
227 lines (181 loc) · 8.56 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Some common models for deep neural network.
Last update: KzXuan, 2019.10.29
"""
import torch
import numpy as np
import torch.nn as nn
import torch.utils.data as Data
import torch.nn.functional as F
from . import layer
class CNNModel(nn.Module):
def __init__(self, args, emb_matrix=None, kernel_widths=[2, 3, 4], act_fun=nn.ReLU):
"""Initilize CNN model data and layer.
Args:
args [dict]: all model arguments
emb_matrix [np.array]: word embedding matrix
kernel_widths [list]: list of kernel widths for CNN kernel
act_fun [torch.nn.modules.activation]: activation function
"""
super(CNNModel, self).__init__()
self.emb_mat = layer.EmbeddingLayer(emb_matrix, args.emb_type)
self.drop_out = nn.Dropout(args.drop_prob)
self.cnn = nn.ModuleList()
for kw in kernel_widths:
self.cnn.append(
layer.CNNLayer(args.emb_dim, 1, args.n_hidden, kw, act_fun, args.drop_prob)
)
self.predict = layer.SoftmaxLayer(args.n_hidden * len(kernel_widths), args.n_class)
def forward(self, inputs, mask=None):
"""Forward propagation.
Args:
inputs [tensor]: input tensor (batch_size * max_seq_len * input_size)
mask [tensor]: mask matrix (batch_size * max_seq_len)
Returns:
pred [tensor]: predict of the model (batch_size * n_class)
"""
inputs = self.emb_mat(inputs)
assert inputs.dim() == 3, "Dimension error of 'inputs', check args.emb_type & emb_dim."
if mask is not None:
assert inputs.shape[:2] == mask.shape, "Dimension match error of 'inputs' and 'mask'."
outputs = self.drop_out(inputs)
outputs = torch.cat([c(outputs, mask, out_type='max') for c in self.cnn], -1)
pred = self.predict(outputs)
return pred
class RNNModel(nn.Module):
def __init__(self, args, emb_matrix=None, n_hierarchy=1, n_layer=1,
bi_direction=True, rnn_type='LSTM', use_attention=False):
"""Initilize RNN model data and layer.
Args:
args [dict]: all model arguments
emb_matrix [np.array]: word embedding matrix
n_hierarchy [int]: number of model hierarchy
n_layer [int]: number of RNN layer in a hierarchy
bi_direction [bool]: use bi-directional model or not
rnn_type [str]: choose rnn type with 'tanh'/'LSTM'/'GRU'
use_attention [bool]: use attention layer
"""
super(RNNModel, self).__init__()
self.n_hierarchy = n_hierarchy
self.bi_direction_num = 2 if bi_direction else 1
self.use_attention = use_attention
self.emb_mat = layer.EmbeddingLayer(emb_matrix, args.emb_type)
self.drop_out = nn.Dropout(args.drop_prob)
rnn_params = (args.n_hidden, n_layer, bi_direction, rnn_type, args.drop_prob)
self.rnn = nn.ModuleList([layer.RNNLayer(args.emb_dim, *rnn_params)])
if use_attention:
self.att = nn.ModuleList(
[layer.SoftAttentionLayer(self.bi_direction_num * args.n_hidden)]
)
for _ in range(self.n_hierarchy - 1):
self.rnn.append(layer.RNNLayer(self.bi_direction_num * args.n_hidden, *rnn_params))
if use_attention:
self.att.append(layer.SoftAttentionLayer(self.bi_direction_num * args.n_hidden))
self.predict = layer.SoftmaxLayer(self.bi_direction_num * args.n_hidden, args.n_class)
def forward(self, inputs, mask=None):
"""Forward propagation.
Args:
inputs [tensor]: input tensor (batch_size * max_seq_len * input_size)
mask [tensor]: mask matrix (batch_size * max_seq_len)
Returns:
pred [tensor]: predict of the model (batch_size * n_class)
"""
inputs = self.emb_mat(inputs)
if mask is not None:
assert inputs.shape[:-1] == mask.shape, "Dimension match error of 'inputs' and 'mask'."
_, *max_seq_len, _ = inputs.size()
max_seq_len = max_seq_len[::-1]
assert len(max_seq_len) == self.n_hierarchy, "Hierarchy match error of 'inputs'."
outputs = self.drop_out(inputs)
for hi in range(self.n_hierarchy):
outputs = outputs.reshape(-1, max_seq_len[hi], outputs.size(-1))
if mask is not None:
mask = mask.reshape(-1, max_seq_len[hi])
if self.use_attention:
outputs = self.rnn[hi](outputs, mask, out_type='all')
outputs = self.att[hi](outputs, mask)
else:
outputs = self.rnn[hi](outputs, mask, out_type='last')
if mask is not None:
mask = (mask.sum(-1) != 0).int()
pred = self.predict(outputs)
return pred
class RNNCRFModel(nn.Module):
def __init__(self, args, emb_matrix=None, n_layer=1, bi_direction=True, rnn_type='LSTM'):
"""Initilize RNN-CRF model data and layer.
Args:
args [dict]: all model arguments
emb_matrix [np.array]: word embedding matrix
n_layer [int]: number of RNN layer in a hierarchy
bi_direction [bool]: use bi-directional model or not
rnn_type [str]: choose rnn type with 'tanh'/'LSTM'/'GRU'
"""
super(RNNCRFModel, self).__init__()
self.bi_direction_num = 2 if bi_direction else 1
self.emb_mat = layer.EmbeddingLayer(emb_matrix, args.emb_type)
self.drop_out = nn.Dropout(args.drop_prob)
rnn_params = (args.n_hidden, n_layer, bi_direction, rnn_type, args.drop_prob)
self.rnn = layer.RNNLayer(args.emb_dim, *rnn_params)
self.linear = nn.Linear(self.bi_direction_num * args.n_hidden, args.n_class)
self.crf = layer.CRFLayer(args.n_class)
def forward(self, inputs, mask=None, tags=None):
"""Forward propagation.
Args:
inputs [tensor]: input tensor (batch_size * max_seq_len * input_size)
mask [tensor]: mask matrix (batch_size * max_seq_len)
tags [tensor]: label matrix (batch_size * max_seq_len)
Returns:
loss [tensor]: predicting loss
pred [tensor]: predicting of the model (batch_size * max_seq_len)
"""
inputs = self.emb_mat(inputs)
assert inputs.dim() == 3, "Dimension error of 'inputs', check args.emb_type & emb_dim."
if mask is not None:
assert inputs.shape[:-1] == mask.shape, "Dimension match error of 'inputs' and 'mask'."
outputs = self.drop_out(inputs)
outputs = self.rnn(outputs, mask, out_type='all')
outputs = self.linear(outputs)
if tags is not None:
loss = self.crf(outputs, mask, tags)
return loss
else:
pred = self.crf(outputs, mask)
return pred
class TransformerModel(nn.Module):
def __init__(self, args, emb_matrix=None, n_layer=6, n_head=8, feed_dim=None):
"""Initilize transfomer model data and layer.
Args:
args [dict]: all model arguments
emb_matrix [np.array]: word embedding matrix
n_layer [int]: number of RNN layer in a hierarchy
n_head [int]: number of attention heads
feed_dim [int]: hidden matrix dimension
"""
super(TransformerModel, self).__init__()
self.n_layer = n_layer
self.emb_mat = layer.EmbeddingLayer(emb_matrix, args.emb_type)
self.drop_out = nn.Dropout(args.drop_prob)
self.trans = nn.ModuleList(
[layer.TransformerLayer(args.emb_dim, n_head, feed_dim) for _ in range(n_layer)]
)
self.predict = layer.SoftmaxLayer(args.emb_dim, args.n_class)
def forward(self, inputs, mask=None):
"""Forward propagation.
Args:
inputs [tensor]: input tensor (batch_size * max_seq_len * input_size)
mask [tensor]: mask matrix (batch_size * max_seq_len)
Returns:
pred [tensor]: predict of the model (batch_size * n_class)
"""
inputs = self.emb_mat(inputs)
assert inputs.dim() == 3, "Dimension error of 'inputs', check args.emb_type & emb_dim."
if mask is not None:
assert inputs.shape[:2] == mask.shape, "Dimension match error of 'inputs' and 'mask'."
outputs = self.drop_out(inputs)
for li in range(self.n_layer - 1):
outputs = self.trans[li](outputs, query_mask=mask, out_type='all')
outputs = self.trans[-1](outputs, query_mask=mask, out_type='first')
pred = self.predict(outputs)
return pred