標籤:ufldl deep learning 機器學習 octave matlab
ufldl學習筆記與編程作業:Softmax Regression(vectorization加速)
ufldl出了新教程,感覺比之前的好,從基礎講起,系統清晰,又有編程實踐。
在deep learning高品質群裡面聽一些前輩說,不必深究其他機器學習的演算法,可以直接來學dl。
於是最近就開始搞這個了,教程加上matlab編程,就是完美啊。
新教程的地址是:http://ufldl.stanford.edu/tutorial/
本節是對ufldl學習筆記與編程作業:Softmax Regression(softmax迴歸)版本的改進。
哈哈,把向量化的寫法給寫出來了,尼瑪好快啊。只需要2分鐘,200迭代就跑完了。昨晚的for迴圈寫法跑了我1個半小時。
其實實現向量化寫法,要把各種矩陣給在紙上寫出來。
1 感謝tornadomeet,雖然他做的是舊教程的實驗,但是從他那裡學了幾個matlab函數。http://www.cnblogs.com/tornadomeet/archive/2013/03/23/2977621.html
比如sparse和full。‘
2 還有從舊教程http://deeplearning.stanford.edu/wiki/index.php/Exercise:Softmax_Regression
學了
% M is the matrix as described in the textM = bsxfun(@rdivide, M, sum(M))
3 新教程學到了
I=sub2ind(size(A), 1:size(A,1), y);values = A(I);
以下是softmax_regression_vec.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))];%加1行 p = bsxfun(@rdivide,a,sum(a)); c = log2(p); i = sub2ind(size(c), y,[1:size(c,2)]); values = c(i); f = -sum(values); d = full(sparse(1:m,y,1)); d = d(:,1:(size(d,2)-1)); p = p(1:(size(p,1)-1),:);%減1行 g = X*(p'.-d); % % 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
本文linger
本文連結:http://blog.csdn.net/lingerlanlan/article/details/38425929