Generate binary addition dataset. http://devankuleindiren.com/Projects/rnn_arithmetic.php
(dim=10, n_samples=10000, batch_size=64)
| 18 | |
| 19 | |
| 20 | def addition_dataset(dim=10, n_samples=10000, batch_size=64): |
| 21 | """Generate binary addition dataset. |
| 22 | http://devankuleindiren.com/Projects/rnn_arithmetic.php |
| 23 | """ |
| 24 | binary_format = "{:0" + str(dim) + "b}" |
| 25 | |
| 26 | # Generate all possible number combinations |
| 27 | combs = list(islice(combinations(range(2 ** (dim - 1)), 2), n_samples)) |
| 28 | |
| 29 | # Initialize empty arrays |
| 30 | X = np.zeros((len(combs), dim, 2), dtype=np.uint8) |
| 31 | y = np.zeros((len(combs), dim, 1), dtype=np.uint8) |
| 32 | |
| 33 | for i, (a, b) in enumerate(combs): |
| 34 | # Convert numbers to binary format |
| 35 | X[i, :, 0] = list(reversed([int(x) for x in binary_format.format(a)])) |
| 36 | X[i, :, 1] = list(reversed([int(x) for x in binary_format.format(b)])) |
| 37 | |
| 38 | # Generate target variable (a+b) |
| 39 | y[i, :, 0] = list(reversed([int(x) for x in binary_format.format(a + b)])) |
| 40 | |
| 41 | X_train, X_test, y_train, y_test = train_test_split( |
| 42 | X, y, test_size=0.2, random_state=1111 |
| 43 | ) |
| 44 | |
| 45 | # Round number of examples for batch processing |
| 46 | train_b = (X_train.shape[0] // batch_size) * batch_size |
| 47 | test_b = (X_test.shape[0] // batch_size) * batch_size |
| 48 | X_train = X_train[0:train_b] |
| 49 | y_train = y_train[0:train_b] |
| 50 | |
| 51 | X_test = X_test[0:test_b] |
| 52 | y_test = y_test[0:test_b] |
| 53 | return X_train, X_test, y_train, y_test |
| 54 | |
| 55 | |
| 56 | def addition_problem(ReccurentLayer): |