Project - Building Cat vs Non-Cat Image Classifier using NumPy and ANN

26 / 32

Cat vs Non-cat Classifier - Defining some utility functions - Optimize

The Optimize function:

  • implements both the forward and backward propagations by calling the propagate function for each iteration.
  • updates the weights and bias matrices based on the gradients received from the propagate function.
  • predicts the labels for train and test datasets by calling the predict function
  • calculates the accuracies
  • returns the parameter values that yield the optimal test accuracies.

Copy-paste the following code for the optimize function.

Call the propagate function, predict function and get_accuracies function at the appropriate places inside the optimize function.

def optimize(w, b, X, Y, X_val, Y_val, num_iterations, learning_rate):
    final_w = w
    final_b = b

    for i in range(num_iterations):

        # Call Propagate function to get Cost and gradients
        grads, cost = << your code comes here >>(w, b, X, Y)

        # Get derivatives
        dw = grads['dw']
        db = grads['db']

        # Update rule
        w = w - learning_rate * dw
        b = b - learning_rate * db

        # Predict labels for train and validation sets        
        Y_prediction_train = << your code comes here >>(w, b, X)
        Y_prediction_val =  << your code comes here >>(w, b, X_val)

        # Get accuracies for the train and validation predictions
        train_acc =  << your code comes here >>(Y_prediction_train , Y)
        val_acc =  << your code comes here >>(Y_prediction_val, Y_val)

        if val_acc > prev_val_acc and train_acc>=val_acc:
            print("Epoch - {} - train accuracy: {} %".format(i,train_acc))
            print("Epoch - {} - val accuracy: {} %".format(i,val_acc))
            prev_train_acc = train_acc
            prev_val_acc = val_acc
            epoch = i
            final_w = w
            final_b = b

    params = {'w': w, 'b': b}
    grads = {'dw': dw, 'db': db}

    optimal_values = {
        'costs': costs,
        'final w':final_w,
        'final b':final_b,
        'Train accuracy':prev_train_acc,
        'Validation accuracy': prev_val_acc,
        'Y_prediction_val': Y_prediction_val,
        'Y_prediction_train': Y_prediction_train,

    return optimal_values
Get Hint See Answer

Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...