当前位置:网站首页>Machine learning note 8: octave for handwritten digit recognition based on Neural Network
Machine learning note 8: octave for handwritten digit recognition based on Neural Network
2022-06-22 05:43:00 【Amyniez】
Octave Code
- Problems to be solved (3 individual ):
- 1. Data loading and visualization
- 2. Parameter loading
- 3. Calculate the cost based on forward propagation algorithm
- 4. Regularization
- 5. Gradient descent function
- 6. Initialize parameters
- 7. Back propagation algorithm implementation
- 8. Regularization implementation of back propagation algorithm
- 9. Neural network training
- 10. Weight and prediction accuracy
Problems to be solved (3 individual ):

1. Data loading and visualization
% Instructions
% ------------
%
% This file contains code that helps you get started on the
% linear exercise. You will need to complete the following functions
% in this exericse:
%
% sigmoidGradient.m
% randInitializeWeights.m
% nnCostFunction.m
%
% You will not need to change any code in this file,
% or any other files other than those mentioned above.
%
%% Initialization
clear ;
close all;
clc
%% Setup the parameters you will use for this exercise
input_layer_size = 400; % 20x20 Input Images of Digits
hidden_layer_size = 25; % 25 hidden units
num_labels = 10; % 10 labels, from 1 to 10
% (note that we have mapped "0" to label 10)
%% =========== Part 1: Loading and Visualizing Data =============
% We start the exercise by first loading and visualizing the dataset.
% You will be working with a dataset that contains handwritten digits.
%
% Load Training Data
fprintf('Loading and Visualizing Data ...\n')
% X has 5000 samples and 400 characteristics.
load('ex4data1.mat');
m = size(X, 1);
% Randomly select 100 data points to display.
sel = randperm(size(X, 1));
sel = sel(1:100);
% The starting point is (1, 1), not (0, 0).
% K is a matrix of 100*400
k = X(sel,:);
displayData(k);
fprintf('Program paused. Press enter to continue.\n');
1. sel Array (1*100):

