Home > Back-end >  How to correctly compute the gradient of a curve using numpy gradient?
How to correctly compute the gradient of a curve using numpy gradient?

Time:05-15

I have a curve which is composed of 1200 values and i just want to compute its derivative so i use numpy gradient function.

Here is the code i'm using:

data = np.genfromtxt('test_data.csv', delimiter=',')
support = np.array(np.arange(1200))
plt.plot(support, data)
plt.show()
plt.plot(support, np.gradient(data, support))
plt.show()

Here is the curve plot:

Curve plot

And here is the gradient plot:

Gradient plot

Why is there positives values at the begining of the gradient curve ? My curve is strictly decreasing on [0; 600], and why is there so much noise ?

I'm putting down the data in the CSV if you want to check it out:

Zoomed plot

Your data is noisy, and the gradient of a noisy function always appears noisier.

You can apply a simple moving average to smooth your data:

w = 25
smooth = np.convolve(data, np.ones(w), 'valid') / w
smooth_support = support[w//2:-w//2 1]
plt.plot(smooth_support, smooth)
plt.show()
plt.plot(smooth_support, np.gradient(smooth, smooth_support))
plt.show()

Smoothed Smoothed gradient

Of course, instead of using a flat convolution kernel (like np.ones()) you can use a better approach from scipy.signal.

  • Related