【问题标题】:Plotting contour plot of minimum square estimate function in matplotlib在 matplotlib 中绘制最小二乘估计函数的等高线图
【发布时间】:2021-03-03 03:46:16
【问题描述】:

为了可视化我的线性回归模型的梯度下降,我正在尝试为以下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有效的方法来制作这个函数的等高线图?

【问题讨论】:

    标签: python matplotlib machine-learning contour mse


    【解决方案1】:

    您不需要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)
    

    具有以下输出轮廓

    【讨论】:

      猜你喜欢
      • 2011-09-16
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 2021-09-08
      • 2019-10-24
      • 2018-07-18
      相关资源
      最近更新 更多