pythonnumpymatplotlibrelu

matplotlib does not plot zeroes


Currently I am trying to plot a simple Relu function using matplotlib. My problem is that when plotting, matplotlib ignores the zeroes and does not plot them.

Heres my functions

def relu(t):
    t[t <= 0] = 0
    return t

def relu_plot():
    t = np.arange(-2, 2, 0.1)
    k = np.zeros(40)
    plt.plot(t, relu(t))
    plt.show()
    print(len(relu(t)))

relu_plot()

And here is what matplotlib returns enter image description here

The plot works if I instead use an array of size 40 with only zeroes, and the relu function is indeed returning an array of size 40. Any help would be appreciated

Update: Instead of just plotting relu(t), I tried plotting a concatenated array as follows

    k = np.concatenate((np.zeros(20), j))
    plt.plot(t, k)

And it works as expected. I think then that it is a problem with how I changed the values to 0 in the relu function but I am not sure yet.


Solution

  • Your relu function modifies t, so using t for your x variable produces the unexpected results (no longer spanning -2 to 2, but 0 to 2).

    def relu(t):
        return t.clip(min=0)
    

    Output:

    enter image description here