使用plt.contour时出错:输入z必须是一个二维数组。

4
我在使用matplotlib的plt.contour函数时,收到了错误信息"Input z must be a 2D array"。

我已经尝试过使用meshgrid,但它并没有起作用,我无法找到问题所在。E = np.zeros(2500)是一个数组,所以我找不到错在何处。

import numpy as np
import numpy.random as rd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mkgrid2d import *

W1 = np.linspace(-1.0,3.0,num = 50)
W0 = np.linspace(-2.0,4.0,num = 50)

w11 = 1.00
w00=1.0

w = np.array([[w11],[w00]],dtype=float)

mew = 0
sigma = np.sqrt(2)


Npts=50;rd.seed(1)
x1=rd.rand(1,Npts)*10.-5.0 #Npts uniformemente distribuídos
r = np.random.normal(mew, sigma, 50)*2.-1.0#ruído gaussiano distribuído

X = np.vstack((x1,np.ones((1,x1.shape[1]))))
X = X.astype('float') #converter para float

N=Npts 

y = np.dot(w.T,X) + r
E= np.zeros(2500) 

“E”将成为Contour的Z。
count = 0
for i in range (len(W1)):
    for j in range (len (W0)):
        w1 = np.array([W1[i],W0[j]])
        yn = np.dot(w1.T,X)
        E[count] = (1./50)*(np.sum((y-yn)**2))
        count +=1

plt.figure()
CS = plt.contour(W1,W0,E)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('Simplest default with labels')
        
1个回答

3

正如错误信息所述,你需要使E数组成为一个2D的数组,形状为(50,50),而不是形状为(2500)的1D数组。

有几种方法可以解决这个问题:

  1. reshape your E after assigning it

    E = E.reshape(len(W1),len(W0))
    
  2. create E with the correct shape in the first place, then use your i and j to index it

    E = np.zeros((len(W1),len(W0)))
    
    for i in range (len(W1)):
        for j in range (len (W0)):
            w1 = np.array([W1[i],W0[j]])
            yn = np.dot(w1.T,X)
            E[i][j] = (1./50)*(np.sum((y-yn)**2))
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接