2. Digital Visualization :
1.1 displayData.m
Realization function : Display a two-dimensional array in the grid , And automatically generate a width for the number in each grid ( Width if any , It's not generated )
function [h, display_array] = displayData(X, example_width)
%DISPLAYDATA Display 2D data in a nice grid
% [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data
% stored in X in a nice grid. It returns the figure handle h and the
% displayed array if requested.
%% Set the length and width of the image, equal by default that is 20 and 20
% Set example_width automatically if not passed in
if ~exist('example_width', 'var') || isempty(example_width)
example_width = round(sqrt(size(X, 2))); % 2 is columns;
% example_width is 20
end
% Gray Image
colormap(gray);
% Compute rows, cols;
% example_height is 20
[m n] = size(X);
example_height = (n / example_width);
%% Compute number of items to display
% .._rows*.._cols is 10 * 1
display_rows = floor(sqrt(m));
display_cols = ceil(m / display_rows);
%% Between images padding
% Separated by a black line
pad = 1; % What's the meaning of this?
% Setup blank display;
% display_array is (1+10*21) * (1+1*21)
display_array = - ones(pad + display_rows * (example_height + pad), ...
pad + display_cols * (example_width + pad));
% Copy each example into a patch on the display_array
curr_ex = 1;
for j = 1:display_rows
for i = 1:display_cols
if curr_ex > m,
break;
end
% Copy the patch
% Get the max value of the patch and normalize each sample
max_val = max(abs(X(curr_ex, :)));
display_array(pad + (j - 1) * (example_height + pad) + (1:example_height), ...
pad + (i - 1) * (example_width + pad) + (1:example_width)) = ...
% reshape a (1*400) row vector into a (example_height*example_width)
% square matrix.
reshape(X(curr_ex, :), example_height, example_width) / max_val;
curr_ex = curr_ex + 1;
end
if curr_ex > m,
break;
end
end
% Display Image
h = imagesc(display_array, [-1 1]);
% Do not show axis
axis image off
drawnow;
end
Code flow chart :
2. Parameter loading
% Load some pre-initialized neural network parameters.
fprintf('\nLoading Saved Neural Network Parameters ...\n')
% Load the weights into variables Theta1 and Theta2
load('ex4weights.mat');
% Unroll parameters
% Theta1:25*401=10025
% Theta2:10*26=260
% Expand by column,10285*1
nn_params = [Theta1(:) ; Theta2(:)];
3. Calculate the cost based on forward propagation algorithm
% To the neural network, you should first start by implementing the
% feedforward part of the neural network that returns the cost only. You
% should complete the code in nnCostFunction.m to return cost. After
% implementing the feedforward to compute the cost, you can verify that
% your implementation is correct by verifying that you get the same cost
% as us for the fixed debugging parameters.
%
% We suggest implementing the feedforward cost *without* regularization
% first so that it will be easier for you to debug. Later, in part 4, you
% will get to implement the regularized cost.
%
fprintf('\nFeedforward Using Neural Network ...\n')
% Weight regularization parameter (we set this to 0 here).
% *without* regularization first
lambda = 0;
J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, ...
num_labels, X, y, lambda);
fprintf(['Cost at parameters (loaded from ex4weights): %f '...
'\n(this value should be about 0.287629)\n'], J);
fprintf('\nProgram paused. Press enter to continue.\n');
The result of non regularization :
4. Regularization
% Once your cost function implementation is correct, you should now
% continue to implement the regularization with the cost.
%
fprintf('\nChecking Cost Function (w/ Regularization) ... \n')
% Weight regularization parameter (we set this to 1 here).
lambda = 1;
J_reg = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, ...
num_labels, X, y, lambda);
fprintf(['Cost at parameters (loaded from ex4weights): %f '...
'\n(this value should be about 0.383770)\n'], J);
fprintf('Program paused. Press enter to continue.\n');
Regularization results :
4.1 nnCostFunction.m
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
% Column vector to be expanded , Remodel as theta matrix
% Theta Reshaped matrix : First dimension = The number of features of the next layer , The second dimension = Number of features of the first layer +1
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
% Set the number of samples , Here for 5000 individual
m = size(X, 1);
% You need to return the following variables correctly
J = 0;
Theta1_grad = zeros(size(Theta1));
Theta2_grad = zeros(size(Theta2));
part1:
principle :

% 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
%
% The first layer calculates ( Input layer to hidden layer ), Add bias number (+1), Calculation sigmoid The value in
X = [ones(m,1) X]; % 5000 * 401
net_h = X * Theta1'; % 5000 * 25 out_h = sigmoid(net_h); % The second layer calculates ( Hidden layer to output layer ) out_h = [ones(m,1) out_h]; % 5000*26 net_o = out_h * Theta2'; % 5000*10
out_o = sigmoid(net_o);
% out_o by h(x) function , Dimension for 5000*10,y The dimensions are 5000*1, To put y The dimension of is converted to 5000*10, I.e out_o The dimensions are the same
for i =1:num_labels,
matrices_y(:,i) = (y==i);
end
matrices_J = log(out_o) .* matrices_y +log((1 - out_o)) .* (1 - matrices_y);
J = (-1/m)*sum(sum(matrices_J));
part2: Back propagation algorithm implementation ( Regular terms are not considered )

% 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.
%
error_termOut = zeros(m, num_labels);
% Error of the third output layer
error_termOut = out_o-matrices_y % 5000*10
% Error of the second hidden layer
% error_termH The dimension of is consistent with the dimension of the second layer
error_termH = (error_termOut*Theta2).*out_h.*(1-out_h); % 5000*26( Add offset term +1)
Theta2_grad = error_termOut'*out_h % error_termOut Dimension for 5000*10 % out_h Dimension for 5000*26 % Forward propagation algorithm adds bias term , Backward propagation , Get rid of the first column Theta1_grad = error_termH(:,2:end)'*X %Theta1_grad Dimension for 25*401
disp(Theta1_grad);
disp(Theta2_grad);
part3: Consider the regular term
First , Calculation Theta1_reg、Theta2_grad:
Be careful : Calculate the regular term from the second column
Last , Calculate regular term :

