|
a |
|
b/src/cnn/cnn.py |
|
|
1 |
import torch |
|
|
2 |
import torch.nn as nn |
|
|
3 |
|
|
|
4 |
class character_cnn(nn.Module): |
|
|
5 |
def __init__(self, vocabulary, sequence_length, number_classes = 10): |
|
|
6 |
super().__init__() |
|
|
7 |
|
|
|
8 |
self.conv1 = nn.Sequential(nn.Conv1d(len(vocabulary)+1, 256, kernel_size = 7, padding = 0), |
|
|
9 |
nn.ReLU(), |
|
|
10 |
nn.MaxPool1d(3) |
|
|
11 |
) |
|
|
12 |
|
|
|
13 |
self.conv2 = nn.Sequential(nn.Conv1d(256, 256, kernel_size=7, padding=0), |
|
|
14 |
nn.ReLU(), |
|
|
15 |
nn.MaxPool1d(3) |
|
|
16 |
) |
|
|
17 |
|
|
|
18 |
self.conv3 = nn.Sequential(nn.Conv1d(256, 256, kernel_size=3, padding=0), |
|
|
19 |
nn.ReLU() |
|
|
20 |
) |
|
|
21 |
|
|
|
22 |
self.conv4 = nn.Sequential(nn.Conv1d(256, 256, kernel_size=3, padding=0), |
|
|
23 |
nn.ReLU() |
|
|
24 |
) |
|
|
25 |
|
|
|
26 |
input_shape = (1, len(vocabulary)+1, sequence_length) |
|
|
27 |
self.output_dimension = self._get_conv_output(input_shape) |
|
|
28 |
|
|
|
29 |
self.fc1 = nn.Sequential( |
|
|
30 |
nn.Linear(self.output_dimension, 1024), |
|
|
31 |
nn.ReLU(), |
|
|
32 |
nn.Dropout(0.5) |
|
|
33 |
) |
|
|
34 |
|
|
|
35 |
self.fc2 = nn.Sequential( |
|
|
36 |
nn.Linear(1024, 1024), |
|
|
37 |
nn.ReLU(), |
|
|
38 |
nn.Dropout(0.5) |
|
|
39 |
) |
|
|
40 |
|
|
|
41 |
self.fc3 = nn.Linear(1024, number_classes) |
|
|
42 |
|
|
|
43 |
|
|
|
44 |
self.act = nn.Sigmoid() |
|
|
45 |
|
|
|
46 |
def _get_conv_output(self, shape): |
|
|
47 |
x = torch.rand(shape) |
|
|
48 |
x = self.conv1(x) |
|
|
49 |
x = self.conv2(x) |
|
|
50 |
x = self.conv3(x) |
|
|
51 |
x = self.conv4(x) |
|
|
52 |
x = x.view(x.size(0), -1) |
|
|
53 |
output_dimension = x.size(1) |
|
|
54 |
return output_dimension |
|
|
55 |
|
|
|
56 |
|
|
|
57 |
def forward(self, x): |
|
|
58 |
x = self.conv1(x) |
|
|
59 |
x = self.conv2(x) |
|
|
60 |
x = self.conv3(x) |
|
|
61 |
x = self.conv4(x) |
|
|
62 |
x = x.view(x.size(0), -1) |
|
|
63 |
x = self.fc1(x) |
|
|
64 |
x = self.fc2(x) |
|
|
65 |
x = self.fc3(x) |
|
|
66 |
x = self.act(x) |
|
|
67 |
return x |
|
|
68 |
|
|
|
69 |
|
|
|
70 |
|
|
|
71 |
|
|
|
72 |
|