新手学习,如果哪里写错了,欢迎指正。
这门课程网站是http://ufldl.stanford.edu/tutorial/
这一节主要是将如果遇到循环次数较多的情况下,matlab跑起来就很慢了。这种情况下就该想办法改进了,于是引出了这一节。
当我们按照常规思维对矩阵进行分块运算,最后发现运行时间很长。正如课程第二节我实现的逻辑回归代码,跑起来巨慢。这个时候可以直接转换思维,对整个矩阵进行操作,从而达到快速计算的结果。大体就是这个样子了。
线性回归改进后的代码如下
function [f,g] = linear_regression_vec(theta, X,y)
%
% Arguments:
% theta - A vector containing the parameter values to optimize.
% X - The examples stored in a matrix.
% X(i,j) is the i'th coordinate of the j'th example.
% y - The target value for each example. y(j) is the target for example j.
%
m=size(X,2);
% initialize objective value and gradient.
f = 0;
g = zeros(size(theta));
%
% TODO: Compute the linear regression objective function and gradient
% using vectorized code. (It will be just a few lines of code!)
% Store the objective function value in 'f', and the gradient in 'g'.
%
%%% YOUR CODE HERE %%%
g = X*((theta'*X)-y)';
temp =(theta'*X)-y;
f = temp*temp'*0.5;
跑出来的效果是这样的
当然运行多几次会发现,有时Test error是超过5的。个人猜测是随机初始theta的影响。
至于逻辑回归部分的改进,由于我的matlab水平很一般,所以一开始实现如下:
function [f,g] = logistic_regression_vec(theta, X,y)
%
% Arguments:
% theta - A column vector containing the parameter values to optimize.
% X - The examples stored in a matrix.
% X(i,j) is the i'th coordinate of the j'th example.
% y - The label for each example. y(j) is the j'th example's label.
%
m=size(X,2);
% initialize objective value and gradient.
f = 0;
g = zeros(size(theta));
%
% TODO: Compute the logistic regression objective function and gradient
% using vectorized code. (It will be just a few lines of code!)
% Store the objective function value in 'f', and the gradient in 'g'.
%
%%% YOUR CODE HERE %%%
temp = theta'*X;
temp1 = zeros(size(temp));
temp2 = zeros(size(temp));
temp3 = zeros(size(temp));
for i=1:m
temp1(i) = log(sigmoid(temp(i)));
temp2(i) = log(1-sigmoid(temp(i)));
temp3(i) = sigmoid(temp(i));
end
yi =1-y;
f = y*temp1'+yi*temp2';
f = f*-1;
g = X*(temp3-y)';
效果也很一般
看的出来很慢,后来看了这位仁兄的实现,学习了一下
http://blog.csdn.net/songrotek/article/details/41287417
发现原来log和sigmoid函数也可以用于向量的操作,改了之后速度果然快了很多。
学到这一节突然想写下博客,前两节的后面补上。