机器学习之Regularized Linear Regression and Bias v.s. Variance

这篇博客探讨了机器学习中的正则化线性回归,并深入理解偏差与方差的概念。通过`linearRegCostFunction.m`、`learningCurve.m`和`validationCurve.m`三个代码示例,展示了如何在实践中平衡模型的复杂度与性能。
摘要由CSDN通过智能技术生成

学习中的各种纠结,心得,小知识在代码里面喽

linearRegCostFunction.m

function [J, grad] = linearRegCostFunction(X, y, theta, lambda)
%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear 
%regression with multiple variables
%   [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the 
%   cost of using theta as the parameter for linear regression to fit the 
%   data points in X and y. Returns the cost in J and the gradient in grad

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost and gradient of regularized linear 
%               regression for a particular choice of theta.
%
%               You should set J to the cost and grad to the gradient.
%


theta_meddile=theta(2:end);
%搞了半天是截取的问题啊,[0;theta(2:end)]
%theta截取的时候要不要有前面的冒号???
J=1 / (2 * m) *sum((X*theta-y).^2)+lambda / (2 * m) *sum(theta_meddile.^2);
%?????为什么theta平方的时候第一项要变成0??????因为不需要regularize第一项
%正确与否和m的位置无关


%grad = X' * (X*theta - y) / m + [0;theta(2:end)] * lambda / m;
grad=(1/m)*(X'*(X*theta-y))+lambda*(1/m)*[0;theta(2:end)];
%gg=lambda*(1/m)*theta;
%grad=grad+[0;gg(2:end)];
%这次的错误出在。。。。。。。唉,太无语了。。。。是grad运算出错,(X'*(X*theta-y))得到了
%3行1列的数据,与theta相符合,而之前的没有做到


% =========================================================================

grad = grad(:);

end

learningCurve.m

function [error_train, error_val] = ...
    learningCurve(X, y, Xval, yval, lambda)
%LEARNINGCURVE Generates the train and cross validation set errors needed
%to plot a learning curve
%   [error_train, error_val] = ...
%       LEARNINGCURVE(X, y, Xval, yval, lambda) returns the train and
%       cross validation set errors for a learning curve. In particular,
%       it returns two vectors of the same length - error_train and
%       error_val. Then, error_train(i) contains the training error for
%       i examples (and similarly for error_val(i)).
%
%   In this function, you will compute the train and test errors for
%   dataset sizes from 1 up to m. In practice, when working with larger
%   datasets, you might want to do this in larger intervals.
%

% Number of training examples
m = size(X, 1);

% You need to return these values correctly
error_train = zeros(m, 1);
error_val   = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return training errors in
%               error_train and the cross validation errors in error_val.
%               i.e., error_train(i) and
%               error_val(i) should give you the errors
%               obtained after training on i examples.
%
% Note: You should evaluate the training error on the first i training
%       examples (i.e., X(1:i, :) and y(1:i)).
%
%       For the cross-validation error, you should instead evaluate on
%       the _entire_ cross validation set (Xval and yval).
%
% Note: If you are using your cost function (linearRegCostFunction)
%       to compute the training and cross validation error, you should
%       call the function with the lambda argument set to 0.
%       Do note that you will still need to use lambda when running
%       the training to obtain the theta parameters.
%
% Hint: You can loop over the examples with the following:
%
%       for i = 1:m
%           % Compute train/cross validation errors using training examples
%           % X(1:i, :) and y(1:i), storing the result in
%           % error_train(i) and error_val(i)
%           ....
%
%       end
%

% ---------------------- Sample Solution ----------------------

for i=1:m
    theta=trainLinearReg([ones(i,1),X(1:i, :)], y(1:i), lambda);
    %原来theta是这么来的,
    %而且前面必须加1啊
    %ones必须是标量?用i
    %获取theta的时候也应该i个
    %这个地方,获取theta的时候应该用lambda
    error_train(i)=linearRegCostFunction([ones(i,1),X(1:i, :)], y(1:i), theta, 0);
    error_val(i)=linearRegCostFunction([ones(size(Xval,1),1),Xval], yval, theta, 0);
    %xval要用全部,不同的是theta
end



% -------------------------------------------------------------

% =========================================================================

end

validationCurve.m

function [lambda_vec, error_train, error_val] = ...
    validationCurve(X, y, Xval, yval)
%VALIDATIONCURVE Generate the train and validation errors needed to
%plot a validation curve that we can use to select lambda
%   [lambda_vec, error_train, error_val] = ...
%       VALIDATIONCURVE(X, y, Xval, yval) returns the train
%       and validation errors (in error_train, error_val)
%       for different values of lambda. You are given the training set (X,
%       y) and validation set (Xval, yval).
%

% Selected values of lambda (you should not change this)
lambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';

% You need to return these variables correctly.
error_train = zeros(length(lambda_vec), 1);
error_val = zeros(length(lambda_vec), 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return training errors in
%               error_train and the validation errors in error_val. The
%               vector lambda_vec contains the different lambda parameters
%               to use for each calculation of the errors, i.e,
%               error_train(i), and error_val(i) should give
%               you the errors obtained after training with
%               lambda = lambda_vec(i)
%
% Note: You can loop over lambda_vec with the following:
%
%       for i = 1:length(lambda_vec)
%           lambda = lambda_vec(i);
%           % Compute train / val errors when training linear
%           % regression with regularization parameter lambda
%           % You should store the result in error_train(i)
%           % and error_val(i)
%           ....
%
%       end
%
%

for i = 1:length(lambda_vec)
    lambda = lambda_vec(i);
    [theta]=trainLinearReg(X, y, lambda);
    %由于theta是数组,所以应该加上【】
    error_train(i)=linearRegCostFunction(X, y, theta, 0);
    error_val(i)=linearRegCostFunction(Xval, yval, theta, 0);
end



% =========================================================================

end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值