UFLDL是吳恩達團隊編寫的較早的一門深度學習入門,里面理論加上練習的節(jié)奏非常好,每次都想快點看完理論去動手編寫練習,因為他幫你打好了整個代碼框架,也有詳細的注釋,所以我們只要實現(xiàn)一點核心的代碼編寫工作就行了,上手快!
第三節(jié)是:Vectorization(向量化)
這節(jié)的思想就是,運用向量化編程思維,讓代碼運行更加高效,而不是用for循環(huán),所以通過這次之后,我看到這種符號,腦子里第一下就想,能不能用向量化編程。
要用向量化編程,最好自己能寫一兩項求和的內容,之后再用類似內積的矩陣乘法來表述,教程寫的不是太明白,自己能用矩陣乘法表示出來即可,注意矩陣維數(shù)對應就好!!
當然還是學到了一個之后會經常用到的函數(shù):bsxfun函數(shù),用來作element-wise操作,即向量元素之間的對應操作,具體可看matlab官方文檔介紹!
下面是我用向量化編寫之前的線性回歸和邏輯回歸的代碼(運行的時候去注釋相應的非向量化調用語句):
我這里用的是:matlab2016a
linear_regression_vec.m:
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 %%%
f = 0.5 .* (theta' * X - y) * (theta' * X - y)';
% g = g';
g = (theta' * X - y) * X';
g = g';
運行結果:
線性回歸(向量化)
線性回歸(向量化)圖
可以看到和之前的0.78秒,現(xiàn)在有了較快的提升!
linear_regression_vec.m:
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 %%%
h = inline('1./(1+exp(-z))');
% Calculate f
f = f - (y*log(h(X'*theta)) + (1-y)*log(1-h(X'*theta)));
% Calculate g
g = X * (h(theta' * X) - y)';
運行結果:

邏輯回歸(向量化).png
可以看到和之前的6.84秒,現(xiàn)在速度提升了23倍!
有理解不到位之處,還請指出,有更好的想法,可以在下方評論交流!