% 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.
%
Theta2_reg = Theta2_grad(:,2:end)+lambda.*Theta2(:,2:end);
Theta2_grad = (1/m).*[Theta2_grad(:,1) Theta2_reg];
Theta1_reg = Theta1_grad(:,2:end)+lambda.*Theta1(:,2:end);
Theta1_grad = (1/m).*[Theta1_grad(:,1) Theta1_reg];
% Plus the regular term
reg1 = sum(sum(Theta1(:,2:end).^2));
reg2 = sum(sum(Theta2(:,2:end).^2));
reg = (lambda/2*m)*(reg1+reg2); % Be careful 2m It doesn't mean 2*m
J = J +reg;
% -------------------------------------------------------------
% =========================================================================
% Unroll gradients
grad = [Theta1_grad(:) ; Theta2_grad(:)];
end
5. Gradient descent function
%% ================ Part 5: Sigmoid Gradient ================
% Before you start implementing the neural network, you will first
% implement the gradient for the sigmoid function. You should complete the
% code in the sigmoidGradient.m file.
%
fprintf('\nEvaluating sigmoid gradient...\n')
g = sigmoidGradient([-1 -0.5 0 0.5 1]);
fprintf('Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]:\n ');
fprintf('%f ', g);
fprintf('\n\n');
fprintf('Program paused. Press enter to continue.\n');

5.1 sigmoid.m
function g = sigmoid(z)
%SIGMOID Compute sigmoid functoon
% J = SIGMOID(z) computes the sigmoid of z.
g = 1.0 ./ (1.0 + exp(-z));
end
5.2 sigmoidGradient.m
function g = sigmoidGradient(z)
%SIGMOIDGRADIENT returns the gradient of the sigmoid function
%evaluated at z
% g = SIGMOIDGRADIENT(z) computes the gradient of the sigmoid function
% evaluated at z. This should work regardless if z is a matrix or a
% vector. In particular, if z is a vector or matrix, you should return
% the gradient for each element.
g = zeros(size(z));
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the gradient of the sigmoid function evaluated at
% each value of z (z can be a matrix, vector or scalar).
g = sigmoid(z).*(1-sigmoid(z))
% =============================================================
end
6. Initialize parameters
%% ================ Part 6: Initializing Pameters ================
% In this part of the exercise, you will be starting to implment a two
% layer neural network that classifies digits. You will start by
% implementing a function to initialize the weights of the neural network
% (randInitializeWeights.m)
fprintf('\nInitializing Neural Network Parameters ...\n')
initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size);
initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels);
% Unroll parameters
initial_nn_params = [initial_Theta1(:) ; initial_Theta2(:)];


