现在的位置: 首页 > 综合 > 正文

ufldl学习笔记与编程作业:Softmax Regression(softmax回归)

2018年04月13日 ⁄ 综合 ⁄ 共 2271字 ⁄ 字号 评论关闭

ufldl学习笔记与编程作业:Softmax Regression(softmax回归)

ufldl出了新教程,感觉比之前的好,从基础讲起,系统清晰,又有编程实践。

在deep learning高质量群里面听一些前辈说,不必深究其他机器学习的算法,可以直接来学dl。

于是最近就开始搞这个了,教程加上matlab编程,就是完美啊。

新教程的地址是:http://ufldl.stanford.edu/tutorial/

本节学习链接:http://ufldl.stanford.edu/tutorial/supervised/SoftmaxRegression/

softmax回归其实是逻辑回归的扩展形式,

逻辑回归通常用作2类的分类器,

softmax则用作多类的分类器。

从数学形式来说,其实逻辑回归就是softmax回归中k=2的情况。这点教程里也说了。

softmax的目标函数和参数的偏导数教程推导也很清楚。

对于编程作业,由于对matlab实现不熟,跳了很多坑。

弄了很久,而且还只是用for循环来实现的。

这次终于体会到了,for循环的性能之差了。迭代了200次,1个多小时。

也跟这个模型比前两个模型复杂有关。

先贴第一个版本的代码吧。以后想出了向量化的编程再补上。

以下是softmax_regression.m的代码

function [f,g] = softmax_regression_vec(theta, X,y)
  %
  % Arguments:
  %   theta - A vector containing the parameter values to optimize.
  %       In minFunc, theta is reshaped to a long vector.  So we need to
  %       resize it to an n-by-(num_classes-1) matrix.
  %       Recall that we assume theta(:,num_classes) = 0.
  %
  %   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);
  n=size(X,1);

  %theta本来是矩阵,传参的时候,theta(:)这样进来的,是一个vector,只有一列,现在我们得把她变为矩阵
  % theta is a vector;  need to reshape to n x num_classes.
  theta=reshape(theta, n, []);
  num_classes=size(theta,2)+1;
  
  % initialize objective value and gradient.
  f = 0;
  g = zeros(size(theta));

  h = theta'*X;%h(k,i)第k个theta,第i个样本  麻痹还是得循环求啊
  a = exp(h);
  a = [a;ones(1,size(a,2))];%加行
  b = sum(a,1);

  for i=1:m
    for j=1:num_classes
      if y(i)!=j
        continue;
      end
      f+=log2(a(j,i)/b(i));
    end
  end
  f=-f;%符号


  flag=0;
  for j=1:num_classes-1
    for i=1:m
      if (y(i)==j)
        flag =1;
      else 
        flag=0;
      end
      g(:,j)+=X(:,i)*(a(j,i)/b(i)-flag);
    end
  end
  %
  % TODO:  Compute the softmax objective function and gradient using vectorized code.
  %        Store the objective function value in 'f', and the gradient in 'g'.
  %        Before returning g, make sure you form it back into a vector with g=g(:);
  %
%%% YOUR CODE HERE %%%
  
  g=g(:); % make gradient a vector for minFunc

以下是运行结果:

旧教程http://deeplearning.stanford.edu/wiki/index.php/Exercise:Softmax_Regression

也有softmax的编程作业。里面也是识别手写体数字。

其中提到准确率的问题。

Our implementation achieved an accuracy of 92.6%.
If your model's accuracy is significantly less (less than 91%), check your code, ensure that you are using the trained weights, and that you are training your model on the full 60000 training images. Conversely, if your accuracy is too high (99-100%), ensure
that you have not accidentally trained your model on the test set as well.

也就是说,从准确率来说,我的代码还是可以的。

接下来就是想办法实现向量化编程,加快速度了。


如果您有什么好想法,记得分享一下哦!

本文作者:linger

本文链接:http://blog.csdn.net/lingerlanlan/article/details/38410123

抱歉!评论已关闭.