2
votes

I'm following the machine learning course on Coursera, and one of the lectures provides a contour plot of a cost function for linear regression on one variable:

enter image description here

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

I thought it would be useful from an educational standpoint to be able to reproduce this chart. I don't have any octave experience, so I would need step by step instructions that I could paste into the octave command window.

Anyone here able to help with this?


Update:

I ended up with the following:

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 )
1
Have a look at demo ezcontour. You should rewrite your cost function so that it accepts matrices input for theta0 and theta1 - Andy
Thanks Andy. I came up with a different solution with arrayfun inside my function. Is that what you meant by making my function accept matrices? - Chris Snow

1 Answers

1
votes

If you are no able to rewrite your cost funktion so that it accepts matrix inputs you can use 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

gives print