contour graph tuple index out of range

Question:

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
Asked By: problème0123

||

Answers:

There are a few problems that need to be addressed:

  1. Please, read the documentation to obtain contour plots with `help(plt.contour).
  2. from the docs, you’ll see that x, y needs to be monotonically sorted. You can achieve that with np.sort(x.reshape(len(x))).
  3. 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 execute plt.contour(X=xmesh, Y=ymesh, Z=z[0]) or z[1].
Answered By: Davide_sd
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.