How to find Gradient of a Function using Python?
The gradient of a function simply means the rate of change of a function. We will use numdifftools to find Gradient of a function.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Input : x^4+x+1 Output :Gradient of x^4+x+1 at x=1 is 4.99 Input :(1-x)^2+(y-x^2)^2 Output :Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is [-4. 2.]
- For Single variable function: For single variable function we can define directly using “lambda” as stated below:-
- For Multi-Variable Function: We will define a function using “def” and pass an array “x” and it will return multivariate function as described below:-
def rosen(x): return (1-x)**2 +(x-x**2)**2
where ‘rosen’ is name of function and ‘x’ is passed as array.
xare array elements in the same order as defined in array.i.e Function defined above is
Similarly, We can define function of more than 2-variables also in same manner as stated above.
Method used: Gradient()
Gradient of x^4+x+1 at x=1 is 4.999999999999998 Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is [-4. 2.]