6
6
7
7
from mla .metrics import accuracy
8
8
from mla .neuralnet import NeuralNet
9
- from mla .neuralnet .constraints import SmallNorm
10
- from mla .neuralnet .layers import Activation , TimeDistributedDense , Parameters
11
- from mla .neuralnet .layers .recurrent import RNN , LSTM
9
+ from mla .neuralnet .layers import Activation , TimeDistributedDense
10
+ from mla .neuralnet .layers .recurrent import LSTM
12
11
from mla .neuralnet .optimizers import Adam
13
12
14
13
logging .basicConfig (level = logging .DEBUG )
15
14
16
15
17
16
def addition_dataset (dim = 10 , n_samples = 10000 , batch_size = 64 ):
18
- combs = list (islice (combinations (range (2 ** (dim - 1 )), 2 ), n_samples ))
17
+ """Generate binary addition dataset.
18
+ http://devankuleindiren.com/Projects/rnn_arithmetic.php
19
+ """
19
20
binary_format = '{:0' + str (dim ) + 'b}'
21
+
22
+ # Generate all possible number combinations
23
+ combs = list (islice (combinations (range (2 ** (dim - 1 )), 2 ), n_samples ))
24
+
25
+ # Initialize empty arrays
20
26
X = np .zeros ((len (combs ), dim , 2 ), dtype = np .uint8 )
21
27
y = np .zeros ((len (combs ), dim , 1 ), dtype = np .uint8 )
22
28
23
29
for i , (a , b ) in enumerate (combs ):
30
+ # Convert numbers to binary format
24
31
X [i , :, 0 ] = list (reversed ([int (x ) for x in binary_format .format (a )]))
25
32
X [i , :, 1 ] = list (reversed ([int (x ) for x in binary_format .format (b )]))
33
+
34
+ # Generate target variable (a+b)
26
35
y [i , :, 0 ] = list (reversed ([int (x ) for x in binary_format .format (a + b )]))
27
36
28
37
X_train , X_test , y_train , y_test = train_test_split (X , y , test_size = 0.2 , random_state = 1111 )
29
38
39
+ # Round number of examples for batch processing
30
40
train_b = (X_train .shape [0 ] // batch_size ) * batch_size
31
41
test_b = (X_test .shape [0 ] // batch_size ) * batch_size
32
42
X_train = X_train [0 :train_b ]
@@ -37,7 +47,7 @@ def addition_dataset(dim=10, n_samples=10000, batch_size=64):
37
47
return X_train , X_test , y_train , y_test
38
48
39
49
40
- def addition_nlp (ReccurentLayer ):
50
+ def addition_problem (ReccurentLayer ):
41
51
X_train , X_test , y_train , y_test = addition_dataset (8 , 5000 )
42
52
43
53
print (X_train .shape , X_test .shape )
@@ -60,8 +70,7 @@ def addition_nlp(ReccurentLayer):
60
70
print (accuracy (y_test , predictions ))
61
71
62
72
63
-
64
73
# RNN
65
- # addition_nlp (RNN(16, parameters=Parameters(constraints={'W': SmallNorm(), 'U': SmallNorm()})))
74
+ # addition_problem (RNN(16, parameters=Parameters(constraints={'W': SmallNorm(), 'U': SmallNorm()})))
66
75
# LSTM
67
- addition_nlp (LSTM (16 ))
76
+ addition_problem (LSTM (16 ))
0 commit comments