6.1 randInitializeWeights.m
function W = randInitializeWeights(L_in, L_out)
%RANDINITIALIZEWEIGHTS Randomly initialize the weights of a layer with L_in
%incoming connections and L_out outgoing connections
% W = RANDINITIALIZEWEIGHTS(L_in, L_out) randomly initializes the weights
% of a layer with L_in incoming connections and L_out outgoing
% connections.
%
% Note that W should be set to a matrix of size(L_out, 1 + L_in) as
% the first column of W handles the "bias" terms
%
% You need to return the following variables correctly
W = zeros(L_out, 1 + L_in);
% ====================== YOUR CODE HERE ======================
% Instructions: Initialize W randomly so that we break the symmetry while
% training the neural network.
%
% Note: The first column of W corresponds to the parameters for the bias unit
%
epsilon = 0.01;
w = (2*epsilon) .* rand(L_out,L_in) - epsilon;
% =========================================================================
end
7. Back propagation algorithm implementation
%% =============== Part 7: Implement Backpropagation ===============
% Once your cost matches up with ours, you should proceed to implement the
% backpropagation algorithm for the neural network. You should add to the
% code you've written in nnCostFunction.m to return the partial % derivatives of the parameters. % fprintf('\nChecking Backpropagation... \n'); % Check gradients by running checkNNGradients checkNNGradients; fprintf('\nProgram paused. Press enter to continue.\n');
Results show :
7.1 checkNNGradients.m
function checkNNGradients(lambda)
%CHECKNNGRADIENTS Creates a small neural network to check the
%backpropagation gradients
% CHECKNNGRADIENTS(lambda) Creates a small neural network to check the
% backpropagation gradients, it will output the analytical gradients
% produced by your backprop code and the numerical gradients (computed
% using computeNumericalGradient). These two gradient computations should
% result in very similar values.
%
if ~exist('lambda', 'var') || isempty(lambda)
lambda = 0;
end
input_layer_size = 3;
hidden_layer_size = 5;
num_labels = 3;
m = 5;
% We generate some 'random' test data
Theta1 = debugInitializeWeights(hidden_layer_size, input_layer_size);
Theta2 = debugInitializeWeights(num_labels, hidden_layer_size);
% Reusing debugInitializeWeights to generate X
X = debugInitializeWeights(m, input_layer_size - 1);
y = 1 + mod(1:m, num_labels)'; % Unroll parameters nn_params = [Theta1(:) ; Theta2(:)]; % Short hand for cost function costFunc = @(p) nnCostFunction(p, input_layer_size, hidden_layer_size, ... num_labels, X, y, lambda); [cost, grad] = costFunc(nn_params); numgrad = computeNumericalGradient(costFunc, nn_params); % Visually examine the two gradient computations. The two columns % you get should be very similar. disp([numgrad grad]); fprintf(['The above two columns you get should be very similar.\n' ... '(Left-Your Numerical Gradient, Right-Analytical Gradient)\n\n']); % Evaluate the norm of the difference between two solutions. % If you have a correct implementation, and assuming you used EPSILON = 0.0001 % in computeNumericalGradient.m, then diff below should be less than 1e-9 diff = norm(numgrad-grad)/norm(numgrad+grad); fprintf(['If your backpropagation implementation is correct, then \n' ... 'the relative difference will be small (less than 1e-9). \n' ... '\nRelative Difference: %g\n'], diff);
end
8. Regularization implementation of back propagation algorithm
%% =============== Part 8: Implement Regularization ===============
% Once your backpropagation implementation is correct, you should now
% continue to implement the regularization with the cost and gradient.
%
fprintf('\nChecking Backpropagation (w/ Regularization) ... \n')
% Check gradients by running checkNNGradients
lambda = 3;
checkNNGradients(lambda);
% Also output the costFunction debugging values
debug_J = nnCostFunction(nn_params, input_layer_size, ...
hidden_layer_size, num_labels, X, y, lambda);
fprintf(['\n\nCost at (fixed) debugging parameters (w/ lambda = %f): %f ' ...
'\n(for lambda = 3, this value should be about 0.576051)\n\n'], lambda, debug_J);
fprintf('Program paused. Press enter to continue.\n');
Results show :

It can be seen from the above figure , This is a process that involves a lot of computation , It's going to be a lot of trouble .
9. Neural network training
%% =================== Part 8: Training NN ===================
% You have now implemented all the code necessary to train a neural
% network. To train your neural network, we will now use "fmincg", which
% is a function which works similarly to "fminunc". Recall that these
% advanced optimizers are able to train our cost functions efficiently as
% long as we provide them with the gradient computations.
%
fprintf('\nTraining Neural Network... \n')
% After you have completed the assignment, change the MaxIter to a larger
% value to see how more training helps.
options = optimset('MaxIter', 50);
% You should also try different values of lambda
lambda = 1;
% Create "short hand" for the cost function to be minimized
costFunction = @(p) nnCostFunction(p, ...
input_layer_size, ...
hidden_layer_size, ...
num_labels, X, y, lambda);
% Now, costFunction is a function that takes in only one argument (the
% neural network parameters)
[nn_params, cost] = fmincg(costFunction, initial_nn_params, options);
% Obtain Theta1 and Theta2 back from nn_params
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));
fprintf('Program paused. Press enter to continue.\n');
This process is time-consuming
Results are for reference only :

