UFLDL Tutorial-Logistic Regression

新手学习,如果哪里写错了,欢迎指正。
这门课程网站是http://ufldl.stanford.edu/tutorial/
逻辑回归强调的是最后的结果不是一个数值,而是一个类别或者说是对应各个类别的概率。所以希望得到的结果不是一个具体的数,而是分类。学到后面就会发现前面这里其实很简单,但是代码里面有几个循环,写完跑起来就真的是拼耐心的时候了。建议这里写完先不要运行代码,先学习下一节梯度检查后再在这里先检查下梯度算得对不对,看一两个结果就可以。误差数量级很小的话就可以安心把它丢去跑一跑,切记要有耐心。下面贴出代码和运行结果

function [f,g] = logistic_regression(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.
  %
  n=size(X,1);%行数
  m=size(X,2);%列数

  % initialize objective value and gradient.
  f = 0;
  g = zeros(size(theta));


  %
  % TODO:  Compute the objective function by looping over the dataset and summing
  %        up the objective values for each example.  Store the result in 'f'.
  %
  % TODO:  Compute the gradient of the objective by looping over the dataset and summing
  %        up the gradients (df/dtheta) for each example. Store the result in 'g'.
  %
%%% YOUR CODE HERE %%%
for i=1:m
    f=f+y(i)*log(sigmoid(theta'*X(1:n,i)))+(1-y(i))*log(1-sigmoid(theta'*X(1:n,i)));
end
f = f*(-1);
for j=1:size(theta)
    for i=1:m
        g(j)=g(j)+X(j,i)*(sigmoid(theta'*X(1:n,i))-y(i));
    end
end

结果如下图
这里写图片描述
大家不妨算下。。。大概跑了五个多小时吧。。。这样的代码要是要依靠运行的结果来判断对错然后再修改代码要等到哭的。。。代码跑了三个小时后我就很醉了,上网查了不少资料,找到的唯一一篇贴出运行时间的文章,又是使用了向量计算而不是单纯的循环。
当然不知道是不是我的电脑的缘故,所以欢迎大家用for循环实现后留言告诉我运行时长。下一节讲下梯度检测那节。

你可能感兴趣的:(DL-深度学习)