Calculate the derivative of the sum of a mathematical function-MATLAB -
in matlab want create partial derivative of cost function called j(theta_0, theta_1)
(in order calculations necessary gradient descent).
the function j(theta_0, theta_1)
defined as:
lets h_theta(x) = theta_1 + theta_2*x
. also: alpha
fixed, starting values of theta_1
, theta_2
given. let's in example: alpha = 0.1
theta_1 = 0
, theta_2 = 1
. also have values x , y in 2 different vectors.
vectorofx = 5 5 6 vectorofx = 6 6 10
steps took seek solve in matlab: have no clue how solve problem in matlab. started off trying define function in matlab , tried this:
theta_1 = 0 theta_2 = 1 syms x; h_theta(x) = theta_1 + t2*x;
this worked, not wanted. wanted x^(i), in vector. next thing tried was:
theta_1 = 0 theta_2 = 1 syms x; h_theta(x) = theta_1 + t2*vectorofx(1);
this gives next error:
error using sym/subsindex (line 672) invalid indexing or function definition. when defining function, ensure body of function sym object. when indexing, input must numeric, logical or ':'. error in prog1>gradientdescent (line 46) h_theta(x) = theta_1 + theta_2*vectorofx(x);
i looked error , don't know how solve particular example. have feeling create matlab work against me instead of using in favor.
when have perform symbolic computations prefer utilize mathematica. in environment code partial derivatives looking for.
j[th1_, th2_, m_] := sum[(th1 + th2*subscript[x, i] - subscript[y, i])^2, {i, 1, m}]/(2*m) d[j[th1, th2, m], th1] d[j[th1, th2, m], th2]
and gives
coming matlab can solve problem next code
%// constants. alpha = 0.1; theta_1 = 0; theta_2 = 1; x = [5 ; 5 ; 6]; y = [6 ; 6 ; 10]; %// number of points. m = length(x); %// partial derivatives. dtheta1 = @(theta_1, theta_2) sum(2*(theta_1+theta_2*x-y))/2/m; dtheta2 = @(theta_1, theta_2) sum(2*x.*(theta_1+theta_2*x-y))/2/m; %// loop initialization. toll = 1e-5; maxiter = 100; = 0; err = 1; theta_1_last = theta_1; theta_2_last = theta_2; %// iterations. while err>toll && it<maxiter theta_1 = theta_1 - alpha*dtheta1(theta_1, theta_2); theta_2 = theta_2 - alpha*dtheta2(theta_1, theta_2); = + 1; err = norm([theta_1-theta_1_last ; theta_2-theta_2_last]); theta_1_last = theta_1; theta_2_last = theta_2; end
unfortunately case iterations not converge.
matlab not flexible symbolic computations, way partial derivatives following
m = 10; syms th1 th2 x = sym('x', [m 1]); y = sym('y', [m 1]); j = @(th1, th2) sum((th1+th2.*x-y).^2)/2/m; diff(j, th1) diff(j, th2)
matlab function derivative
No comments:
Post a Comment