I want to plot a simple illustration of using derivative to find out a slope of a function at any point. It would look kinda like this:
I have already plotted a simple parabola using this code:
import numpy as np
from matplotlib import pyplot as plt
inputs = 0.2
weights = np.arange(-6,14)
target_prediction = 0.7
prediction = inputs*weights
errors = (prediction - target_prediction) ** 2
plt.xlabel("Weight")
plt.ylabel("Error")
plt.plot(weights, error)
Now I want to add something like this:
current_weight = 5
# draw a short fraction of a line to represent slope
x = np.arange(optimal_weight - 3, optimal_weight + 3)
# derivative
slope = 2 * (inputs*current_weight - target_prediction)
y = slope*x # How should this equation look like?
plt.plot(x, y)
To draw a tangent line going through the current_weight
.
But I can't seem to figure this out, can you help?
To find the slope of a line tangent to a parabola at a specific point, find the derivative of the parabola's equation, then substitute the -coordinate of the specific point in the new equation.
Once you have the slope at the desired point, you need to write the equation for the tangent line using point-slope form:
# Define parabola
def f(x):
return x**2
# Define parabola derivative
def slope(x):
return 2*x
# Define x data range for parabola
x = np.linspace(-5,5,100)
# Choose point to plot tangent line
x1 = -3
y1 = f(x1)
# Define tangent line
# y = m*(x - x1) + y1
def line(x, x1, y1):
return slope(x1)*(x - x1) + y1
# Define x data range for tangent line
xrange = np.linspace(x1-1, x1+1, 10)
# Plot the figure
plt.figure()
plt.plot(x, f(x))
plt.scatter(x1, y1, color='C1', s=50)
plt.plot(xrange, line(xrange, x1, y1), 'C1--', linewidth = 2)
You can do this for any differentiable function, and can use derivative approximation methods (such as finite differencing) to eliminate the need to provide the analytical derivative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With