Deep Learning 9_深度學習UFLDL教程:linear decoder_exercise(斯坦福大學深度學習教程)
前言
實驗基礎說明:
1.為什麼要用線性解碼器,而不用前面用過的棧式自編碼器等?即:線性解碼器的作用?
這一點,Ng已經在講解中說明了,因為線性解碼器不用要求輸入資料範圍一定為(0,1),而前面用過的棧式自編碼器等要求輸入資料範圍必須為(0,1)。因為a3的輸出值是f函式的輸出,而在普通的sparse autoencoder中f函式一般為sigmoid函式,所以其輸出值的範圍為(0,1),所以可以知道a3的輸出值範圍也在0到1之間。另外我們知道,在稀疏模型中的輸出層應該是儘量和輸入層特徵相同,也就是說a3=x1,這樣就可以推匯出x1也是在0和1之間,那就是要求我們對輸入到網路中的資料要先變換到0和1之間,這一條件雖然在有些領域滿足,比如前面實驗中的MINIST數字識別。但是有些領域,比如說使用了PCA Whitening後的資料,其範圍卻不一定在0和1之間。因此Linear Decoder方法就出現了。Linear Decoder是指在隱含層採用的激發函式是sigmoid函式,而在輸出層的激發函式採用的是線性函式,比如說最特別的線性函式——等值函式。
2.在實驗中,在ZCA whitening前進行資料預處理時,每列代表一個樣本,但為什麼是對patches的每行0均值化(即:每一維度0均值化,具體做法是:首先計算每一個維度上資料的均值(使用全體資料計算),之後在每一個維度上都減去該均值。),而以前的實驗都是對每列即每個樣本0均值化(即:逐樣本均值消減)?
①因為以前是灰度圖,現在是RGB彩色影象,如果現在對每列平均就是對三個通道求平均,這肯定不行。因為不同色彩通道中的畫素並不都存在平穩特性,而要進行逐樣本均值消減(即:單獨每個樣本0均值化)有一個必須滿足的前提:該資料是平穩的(見:資料預處理)。
②因為以前是自然影象,自然影象中畫素之間的統計特性都一樣,有一定的相關性,而現在是人工分割的影象塊,沒有這種特性。
3.在實驗中,把網路權值顯示出來為什麼是用displayColorNetwork( (W*ZCAWhite)'),而不像以前用的是display_Network( (W1)')?
因為在本實驗中,資料patches在輸入網路前先經過了ZCA whitening的資料預處理,變成了ZCA白化後的資料ZCAWhite * patches,所以第一層隱含層輸出的實際上是W*ZCAWhite * patches,也就是說從原始資料patches到第一層隱含層輸出為W*ZCAWhite * patches的整個過程l轉換權值為W*ZCAWhite。
4.PCA Whitening和ZCA Whitening的區別
PCA Whitening:處理後的各資料方差都都相等,並都為1。主要用於降維和去相關性。
ZCA Whitening:處理後的各資料方差不一定為1,但一定相等。主要用於去相關性,且能儘量保持原始資料。
5.優秀的程式設計技巧:
要學會用函式控制代碼,比如patches = bsxfun(@minus, patches, meanPatch);
因為不使用函式控制代碼的情況下,對函式多次呼叫,每次都要為該函式進行全面的路徑搜尋,直接影響計算速度,藉助控制代碼可以完全避免這種時間損耗。也就是直接指定了函式的指標。函式控制代碼就像一個函式的名字,有點類似於C++程式中的引用。當然這一點已經在Deep Learning一之深度學習UFLDL教程:Sparse Autoencoder練習(斯坦福大學深度學習教程)中提到過,但我覺得有必須再強調一下。
實驗步驟
1.初始化引數,編寫計算線性解碼器代價函式及其梯度的函式sparseAutoencoderLinearCost.m,主要是在sparseAutoencoderCost.m的基礎上稍微修改,然後再檢查其梯度實現是否正確。
2.載入資料並原始資料進行ZCA Whitening的預處理。
3.學習特徵,即用LBFG演算法訓練整個線性解碼器網路,得到整個網路權值optTheta。
4.視覺化第一層學習到的特徵。
實驗結果
原始資料
ZCA Whitening後的資料
特徵視覺化結果,即:每一層學習到的特徵
程式碼
linearDecoderExercise.m
%% CS294A/CS294W Linear Decoder Exercise % Instructions % ------------ % % This file contains code that helps you get started on the % linear decoder exericse. For this exercise, you will only need to modify % the code in sparseAutoencoderLinearCost.m. You will not need to modify % any code in this file. %%====================================================================== %% STEP 0: Initialization % Here we initialize some parameters used for the exercise. imageChannels = 3; % number of channels (rgb, so 3) patchDim = 8; % patch dimension numPatches = 100000; % number of patches visibleSize = patchDim * patchDim * imageChannels; % number of input units outputSize = visibleSize; % number of output units hiddenSize = 400; % number of hidden units sparsityParam = 0.035; % desired average activation of the hidden units. lambda = 3e-3; % weight decay parameter beta = 5; % weight of sparsity penalty term epsilon = 0.1; % epsilon for ZCA whitening %%====================================================================== %% STEP 1: Create and modify sparseAutoencoderLinearCost.m to use a linear decoder, % and check gradients % You should copy sparseAutoencoderCost.m from your earlier exercise % and rename it to sparseAutoencoderLinearCost.m. % Then you need to rename the function from sparseAutoencoderCost to % sparseAutoencoderLinearCost, and modify it so that the sparse autoencoder % uses a linear decoder instead. Once that is done, you should check % your gradients to verify that they are correct. % NOTE: Modify sparseAutoencoderCost first! % To speed up gradient checking, we will use a reduced network and some % dummy patches debugHiddenSize = 5; debugvisibleSize = 8; patches = rand([8 10]); theta = initializeParameters(debugHiddenSize, debugvisibleSize); [cost, grad] = sparseAutoencoderLinearCost(theta, debugvisibleSize, debugHiddenSize, ... lambda, sparsityParam, beta, ... patches); % Check gradients numGrad = computeNumericalGradient( @(x) sparseAutoencoderLinearCost(x, debugvisibleSize, debugHiddenSize, ... lambda, sparsityParam, beta, ... patches), theta); % Use this to visually compare the gradients side by side disp([numGrad grad]); diff = norm(numGrad-grad)/norm(numGrad+grad); % Should be small. In our implementation, these values are usually less than 1e-9. disp(diff); assert(diff < 1e-9, 'Difference too large. Check your gradient computation again'); % NOTE: Once your gradients check out, you should run step 0 again to % reinitialize the parameters %} %%====================================================================== %% STEP 2: 從pathes中學習特徵 Learn features on small patches % In this step, you will use your sparse autoencoder (which now uses a % linear decoder) to learn features on small patches sampled from related % images. %% STEP 2a: 載入資料 Load patches % In this step, we load 100k patches sampled from the STL10 dataset and % visualize them. Note that these patches have been scaled to [0,1] load stlSampledPatches.mat %怎麼就就這個變數加到pathes上了呢?因為它裡面自己定義了變數patches的值! figure; displayColorNetwork(patches(:, 1:100)); %% STEP 2b: 預處理 Apply preprocessing % In this sub-step, we preprocess the sampled patches, in particular, % ZCA whitening them. % % In a later exercise on convolution and pooling, you will need to replicate % exactly the preprocessing steps you apply to these patches before % using the autoencoder to learn features on them. Hence, we will save the % ZCA whitening and mean image matrices together with the learned features % later on. % Subtract mean patch (hence zeroing the mean of the patches) meanPatch = mean(patches, 2); %為什麼是對每行求平均,以前是對每列即每個樣本求平均呀?因為以前是灰度圖,現在是彩色圖,如果現在對每列平均就是對三個通道求平均,這肯定不行 patches = bsxfun(@minus, patches, meanPatch); % Apply ZCA whitening sigma = patches * patches' / numPatches; %協方差矩陣 [u, s, v] = svd(sigma); ZCAWhite = u * diag(1 ./ sqrt(diag(s) + epsilon)) * u'; patches = ZCAWhite * patches; figure; displayColorNetwork(patches(:, 1:100)); %% STEP 2c: Learn features % You will now use your sparse autoencoder (with linear decoder) to learn % features on the preprocessed patches. This should take around 45 minutes. theta = initializeParameters(hiddenSize, visibleSize); % Use minFunc to minimize the function addpath minFunc/ options = struct; options.Method = 'lbfgs'; options.maxIter = 400; options.display = 'on'; [optTheta, cost] = minFunc( @(p) sparseAutoencoderLinearCost(p, ... visibleSize, hiddenSize, ... lambda, sparsityParam, ... beta, patches), ... theta, options); % Save the learned features and the preprocessing matrices for use in % the later exercise on convolution and pooling fprintf('Saving learned features and preprocessing matrices...\n'); save('STL10Features.mat', 'optTheta', 'ZCAWhite', 'meanPatch'); fprintf('Saved\n'); %% STEP 2d: Visualize learned features W = reshape(optTheta(1:visibleSize * hiddenSize), hiddenSize, visibleSize); b = optTheta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize); figure; displayColorNetwork( (W*ZCAWhite)');
sparseAutoencoderLinearCost.m
function [cost,grad,features] = sparseAutoencoderLinearCost(theta, visibleSize, hiddenSize, ... lambda, sparsityParam, beta, data) %計算線性解碼器代價函式及其梯度 % visibleSize:輸入層神經單元節點數 % hiddenSize:隱藏層神經單元節點數 % lambda: 權重衰減係數 % sparsityParam: 稀疏性引數 % beta: 稀疏懲罰項的權重 % data: 訓練集 % theta:引數向量,包含W1、W2、b1、b2 % -------------------- YOUR CODE HERE -------------------- % Instructions: % Copy sparseAutoencoderCost in sparseAutoencoderCost.m from your % earlier exercise onto this file, renaming the function to % sparseAutoencoderLinearCost, and changing the autoencoder to use a % linear decoder. % -------------------- YOUR CODE HERE -------------------- % The input theta is a vector because minFunc only deal with vectors. In % this step, we will convert theta to matrix format such that they follow % the notation in the lecture notes. W1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize); W2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize); b1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize); b2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end); % Loss and gradient variables (your code needs to compute these values) m = size(data, 2); % 樣本數量 %% ---------- YOUR CODE HERE -------------------------------------- % Instructions: Compute the loss for the Sparse Autoencoder and gradients % W1grad, W2grad, b1grad, b2grad % % Hint: 1) data(:,i) is the i-th example % 2) your computation of loss and gradients should match the size % above for loss, W1grad, W2grad, b1grad, b2grad % z2 = W1 * x + b1 % a2 = f(z2) % z3 = W2 * a2 + b2 % h_Wb = a3 = f(z3) z2 = W1 * data + repmat(b1, [1, m]); a2 = sigmoid(z2); z3 = W2 * a2 + repmat(b2, [1, m]); a3 = z3; rhohats = mean(a2,2); rho = sparsityParam; KLsum = sum(rho * log(rho ./ rhohats) + (1-rho) * log((1-rho) ./ (1-rhohats))); squares = (a3 - data).^2; squared_err_J = (1/2) * (1/m) * sum(squares(:)); %均方差項 weight_decay_J = (lambda/2) * (sum(W1(:).^2) + sum(W2(:).^2));%權重衰減項 sparsity_J = beta * KLsum; %懲罰項 cost = squared_err_J + weight_decay_J + sparsity_J;%損失函式值 % delta3 = -(data - a3) .* fprime(z3); % but fprime(z3) = a3 * (1-a3) delta3 = -(data - a3); beta_term = beta * (- rho ./ rhohats + (1-rho) ./ (1-rhohats)); delta2 = ((W2' * delta3) + repmat(beta_term, [1,m]) ) .* a2 .* (1-a2); W2grad = (1/m) * delta3 * a2' + lambda * W2; % W2梯度 b2grad = (1/m) * sum(delta3, 2); % b2梯度 W1grad = (1/m) * delta2 * data' + lambda * W1; % W1梯度 b1grad = (1/m) * sum(delta2, 2); % b1梯度 %------------------------------------------------------------------- % Convert weights and bias gradients to a compressed form % This step will concatenate and flatten all your gradients to a vector % which can be used in the optimization method. grad = [W1grad(:) ; W2grad(:) ; b1grad(:) ; b2grad(:)]; end %------------------------------------------------------------------- % We are giving you the sigmoid function, you may find this function % useful in your computation of the loss and the gradients. function sigm = sigmoid(x) sigm = 1 ./ (1 + exp(-x)); end
displayColorNetwork.m
function displayColorNetwork(A) % display receptive field(s) or basis vector(s) for image patches % % A the basis, with patches as column vectors % In case the midpoint is not set at 0, we shift it dynamically if min(A(:)) >= 0 A = A - mean(A(:)); % 0均值化 end cols = round(sqrt(size(A, 2)));% 每行大影象中小影象塊的個數 channel_size = size(A,1) / 3; dim = sqrt(channel_size); % 小影象塊內每行或列畫素點個數 dimp = dim+1; rows = ceil(size(A,2)/cols); % 每列大影象中小影象塊的個數 B = A(1:channel_size,:); % R通道畫素值 C = A(channel_size+1:channel_size*2,:); % G通道畫素值 D = A(2*channel_size+1:channel_size*3,:); % B通道畫素值 B=B./(ones(size(B,1),1)*max(abs(B)));% 歸一化 C=C./(ones(size(C,1),1)*max(abs(C))); D=D./(ones(size(D,1),1)*max(abs(D))); % Initialization of the image I = ones(dim*rows+rows-1,dim*cols+cols-1,3); %Transfer features to this image matrix for i=0:rows-1 for j=0:cols-1 if i*cols+j+1 > size(B, 2) break end % This sets the patch I(i*dimp+1:i*dimp+dim,j*dimp+1:j*dimp+dim,1) = ... reshape(B(:,i*cols+j+1),[dim dim]); I(i*dimp+1:i*dimp+dim,j*dimp+1:j*dimp+dim,2) = ... reshape(C(:,i*cols+j+1),[dim dim]); I(i*dimp+1:i*dimp+dim,j*dimp+1:j*dimp+dim,3) = ... reshape(D(:,i*cols+j+1),[dim dim]); end end I = I + 1; % 使I的範圍從[-1,1]變為[0,2] I = I / 2; % 使I的範圍從[0,2]變為[0, 1] imagesc(I); axis equal % 等比座標軸:設定螢幕高寬比,使得每個座標軸的具有均勻的刻度間隔 axis off % 關閉所有的座標軸標籤、刻度、背景 end
參考資料
相關推薦
Deep Learning 9_深度學習UFLDL教程:linear decoder_exercise(斯坦福大學深度學習教程)
前言 實驗基礎說明: 1.為什麼要用線性解碼器,而不用前面用過的棧式自編碼器等?即:線性解碼器的作用? 這一點,Ng已經在講解中說明了,因為線性解碼器不用要求輸入資料範圍一定為(0,1),而前面用過的棧式自編碼器等要求輸入資料範圍必須為(0,1)。因為a3的輸出值是f函式的輸出,而在普通的spa
Deep Learning 12_深度學習UFLDL教程:Sparse Coding_exercise(斯坦福大學深度學習教程)
前言 實驗環境:win7, matlab2015b,16G記憶體,2T機械硬碟 本節實驗比較不好理解也不好做,我看很多人最後也沒得出好的結果,所以得花時間仔細理解才行。 實驗內容:Exercise:Sparse Coding。從10張512*512的已經白化後的灰度影象(即:Deep Learnin
Deep Learning 6_深度學習UFLDL教程:Softmax Regression_Exercise(斯坦福大學深度學習教程)
前言 練習內容:Exercise:Softmax Regression。完成MNIST手寫數字資料庫中手寫數字的識別,即:用6萬個已標註資料(即:6萬張28*28的影象塊(patches)),作訓練資料集,然後利用其訓練softmax分類器,再用1萬個已標註資料(即:1萬張28*28的影象塊(pa
Deep Learning 1_深度學習UFLDL教程:Sparse Autoencoder練習(斯坦福大學深度學習教程)
1前言 本人寫技術部落格的目的,其實是感覺好多東西,很長一段時間不動就會忘記了,為了加深學習記憶以及方便以後可能忘記後能很快回憶起自己曾經學過的東西。 首先,在網上找了一些資料,看見介紹說UFLDL很不錯,很適合從基礎開始學習,Adrew Ng大牛寫得一點都不裝B,感覺非常好
Deep Learning 4_深度學習UFLDL教程:PCA in 2D_Exercise(斯坦福大學深度學習教程)
前言 本節練習的主要內容:PCA,PCA Whitening以及ZCA Whitening在2D資料上的使用,2D的資料集是45個數據點,每個資料點是2維的。要注意區別比較二維資料與二維影象的不同,特別是在程式碼中,可以看出主要二維資料的在PCA前的預處理不需要先0均值歸一化,而二維自然影象需要先
Deep Learning 3_深度學習UFLDL教程:預處理之主成分分析與白化_總結(斯坦福大學深度學習教程)
1PCA ①PCA的作用:一是降維;二是可用於資料視覺化; 注意:降維的原因是因為原始資料太大,希望提高訓練速度但又不希望產生很大的誤差。 ② PCA的使用場合:一是希望提高訓練速度;二是記憶體太小;三是希望資料視覺化。 ③用PCA前的預處理:(1)規整化特徵的均值大致為0;(
Deep Learning 19_深度學習UFLDL教程:Convolutional Neural Network_Exercise(斯坦福大學深度學習教程)
基礎知識 概述 CNN是由一個或多個卷積層(其後常跟一個下采樣層)和一個或多個全連線層組成的多層神經網路。CNN的輸入是2維影象(或者其他2維輸入,如語音訊號)。它通過區域性連線和權值共享,再通過池化可得到平移不變特徵。CNN的另一個優點就是易於訓練
Deep Learning 8_深度學習UFLDL教程:Stacked Autocoders and Implement deep networks for digit classification_Exercise(斯坦福大學深度學習教程)
前言 2.實驗環境:win7, matlab2015b,16G記憶體,2T硬碟 3.實驗內容:Exercise: Implement deep networks for digit classification。利用深度網路完成MNIST手寫數字資料庫中手寫數字的識別。即:用6萬個已標註資料(即:6萬
Deep Learning 11_深度學習UFLDL教程:資料預處理(斯坦福大學深度學習教程)
資料預處理是深度學習中非常重要的一步!如果說原始資料的獲得,是深度學習中最重要的一步,那麼獲得原始資料之後對它的預處理更是重要的一部分。 1.資料預處理的方法: ①資料歸一化: 簡單縮放:對資料的每一個維度的值進行重新調節,使其在 [0,1]或[ − 1,1] 的區間內 逐樣本均值消減:在每個
Deep Learning 13_深度學習UFLDL教程:Independent Component Analysis_Exercise(斯坦福大學深度學習教程)
前言 實驗環境:win7, matlab2015b,16G記憶體,2T機械硬碟 難點:本實驗難點在於執行時間比較長,跑一次都快一天了,並且我還要驗證各種代價函式的對錯,所以跑了很多次。 實驗基礎說明: ①不同點:本節實驗中的基是標準正交的,也是線性獨立的,而Deep Learni
Deep Learning 7_深度學習UFLDL教程:Self-Taught Learning_Exercise(斯坦福大學深度學習教程)
前言 理論知識:自我學習 練習環境:win7, matlab2015b,16G記憶體,2T硬碟 一是用29404個無標註資料unlabeledData(手寫數字資料庫MNIST Dataset中數字為5-9的資料)來訓練稀疏自動編碼器,得到其權重引數opttheta。這一步的目的是提取這
Deep Learning 2_深度學習UFLDL教程:向量化程式設計(斯坦福大學深度學習教程)
1前言 本節主要是讓人用向量化程式設計代替效率比較低的for迴圈。 在前一節的Sparse Autoencoder練習中已經實現了向量化程式設計,所以與前一節的區別只在於本節訓練集是用MINIST資料集,而上一節訓練集用的是從10張圖片中隨機選擇的8*8的10000張小圖塊。綜上,只需要在
Deep Learning 10_深度學習UFLDL教程:Convolution and Pooling_exercise(斯坦福大學深度學習教程)
前言 實驗環境:win7, matlab2015b,16G記憶體,2T機械硬碟 實驗內容:Exercise:Convolution and Pooling。從2000張64*64的RGB圖片(它是 the STL10 Dataset的一個子集)中提取特徵作為訓練資料集,訓練softmax分類器,然後從
Deep Learning 5_深度學習UFLDL教程:PCA and Whitening_Exercise(斯坦福大學深度學習教程)
close all; % clear all; %%================================================================ %% Step 0a: Load data % Here we provide the code to load n
Activiti 學習筆記11:接收活動(receiveTask,即等待活動)
接收任務是一個簡單任務,它會等待對應訊息的到達。 當前,官方只實現了這個任務的java語義。 當流程達到接收任務,流程狀態會儲存到資料庫中。 在任務建立後,意味著流程會進入等待狀態 , 直到引擎接收
實時翻譯的發動機:向量語義(斯坦福大學課程解讀)
大家好,我是為人造的智慧操碎了心的智慧禪師。GraphDB 最近剛剛升級到 8.7 版本,此次特
Deep Learning-TensorFlow (10) CNN卷積神經網路_ TFLearn 快速搭建深度學習模型
環境:Win8.1 TensorFlow1.0.1 軟體:Anaconda3 (整合Python3及開發環境) TensorFlow安裝:pip install tensorflow (CPU版) pip install tensorflow-gpu (GPU版) TFLe
ufldl學習筆記與編程作業:Linear Regression(線性回歸)
cal bug war 環境 art link 行數 ear sad ufldl學習筆記與編程作業:Linear Regression(線性回歸) ufldl出了新教程,感覺比之前的好。從基礎講起。系統清晰,又有編程實踐。在deep learning高質量群裏
CS294-112深度增強學習課程(加州大學伯克利分校 2017)NO.3 Learning dynamical system models from data
增強 data learning http src img sys 增強學習 學習
深度學習第一步:windows+Anaconda下安裝tensorflow深度學習框架
一共四步,一會就成功! 第一步,首先需要安裝Anaconda。 它是一個庫管理工具,能夠管理不同環境,不同環境下可以安裝不同python版本以及其他庫。安裝Anaconda這一步非常的簡單去Anaconda官方網站(https://www.continuum.