【问题标题】:How to plot a contour graph for a linear regression cost function?如何绘制线性回归成本函数的等高线图?
【发布时间】:2016-09-30 16:59:12
【问题描述】:

我正在关注 Coursera 上的 machine learning course,其中一堂课提供了一个变量线性回归的成本函数的等高线图:

来源:https://www.coursera.org/learn/machine-learning/lecture/nwpe2/cost-function-intuition-ii

我认为从教育的角度来看,能够复制此图表会很有用。我没有任何 octave 经验,所以我需要逐步说明,我可以将其粘贴到 octave 命令窗口中。

这里有人可以帮忙吗?


更新:

我最终得到了以下结果:

function cost = calc_cost (theta0, theta1)
   x = 1:10;
   y = x.*2;
   cost = arrayfun( @(t0, t1) ( 1/(length(x)) * sum( ((t0 + t1*x) - y).^2 )), theta0, theta1);
endfunction

[xx, yy] = meshgrid( -3000:50:3000, -3000:50:3000) ;
zz = calc_cost(xx, yy);
contour(xx, yy, zz )

【问题讨论】:

  • 看看demo ezcontour。您应该重写您的成本函数,以便它接受 theta0 和 theta1 的矩阵输入
  • 谢谢安迪。我想出了一个不同的解决方案,在我的函数中使用了 arrayfun。这就是你让我的函数接受矩阵的意思吗?

标签: octave


【解决方案1】:

如果您无法重写成本函数以使其接受矩阵输入,则可以使用 arrayfun:

function cost = calc_cost (theta0, theta1)
   x = 1:10;
   y = x.*2;
   cost = ( 1/(length(x)) * sum( ((theta0 + theta1*x) - y).^2 ) );
 endfunction

[x,y] = meshgrid (linspace(-5000,5000,20), linspace(-500,500,20));
z = arrayfun (@calc_cost, x, y);
contour (x, y, z)
print out.png

给予

【讨论】:

    猜你喜欢
    • 2021-03-18
    • 2018-10-20
    • 2021-12-20
    • 2020-11-01
    • 2014-02-20
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多