1. 程式人生 > >Coursera-吳恩達-機器學習-第五週-程式設計作業: Neural Networks Learning

Coursera-吳恩達-機器學習-第五週-程式設計作業: Neural Networks Learning

本次文章內容: Coursera吳恩達機器學習課程,第五週程式設計作業。程式語言是Matlab。

學習演算法分兩部分進行理解,第一部分是根據code對演算法進行綜述,第二部分是程式碼。

0 Introduction 

在這個練習中,將應用 backpropagation,實現神經網路來識別手寫數字。

1 Neural Networks

Algorithm 

Part 0 Initialization & Setup the parameters

         clear ; close all; clc 的三劍客常規操作。並設定神經網路的結構引數。

         下圖是我們的Model representation:一共是三層,an input layer,a hidden layer and an output layer.

Part 1: Loading and Visualizing Data

           隨機選取100個data進行視覺化。

Part 2: Loading Parameters

          載入已經訓練好的theta引數,並將theta展開為我們需要的向量形式。

Part 3: Compute Cost (Feedforward)

         要做back propagation,先要做feedforward得到每個class的hypothesis。這部分的程式碼主要整合在 nnCostFunction()函式中。 根據我們的model,計算得到每個note的activation值,計算cost function(帶正則項)。next,我們會在這個函式裡計算back propagation,從後向前計算detla value,then計算累積誤差,then計算cost function的partial derivative(帶正則項)。

Part 4: Implement Regularization

         剛剛說到了,並輸入測試值檢測是否得出正確值。

Part 5: Sigmoid Gradient 

          sigmoid 函式的derivative有個特殊性質,這裡計算其導數。

Part 6: Initializing Pameters 

         為了防止所有的theta的初始值都是零,或者same,這將會倒是 back propagation 的計算無意義。所以我們random initialization ,根據維度rand() 0或1 value。

 Part 7: Implement Backpropagation

按4步,計算cost function的gradient,

          1. 計算forward propagation,computing the activations for all layers,注意bias的 +1term。

          2.從output開始從後往前計算detla值

          3.計算hidden layer 的detla 值,注意skip 第一層的detla 值

          4.Accumulate all the gradient值

          5. Obtain the (unregularized) gradient for cost function。

 注意,只有 成功  completed the feedforward之後,才可以implementing the backpropagation algorithm,

Part 8: Implement Regularization

            上一步中,新增正則項,在求cost function的gradient得第五步時。

Part 8: Training NN

         在我們獲得了cost和gradient之後,我們可以通過fmincg()函式來train neural network。

Part 9: Visualize Weights

         對中間層的畫素,進行視覺化。

Part 10: Implement Predict 

         After training the neural network,我們 計算 training set accuracy。

Code  

下面是nnCostFunction()函式部分,其他部分難度不大。

function [J grad] = nnCostFunction(nn_params, ...
                                   input_layer_size, ...
                                   hidden_layer_size, ...
                                   num_labels, ...
                                   X, y, lambda)
%NNCOSTFUNCTION Implements the neural network cost function for a two layer
%neural network which performs classification
%   [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, num_labels, ...
%   X, y, lambda) computes the cost and gradient of the neural network. The
%   parameters for the neural network are "unrolled" into the vector
%   nn_params and need to be converted back into the weight matrices. 
% 
%   The returned parameter grad should be a "unrolled" vector of the
%   partial derivatives of the neural network.
%

% Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices
% for our 2 layer neural network
Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...
                 hidden_layer_size, (input_layer_size + 1));

Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...
                 num_labels, (hidden_layer_size + 1));

% Setup some useful variables
m = size(X, 1);
         
% You need to return the following variables correctly 
J = 0;
Theta1_grad = zeros(size(Theta1));
Theta2_grad = zeros(size(Theta2));

% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the code by working through the
%               following parts.
%
% Part 1: Feedforward the neural network and return the cost in the
%         variable J. After implementing Part 1, you can verify that your
%         cost function computation is correct by verifying the cost
%         computed in ex4.m
%
% Part 2: Implement the backpropagation algorithm to compute the gradients
%         Theta1_grad and Theta2_grad. You should return the partial derivatives of
%         the cost function with respect to Theta1 and Theta2 in Theta1_grad and
%         Theta2_grad, respectively. After implementing Part 2, you can check
%         that your implementation is correct by running checkNNGradients
%
%         Note: The vector y passed into the function is a vector of labels
%               containing values from 1..K. You need to map this vector into a 
%               binary vector of 1's and 0's to be used with the neural network
%               cost function.
%
%         Hint: We recommend implementing backpropagation using a for-loop
%               over the training examples if you are implementing it for the 
%               first time.
%
% Part 3: Implement regularization with the cost function and gradients.
%
%         Hint: You can implement this around the code for
%               backpropagation. That is, you can compute the gradients for
%               the regularization separately and then add them to Theta1_grad
%               and Theta2_grad from Part 2.
%