10. Weight and prediction accuracy
%% ================= Part 9: Visualize Weights =================
% You can now "visualize" what the neural network is learning by
% displaying the hidden units to see what features they are capturing in
% the data.
fprintf('\nVisualizing Neural Network... \n')
displayData(Theta1(:, 2:end));
fprintf('\nProgram paused. Press enter to continue.\n');
pause;
%% ================= Part 10: Implement Predict =================
% After training the neural network, we would like to use it to predict
% the labels. You will now implement the "predict" function to use the
% neural network to predict the labels of the training set. This lets
% you compute the training set accuracy.
pred = predict(Theta1, Theta2, X);
fprintf('\nTraining Set Accuracy: %f\n', mean(double(pred == y)) * 100);
10.1 predict.m
function p = predict(Theta1, Theta2, X)
%PREDICT Predict the label of an input given a trained neural network
% p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the
% trained weights of a neural network (Theta1, Theta2)
% Useful values
m = size(X, 1);
num_labels = size(Theta2, 1);
% You need to return the following variables correctly
p = zeros(size(X, 1), 1);
h1 = sigmoid([ones(m, 1) X] * Theta1'); h2 = sigmoid([ones(m, 1) h1] * Theta2');
[dummy, p] = max(h2, [], 2);
% =========================================================================
end
The above is the whole process of handwritten digit recognition , You only need to complete the top three questions , Understand the code again , Can complete NG Your homework . Of course , I have the code for the training part of the neural network , Not very proficient at it , Need to continue to strengthen the practice .
边栏推荐
- 搜狗输入法无法输出中文
- 企业如何把ERP项目自动施行?
- Why is "CPS alliance marketing" the most cost-effective promotion method?
- 数据的存储(进阶)
- How to find the source of goods for novice stores and how to find high-quality sources of goods?
- Remove then add string from variable of Makefile
- 代码走查的优化方向(接口请求便捷、动态class判断条件过长、去除无用console、抽离公共方法)
- innosetup判断程序已经运行方法
- 《MATLAB 神经网络43个案例分析》:第29章 极限学习机在回归拟合及分类问题中的应用研究——对比实验
- nacos server 源码运行实现
猜你喜欢

I don't suggest you work too hard

《MATLAB 神经网络43个案例分析》:第28章 决策树分类器的应用研究——乳腺癌诊断

Gerrit Code Review Setup

Tongda OA vulnerability analysis collection

微信小程序开发 第一周:页面设置、页面跳转、数据绑定

The prediction made ten years ago by the glacier has now been realized by Ali, which is very shocking

Graduation season | a new start, no goodbye

Hide symbol of dynamic library

OPTEE notes

Implementation of large file fragment uploading based on webuploader
随机推荐
微信小程序开发 第一周:页面设置、页面跳转、数据绑定
Implementation of large file fragment uploading based on webuploader
count registers in C code -- registers has one pattern
Current market situation analysis and investment analysis prospect report of global and Chinese ceramic capacitor industry 2022-2027
Want to put Facebook ads but don't know where to start? This article takes you to know more about
tmux -- ssh terminal can be closed without impact the server process
Force deletion of namespaces in terminating state
Throw away electron and embrace Tauri based on Rust
A simple method to implement deep cloning and encapsulation of objects JS
P1061 [noip2006 popularization group] counting method of jam
亚马逊和独立站,不是简单的二选一
参数序列化
Facebook账户 “ 解封、防封、养号 ” 知识要点,已收藏!
P1061 [NOIP2006 普及组] Jam 的计数法
Data storage (Advanced)
Parameter serialization
Someone always asks me: how to play independent station? Three cases, you will understand after reading
随鼠标移动的提示框
redis连接错误:ERR Client sent AUTH, but no password is set解决方案2个
我不建议你工作太拼命