我已经尝试过使用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”将是轮廓的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')
答案 0 :(得分:2)
正如错误消息所示,您需要E
数组为 2D ,形状为(50,50)
,而不是形状为(2500)
的1D数组。< / p>
有几种解决方法:
在分配后重新塑造您的E
E = E.reshape(len(W1),len(W0))
首先使用正确的形状创建E
,然后使用i
和j
对其进行索引
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))