I'm trying to use the contour function of matplotlib.pyplot. I get an error tuple index out of range.
import numpy as np
from sklearn.datasets import make_regression
import matplotlib.pyplot as plt
import math
x, y = make_regression(n_samples=100, n_features=1, noise=10)
y = y abs(y/2)
thetaInitial = np.random.randn(3,1)
thetaFinal = np.random.randn(3,1)
def f(x): return x**2 x
xmesh, ymesh = np.meshgrid(x, y)
print("x :", xmesh.shape); print("y :", ymesh.shape); print("z: ", z.shape)
z = f(np.array([xmesh, ymesh]))
plt.contour(X=xmesh, Y=ymesh, Z= z, levels=20)
tuple index out of range
CodePudding user response:
There are a few problems that need to be addressed:
- Please, read the documentation to obtain contour plots with `help(plt.contour).
- from the docs, you'll see that
x, y
needs to be monotonically sorted. You can achieve that withnp.sort(x.reshape(len(x)))
. - You evaluated your function with
z = f(np.array([xmesh, ymesh]))
, obtaining an array with shape(2, 100, 100)
. From the docs,Z
must be a 2D array. So you have to executeplt.contour(X=xmesh, Y=ymesh, Z=z[0])
orz[1]
.