Somewhat improved code for Week 3 Programming Assigment, for the "Tuning hidden layer size" extra

Here is a last on for the maintenance team:

Somewhat improved code for Week 3 Programming Assigment, part

Tuning hidden layer size (optional/ungraded exercise)

It also prints the time elapsed and the accuracy computation is unfolded (it should be in a facility function, as accuracy is computed three times in the page, but this will do) :sunglasses:

import time

# This may take about 2 minutes to run

plt.figure(figsize=(16, 32))
# hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]
hidden_layer_sizes = [1, 2, 3, 4, 5]

# you can try with different hidden layer sizes
# but make sure before you submit the assignment it is set as "hidden_layer_sizes = [1, 2, 3, 4, 5]"
# hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]

num_iterations = 5000

for i, n_h in enumerate(hidden_layer_sizes):
    plt.subplot(5, 2, i+1)
    plt.title('Hidden Layer of size %d' % n_h)
    print (f"Training model with hidden layer of size {n_h} with {num_iterations} iterations")
    start_time = time.process_time()    
    parameters = nn_model(X, Y, n_h, num_iterations)
    end_time = time.process_time()
    print (f"Training done in {(end_time-start_time):.2f} seconds")
    # Plot
    plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)    
    # Compute accuracy
    predictions = predict(parameters, X)    
    count_1_1_matches = np.dot(Y,predictions.T).item()
    count_0_0_matches = np.dot(1-Y,1-predictions.T).item() 
    count_matches = count_1_1_matches + count_0_0_matches
    accuracy = count_matches/float(Y.size)
    accuracy = accuracy * 100 # percent
    print (f"Accuracy for {n_h} hidden units: {int(accuracy)} %")
1 Like

Thanks.

1 Like