%me******************************************************
%X= [ones(m,1)  X];
%a1 = sigmoid(X * Theta1');

%m1 = size(a1 ,1);
%X1 = [ones(m1,1) a1];
%hx = sigmoid(X1 * Theta2');

%[p pp] = max(hx, [], 1);
%J1 = (-y).* log(pp) - (1-y).* log(1-pp);
%J = 1/m * sum(J1);

%deta1 = pp -y;
%teacher&***********************************************

ylable = zeros(num_labels, m);   %10x5000
for i = 1:m
    ylable(y(i),i) = 1;
end

a1 = [ones(m,1) X];    %5000x401
z2 = a1 * Theta1';     %5000x25
a2 = sigmoid(z2);     

a2 = [ones(m,1) a2];      %5000x26
a3 = sigmoid(a2 * Theta2');        %5000x10


J = 1 / m * sum( sum( -ylable'.* log(a3) -  (1-ylable').*log(1-a3) )); 

% pay attention :" Theta1(:,2:end) " , no "Theta1" .  
regularized = lambda/(2*m) * (sum(sum(Theta1(:,2:end).^2)) + sum(sum(Theta2(:,2:end).^2)) ); 

J = J + regularized;

delta3 = a3-ylable';            %5000x10 

delta2 = delta3 * Theta2 ;  %5000x26
delta2 = delta2(:,2:end);    %5000x25
delta2 = delta2 .* sigmoidGradient(z2);  %5000x25 

Delta_1 = zeros(size(Theta1));        %25x401
Delta_2 = zeros(size(Theta2));         %10x26

Delta_1 = Delta_1 + delta2' * a1 ;    %25x401
Delta_2 = Delta_2 + delta3' * a2 ;     %10x26

Theta1_grad = 1/m * Delta_1;   
Theta2_grad = 1/m * Delta_2;  

% do the regularization
regularized_1 = lambda/m * Theta1;  
regularized_2 = lambda/m * Theta2;  
% j = 0 is not need to do the regularization
regularized_1(:,1) = zeros(size(regularized_1,1),1);  
regularized_2(:,1) = zeros(size(regularized_2,1),1);  
  
Theta1_grad = Theta1_grad + regularized_1;  
Theta2_grad = Theta2_grad + regularized_2; 

% -------------------------------------------------------------

% =========================================================================

% Unroll gradients
grad = [Theta1_grad(:) ; Theta2_grad(:)];


end

相關推薦

Coursera--機器學習--程式設計作業: Neural Networks Learning

本次文章內容: Coursera吳恩達機器學習課程,第五週程式設計作業。程式語言是Matlab。 學習演算法分兩部分進行理解,第一部分是根據code對演算法進行綜述,第二部分是程式碼。 0 Introduction  在這個練習中,將應用 backpropagation

Coursera--機器學習--程式設計作業: Support Vector Machines

本次文章內容: Coursera吳恩達機器學習課程,第七週程式設計作業。程式語言是Matlab。 本文只是從程式碼結構上做的小筆記,更復雜的推導不在這裡。演算法分兩部分進行理解,第一部分是根據code對演算法進行綜述,第二部分是程式碼。 本次作業分兩個part,第一個是using SVM,第

Coursera--機器學習--程式設計作業: K-Means Clustering and PCA

本次文章內容: Coursera吳恩達機器學習課程,第八週程式設計作業。程式語言是Matlab。 本文只是從程式碼結構上做的小筆記,更復雜的推導不在這裡。演算法分兩部分進行理解,第一部分是根據code對演算法進行綜述,第二部分是程式碼。 本次作業分兩個part,第一個是K-Means Clu

Coursera--機器學習--程式設計作業: Regularized Linear Regression and Bias/Variance

本次文章內容: Coursera吳恩達機器學習課程,第六週程式設計作業。程式語言是Matlab。 學習演算法分兩部分進行理解,第一部分是根據code對演算法進行綜述,第二部分是程式碼。 0 Introduction  在這個練習中,應用regularized linea

Coursera--機器學習--測驗-Large Scale Machine Learning

本片文章內容: Coursera吳恩達機器學習課程,第十週 Large Scale Machine Learning 部分的測驗,題目及答案截圖。 1.cost increase ,說明資料diverge。減小learning rate。 stochastic不需要每步都是減

Coursera--機器學習-九周-程式設計作業-Anomaly Detection and Recommender Systems

本次文章內容: Coursera吳恩達機器學習課程,第九周程式設計作業。程式語言是Matlab。 本文只是從程式碼結構上做的小筆記。   Anomaly Detection  part 0 Initialization Part 1: Load Example

機器學習 | 機器學習程式設計作業(Python版)

實驗指導書  下載密碼:fja4 本篇部落格主要講解,吳恩達機器學習第三週的程式設計作業,作業內容主要是利用邏輯迴歸演算法(正則化)進行二分類。實驗的原始版本是用Matlab實現的,本篇部落格主要用Python來實現。   目錄 1.實驗包含的檔案 2.使用邏

機器學習 | 機器學習程式設計作業(Python版)

實驗指導書   下載密碼:higl 本篇部落格主要講解,吳恩達機器學習第八週的程式設計作業,主要包含KMeans實驗和PCA實驗兩部分。原始實驗使用Matlab實現,本篇部落格提供Python版本。 目錄 1.實驗包含的檔案 2.KMeans實驗 3.K-me

機器學習 | 機器學習程式設計作業(Python版)

實驗指導書  下載密碼:a15g 本篇部落格主要講解,吳恩達機器學習第七週的程式設計作業,包含兩個實驗,一是線性svm和帶有高斯核函式的svm的基本使用;二是利用svm進行垃圾郵件分類。原始實驗使用Matlab實現,本篇部落格提供Python版本。   目錄 1.

機器學習 | 機器學習程式設計作業(Python版)

實驗指導書  下載密碼:4t4y 本篇部落格主要講解,吳恩達機器學習第六週的程式設計作業,作業內容主要是實現一個正則化的線性迴歸演算法,涉及本週講的模型選擇問題,繪製學習曲線判斷高偏差/高方差問題。原始實驗使用Matlab實現,本篇部落格提供Python版本。 目錄 1.實驗包

Coursera--機器學習--測驗-Support Vector Machines

  忘記截圖了,做了二次的,有點繞這裡,慢點想就好了。 正確選項是,It would be reasonable to try increasing C. It would also be reasonable to try decreasing σ2.  &n

Coursera--機器學習--測驗-Principal Component Analysis

本片文章內容: Coursera吳恩達機器學習課程,第八週的測驗,題目及答案截圖。                    

Coursera--機器學習--測驗-Machine Learning System Design

說實話,這一次的測驗對我還是有一點難度的,為了刷到100分,刷了7次(哭)。 無奈,第2道和第4道題總是出錯,後來終於找到錯誤的地方,錯誤原因是思維定式,沒有動腦和審題正確。 這兩道題細節會在下面做出講解。 第二題分析:題意問,使用大量的資料,在哪兩種情況時

Coursera--機器學習-十一-測驗-Application: Photo OCR

本片文章內容: Coursera吳恩達機器學習課程,第十一週 Application: Photo OCR 部分的測驗,題目及答案截圖。   1000*1000,每次移動2畫素,總共是500*500=250000次,兩個視窗是500000次。   &nb

Coursera--機器學習-九周-測驗-Recommender Systems

本片文章內容: Coursera吳恩達機器學習課程,第九周Recommender Systems部分的測驗,題目及答案截圖。   注:區分迴歸的預測和collaborative filtering預測的區別,後者涉及到一些分類。 注:可以結合不同的trai

Coursera機器學習課程 總結筆記及作業程式碼——5周神經網路續

Neural Networks:Learning 上週的課程學習了神經網路正向傳播演算法,這周的課程主要在於神經網路的反向更新過程。 1.1 Cost function 我們先回憶一下邏輯迴歸的價值函式 J(θ)=1m[∑mi=1y(i)log(hθ

Coursera機器學習課程 總結筆記及作業程式碼——1,2周

Linear’regression 發現這個教程是最入門的一個教程了,老師講的很好,也很通俗,每堂課後面還有程式設計作業,全程用matlab程式設計,只需要填寫核心程式碼,很適合自學。 1.1 Model representation 起始給出了

Coursera機器學習課程 總結筆記及作業程式碼——6周有關機器學習的小建議

1.1 Deciding what to try next 當你除錯你的學習演算法時,當面對測試集你的演算法效果不佳時,你會怎麼做呢? 獲得更多的訓練樣本? 嘗試更少的特徵? 嘗試獲取附加的特徵? 嘗試增加多項式的特徵? 嘗試增加λ? 嘗試減小λ?

機器學習

轉載https://www.cnblogs.com/LoganGo/p/8562575.html 一.邏輯迴歸問題(分類問題) 生活中存在著許多分類問題,如判斷郵件是否為垃圾郵件;判斷腫瘤是惡性還是良性等。機器學習中邏輯迴歸便是解決分類問題的一種方法。 二分類:通常表示為yϵ{0,1}

機器學習 | 機器學習學習筆記

課程視訊連結 第六週PPT  下載密碼:zgkq 本週主要講解了如何設計機器學習系統和如何改進機器學習系統,包括一些模型選擇的方法,模型效能的評價指標,模型改進的方法等。 目錄 一、應用機器學習建議 1.決定下一步做什麼 2.評估假設函式 3.模型選擇和訓練、驗