()
| 16 | |
| 17 | |
| 18 | def random_search(): |
| 19 | # get the data and split into train/test |
| 20 | X, Y = get_spiral() |
| 21 | # X, Y = get_clouds() |
| 22 | X, Y = shuffle(X, Y) |
| 23 | Ntrain = int(0.7*len(X)) |
| 24 | Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain] |
| 25 | Xtest, Ytest = X[Ntrain:], Y[Ntrain:] |
| 26 | |
| 27 | # starting hyperparameters |
| 28 | M = 20 |
| 29 | nHidden = 2 |
| 30 | log_lr = -4 |
| 31 | log_l2 = -2 # since we always want it to be positive |
| 32 | max_tries = 30 |
| 33 | |
| 34 | |
| 35 | # loop through all possible hyperparameter settings |
| 36 | best_validation_rate = 0 |
| 37 | best_hls = None |
| 38 | best_lr = None |
| 39 | best_l2 = None |
| 40 | for _ in range(max_tries): |
| 41 | model = ANN([M]*nHidden) |
| 42 | model.fit( |
| 43 | Xtrain, Ytrain, |
| 44 | learning_rate=10**log_lr, reg=10**log_l2, |
| 45 | mu=0.99, epochs=3000, show_fig=False |
| 46 | ) |
| 47 | validation_accuracy = model.score(Xtest, Ytest) |
| 48 | train_accuracy = model.score(Xtrain, Ytrain) |
| 49 | print( |
| 50 | "validation_accuracy: %.3f, train_accuracy: %.3f, settings: %s, %s, %s" % |
| 51 | (validation_accuracy, train_accuracy, [M]*nHidden, log_lr, log_l2) |
| 52 | ) |
| 53 | if validation_accuracy > best_validation_rate: |
| 54 | best_validation_rate = validation_accuracy |
| 55 | best_M = M |
| 56 | best_nHidden = nHidden |
| 57 | best_lr = log_lr |
| 58 | best_l2 = log_l2 |
| 59 | |
| 60 | # select new hyperparams |
| 61 | nHidden = best_nHidden + np.random.randint(-1, 2) # -1, 0, or 1 |
| 62 | nHidden = max(1, nHidden) |
| 63 | M = best_M + np.random.randint(-1, 2)*10 |
| 64 | M = max(10, M) |
| 65 | log_lr = best_lr + np.random.randint(-1, 2) |
| 66 | log_l2 = best_l2 + np.random.randint(-1, 2) |
| 67 | print("Best validation_accuracy:", best_validation_rate) |
| 68 | print("Best settings:") |
| 69 | print("best_M:", best_M) |
| 70 | print("best_nHidden:", best_nHidden) |
| 71 | print("learning_rate:", best_lr) |
| 72 | print("l2:", best_l2) |
| 73 | |
| 74 | |
| 75 | if __name__ == '__main__': |
no test coverage detected