Plot_decision_boundary

Dear Instructors,

I am struggling to understand how the ungraded plot_decision_boundary function works in Week 3

Planar_data_classification_with_one_hidden_layer coding exercise (planar_utils.py). I know it is not part of the grading, but I want to understand how the full code works.

In particular, I do not understand the purpose and the mathematics behind the reshaping Z.
For convenience, copied the function and added my question within the code.

Thank you for your help!

def plot_decision_boundary(model, X, y):
    # Set min and max values and give it some padding
    x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
    y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))#https://numpy.org/doc/stable/reference/generated/numpy.arange.html Return evenly spaced values within a given interval.
    # Predict the function value for the whole grid
    Z = model(np.c_[xx.ravel(), yy.ravel()])#https://numpy.org/doc/stable/reference/generated/numpy.c_.html Translates slice objects to concatenation along the second axis. 
    

    #Question 2 
    #Planar_data_classification_with_one_hidden_layer 
    #what is np.c_ doing in this case? is this creating a list of tuples?
    #xx.ravel() (1038240,) 
    ## yy.ravel()(1038240,)
    ## np.c_(1038240, 2) Seems to stack horisontally xx and yy
    ## z (1008, 1030) multiplying the two gives 1038240 i.e. the dimension of xx, but how were these numbers computed?
    ## Could you please explain how what we did? 
    
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) # further down Z is passed to controurf function.
    # I understood Z is the height? 
    #https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contourf.html
    plt.ylabel('x2')
    plt.xlabel('x1')
    plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)

Hello @Kaiju,

For example, have a look at

There are plenty of resources around the web that use similar constructs as plot_decision_boundary(model, X, y).

I hope that article helps you understand the techniques used :slight_smile:

1 Like

Great article, thanks for sending !