当前位置: 代码迷 >> 综合 >> Coursera-MachineLearning-Week6编程题目整理
  详细解决方案

Coursera-MachineLearning-Week6编程题目整理

热度:109   发布时间:2023-11-11 07:03:55.0

linearRegCostFunction.m

J = 1/(2*m)*sum((X*theta-y).^2)+lambda/(2*m)*(sum(theta.^2)-theta(1).^2);
%去除常数项的正则化代价函数grad = 1/m*X'*(X*theta-y)+lambda/m*theta;  %正则化梯度
grad(1) = grad(1) -lambda/m*theta(1);  %常数项不进行正则化

learningCurve.m

for i = 1:mtheta = trainLinearReg(X(1:i,:), y(1:i,:), lambda);  %计算出参数thetaerror_train(i) = linearRegCostFunction(X(1:i,:), y(1:i,:), theta, 0);  %计算训练数据集误差error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);  %计算交叉验证集误差
end

validationCurve.m

for i = 1 : length(lambda_vec)lambda = lambda_vec(i);  %选择lambda的值theta = trainLinearReg(X, y, lambda);  %计算出参数thetaerror_train(i) = linearRegCostFunction(X, y, theta, 0);  %计算训练数据集误差error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);  %计算交叉验证集误差
end

polyFeatures.m

for i=1:numel(X)  %numel用于获取数组的元素数量for j=1:p  %幂次X_poly(i,j)=X(i,:).^j;end
end