|
| 1 | +import logging |
| 2 | +from itertools import combinations, islice |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +from sklearn.cross_validation import train_test_split |
| 6 | + |
| 7 | +from mla.metrics import accuracy |
| 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 |
| 12 | +from mla.neuralnet.optimizers import Adam |
| 13 | + |
| 14 | +logging.basicConfig(level=logging.DEBUG) |
| 15 | + |
| 16 | + |
| 17 | +def addition_dataset(dim=10, n_samples=10000, batch_size=64): |
| 18 | + combs = list(islice(combinations(range(2 ** (dim - 1)), 2), n_samples)) |
| 19 | + binary_format = '{:0' + str(dim) + 'b}' |
| 20 | + X = np.zeros((len(combs), dim, 2), dtype=np.uint8) |
| 21 | + y = np.zeros((len(combs), dim, 1), dtype=np.uint8) |
| 22 | + |
| 23 | + for i, (a, b) in enumerate(combs): |
| 24 | + X[i, :, 0] = list(reversed([int(x) for x in binary_format.format(a)])) |
| 25 | + X[i, :, 1] = list(reversed([int(x) for x in binary_format.format(b)])) |
| 26 | + y[i, :, 0] = list(reversed([int(x) for x in binary_format.format(a + b)])) |
| 27 | + |
| 28 | + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1111) |
| 29 | + |
| 30 | + train_b = (X_train.shape[0] // batch_size) * batch_size |
| 31 | + test_b = (X_test.shape[0] // batch_size) * batch_size |
| 32 | + X_train = X_train[0:train_b] |
| 33 | + y_train = y_train[0:train_b] |
| 34 | + |
| 35 | + X_test = X_test[0:test_b] |
| 36 | + y_test = y_test[0:test_b] |
| 37 | + return X_train, X_test, y_train, y_test |
| 38 | + |
| 39 | + |
| 40 | +def addition_nlp(ReccurentLayer): |
| 41 | + X_train, X_test, y_train, y_test = addition_dataset(8, 5000) |
| 42 | + |
| 43 | + print(X_train.shape, X_test.shape) |
| 44 | + model = NeuralNet( |
| 45 | + layers=[ |
| 46 | + ReccurentLayer, |
| 47 | + TimeDistributedDense(1), |
| 48 | + Activation('sigmoid'), |
| 49 | + ], |
| 50 | + loss='mse', |
| 51 | + optimizer=Adam(), |
| 52 | + metric='mse', |
| 53 | + batch_size=64, |
| 54 | + max_epochs=15, |
| 55 | + ) |
| 56 | + # print X_train.shape |
| 57 | + model.fit(X_train, y_train) |
| 58 | + predictions = np.round(model.predict(X_test)) |
| 59 | + predictions = np.packbits(predictions.astype(np.uint8)) |
| 60 | + y_test = np.packbits(y_test.astype(np.int)) |
| 61 | + print(accuracy(y_test, predictions)) |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +# RNN |
| 66 | +# addition_nlp(RNN(16, parameters=Parameters(constraints={'W': SmallNorm(), 'U': SmallNorm()}))) |
| 67 | +# LSTM |
| 68 | +addition_nlp(LSTM(16)) |
0 commit comments