在matplotlib中绘制最小平方估计函数的等高线图

Plotting contour plot of minimum square estimate function in matplotlib

为了可视化我的线性回归模型的梯度下降,我正在尝试为以下 mse 函数绘制等高线图:

import jax.numpy as jnp
import numpy as np

def make_mse(x, t):  
  def mse(w,b): 
    return np.sum(jnp.power(x.dot(w) + b - t, 2))/2
  return mse 

其中图的 xy 轴对应于 wb 参数。

xt 与情节无关,因为 x 的值每次都只是乘以 w 的单个值.

我正在尝试执行以下操作:

x = np.linspace(-1.0,1.0,500)
t = 5*x + 1

xcoord = np.linspace(-10.0,10.0,50)
ycoord = np.linspace(-10.0,10.0,50)
w1,w2 = np.meshgrid(xcoord,ycoord)

Z = make_mse(x, t)(w1,w2)

但是,我得到了点积的明显错误:

/usr/local/lib/python3.7/dist-packages/jax/_src/lax/lax.py in dot(lhs, rhs, precision, preferred_element_type)
    634   else:
    635     raise TypeError("Incompatible shapes for dot: got {} and {}.".format(
--> 636         lhs.shape, rhs.shape))
    637 
    638 

TypeError: Incompatible shapes for dot: got (1000, 1) and (50, 50).

是否有任何 pythonic 有效的方法来绘制此函数的等高线图?

您不需要 np.sum(),因为您需要每个网格点的 MSE,而不是它们的总和。此外,x 的维度和网格必须匹配。以下作品:

import numpy as np

def make_mse(x, t):  
  def mse(w,b): 
    return np.power(x.dot(w) + b - t, 2)
  return mse 

x = np.linspace(-1.0,1.0,500)
t = 5*x + 1

xcoord = np.linspace(-10.0,10.0,500)
ycoord = np.linspace(-10.0,10.0,500)
w1,w2 = np.meshgrid(xcoord,ycoord)

Z = make_mse(x, t)(w1,w2)
plt.contourf(w1,w2,Z)

具有以下输出轮廓