Coursera-Machine-Learning-ex4

限时加码!20+主流AI编程工具免费用 购周边加赠Coding Plan Lite,Claude Code、Cursor等即刻畅享,学习进阶更高效! 阅读详情

上一个练习中我们使用给定的权重矩阵对手写数字进行预测,本次练习中,我们尝试去学习参数θ。

Neural Networks

首先使用displayData方法对训练集数据进行可视化。

和之前的训练集一样,共5000个训练样本,每个样本为20*20像素的图片,展开以400维向量形式给出。训练样本处理如下:

首先确定结构,我们本次使用三层结构,一个输入层,一个隐藏层,一个输出层。由于我们每个样本输入有400个元素,所以我们设定400个输入单元(不计算偏置单元),那么我们需要θ1和θ2两个权重矩阵需要学习,其中隐藏层有25个单元,输出层有10个单元。

然后我们首先完成代价函数和梯度下降计算部分。首先利用公式写出h(x)的计算结果,写出不含正则项的代价函数。

经过程序验证后可以加入正则项,公式如下:

 

然后我们需要使用反向传播算法写出偏导项的计算公式,反向传播算法和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
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.
%

a1 = [ones(m, 1) X];
z2 = a1 * Theta1';
a2 = sigmoid(z2);
a2 = [ones(m, 1) a2];
z3 = a2 * Theta2';
h = sigmoid(z3);

yk = zeros(m, num_labels);
for i = 1:m
    yk(i, y(i)) = 1;
end
J = (1/m)* sum(sum(((-yk) .* log(h) - (1 - yk) .* log(1 - h))));


r = (lambda / (2 * m)) * (sum(sum(Theta1(:, 2:end) .^ 2))
    + sum(sum(Theta2(:, 2:end) .^ 2)));
J = J + r;

for row = 1:m
    a1 = [1 X(row,:)]';
    z2 = Theta1 * a1;
    a2 = sigmoid(z2);
    a2 = [1; a2];
    z3 = Theta2 * a2;
    a3 = sigmoid(z3);

    z2 = [1; z2];
    delta3 = a3 - yk'(:, row);
    delta2 = (Theta2' * delta3) .* sigmoidGradient(z2);
    delta2 = delta2(2:end);

    Theta1_grad = Theta1_grad + delta2 * a1';
    Theta2_grad = Theta2_grad + delta3 * a2';

end

Theta1_grad = Theta1_grad ./ m;
Theta1_grad(:, 2:end) = Theta1_grad(:, 2:end) ...
        + (lambda/m) * Theta1(:, 2:end);
Theta2_grad = Theta2_grad ./ m;
Theta2_grad(:, 2:end) = Theta2_grad(:, 2:end) + ...
        + (lambda/m) * Theta2(:, 2:end);
% -------------------------------------------------------------

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

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

进行神经网络训练时,权重矩阵的随机初始化很重要。这里我们设置初始化的随机值在-0.12至0.12之间,设定一个较小的值以确保证学习过程更有效率。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_init=0.12;
W=rand(L_out,1+L_in)*2*epsilon_init-epsilon_init;

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

end

然后我们加入梯度验证,使用近似项计算偏导项值,checkNNGradients.m代码如下:

function numgrad = computeNumericalGradient(J, theta)
%COMPUTENUMERICALGRADIENT Computes the gradient using "finite differences"
%and gives us a numerical estimate of the gradient.
%   numgrad = COMPUTENUMERICALGRADIENT(J, theta) computes the numerical
%   gradient of the function J around theta. Calling y = J(theta) should
%   return the function value at theta.

% Notes: The following code implements numerical gradient checking, and 
%        returns the numerical gradient.It sets numgrad(i) to (a numerical 
%        approximation of) the partial derivative of J with respect to the 
%        i-th input argument, evaluated at theta. (i.e., numgrad(i) should 
%        be the (approximately) the partial derivative of J with respect 
%        to theta(i).)
%                

numgrad = zeros(size(theta));
perturb = zeros(size(theta));
e = 1e-4;
for p = 1:numel(theta)
    % Set perturbation vector
    perturb(p) = e;
    loss1 = J(theta - perturb);
    loss2 = J(theta + perturb);
    % Compute Numerical Gradient
    numgrad(p) = (loss2 - loss1) / (2*e);
    perturb(p) = 0;
end

end

一旦计算出的值和近似值之差很小,我们就可以确认梯度计算是正确的。关闭梯度检验,然后我们使用fmincg来学习参数θ,便可以得到使代价函数最小的参数。

Machine Learning - Coursera 吴恩达机器学习教程 Week1 学习笔记 机器学习的定义 Arthur Samuel 传统定义 Arthur Samuel: “the field of study that gives computers the ability to learn without being explicitly programmed.” This is an older, informal definition. 让计算机无需明确编程,就有学习能力。 Tom Mitchell 现代定义 Tom Mitchell: “A computer program is s 阅读详情

相关推荐

ex4 Coursera Machine-Learning exercise4 课后题答案 jupyter/python 版本 Andrew ng 吴恩达

吴恩达Machine-Learning 课后练习jupyter版本答案 exercise4(系列持续更新) 答案链接:exercise4 https://github.com/NealChalmers/Stanford-CS229-ML-AndrewNg/tree/master/Exercise4 谢谢你的star Introduction In this exercise, you will i...

qq_36418141的博客 640

Coursera machine learning答案

Coursera机器学习的8个练习所有答案,自己写的

Coursera 机器学习课程 Machine Learning Andrew Ng Stanford 讲义合集 lectures

最新(2013年春)一期的Coursera 机器学习课程 Machine Learning Andrew Ng Stanford 讲义合集 lectures 是我在跟进课程学习时候下载的,非常好的课程和讲解,的确很有收获。 希望能够对大家有用。

世界上最大的在线学习平台: Coursera 入门指南

我在 Coursera 平台上学习了很多课程, 其中过程并不乏味, 相反常常伴随着接触到新思路新知识的惊喜和感动。教育和学习是支持人不断上升的途径, 但抛开功利的成分, 学习本身已经是非常令人享受的体验。希望大家能通过这篇文章熟悉 Coursera 平台的用法, 并有机会接触到自己感兴趣的新领域、新知识。.........

云满笔记 1万+

machine learning ex4

本周作业:Neural Networks Learning实现神经网络BP算法,应用于手写数字的辨别。[*] sigmoidGradient.m - Compute the gradient of the sigmoid function[*] randInitializeWeights.m - Randomly initialize weights[*] nnCostFunction.m - N...

yestin_L的博客 527

Coursera极品课程——Learning How To Learn

第一周 一、集中与发散思维概论 集中思维(Focused mode):专注于学习或理解知识时所使用的思维,适用于学习和理解已有的知识。 发散思维(Diffused mode):适用于需要新想法、新概念和创新性的情况。 两种思维不可同时使用 二、课程结构介绍 将学习以下内容: 1、自己是如何自欺欺人的 2、如何更加深刻的将知识印入脑海中 3、如何凝炼知识以便更容易理解 4、克服拖延症的简单技巧(我还...

土豆大叔的博客 2071

Coursera Machine Learning Ex4

nnCostFunction: a1 = [ones(m,1) X]; z2 = a1*Theta1'; a2 = sigmoid(z2); m1 = size(a2,1); a2 = [ones(m1,1) a2]; z3 = a2*Theta2'; a3 = sigmoid(z3); %temp = log(a3); for i=1:num_labels; ynew(:,i)

liucq12的博客 3519

Coursera-Machine Learning-ex4

Some Points: Implement Steps: 1.Pick a neural network  architecture. number of input units = dimension of features number of output units = number of classes number of hidden layer = 1(Default), ...

language_zcx的博客 255

coursera Stanford Machine Learning Week4 Ex3机器学习 实验3

jimtoot的博客 569

coursera Stanford Machine Learning Week5 Ex4机器学习 实验4

Programming Exercise 4:Neural Networks Learning 1.神经网络 1.1 观察数据 本次实验数据与实验3一样,是m=5000个手写数字的灰阶图像。其中每个数字(0--9)各500个,每个图像为20x20的像素。所以X为5000x400的Matrix。Y对应每个图像的值(10 -- 9)10代表数字0。displayData函数将从数据集X中随机选1...

jimtoot的博客 1277

斯坦福机器学习编程作业machine-learning-ex4,神经网络模型,Neural Networks Learning题目,满分,2015最新作业答案

斯坦福机器学习编程作业machine-learning-ex4,神经网络模型,Neural Networks Learning题目,满分,2015最新作业答案 MATLAB 满分

Coursera Machine Learning 第五周week5 ex4Neural Networks Learning编程全套满分题目+注释

Coursera Machine Learning 第五周week5 ex4Neural Networks Learning编程全套满分题目+注释

machine-learning-ex4(编程作业:Neural Networks Learning,程序运行结果正确)

machine-learning-ex4(编程作业:Neural Networks Learning,程序运行结果正确)

CourseraMachine Learning》(机器学习课程,主讲教师为Andrew Ng)配套作业

CourseraMachine Learning》(机器学习课程,主讲教师为Andrew Ng)的课程是机器学习的入门经典课程之一,其特点是深入浅出,并且由一些难度适宜的作业(Matlab编程作业)以帮助学员理解理论。但是很多朋友不清楚如何获取到这些作业,因此整理并上传资料

matlab反向传播算法,[Coursera] Machine Learning ex4 反向传播算法

这周和上周的作业一样,数据集还是5000个 20x20 像素的手写字母,这周会用到反向传播的算法。一共5段需要提交的代码,如果上周的内容弄清楚了,跟着教程的话作业是不太难的(虽然课程视频内容很烧脑)。Feedforward and cost function 30Regularized cost function 15Sigmoid gradient 5Neural net gradient f...

weixin_39963523的博客 331

Coursera Machine Learning 第五周编程week5 ex4Neural Networks Learning编程全套满分题目+注释

资源链接:http://download.csdn.net/download/sinat_39805237/10152688 正常设置迭代次数和lambda的结果 当保证lambda不变,改变迭代次数为150次(在ex4.m中Part8中修改),准确率达到99% 当保证迭代次数为50不变时,改变lambda=0.01,准确率可到96%,由于初始化的随机性可能略有偏

sinat_39805237的博客 1456

coursera python答案,ex4 Coursera Machine-Learning exercise4 课后题答案 jupyter/python 版本 Andrew ng 吴恩达...

吴恩达Machine-Learning 课后练习jupyter版本答案 exercise4(系列持续更新)答案链接:exercise4https://github.com/NealChalmers/Stanford-CS229-ML-AndrewNg/tree/master/Exercise4谢谢你的starIntroductionIn this exercise, you will implem...

weixin_39731782的博客 226

Coursera Machine Learning 第四周week4编程 ex3Multi-class Classication and Neural Networks编程全套满分题目+注释

资源链接: http://download.csdn.net/download/sinat_39805237/10148508 成绩: 分类结果: 神经网络预测结果:

sinat_39805237的博客 904

Coursera-Machine Learning-ex5

Some Points:   The Results: linearRegCostFunction.m function [J, grad] = linearRegCostFunction(X, y, theta, lambda) % Initialize some useful values m = length(y); % number of training examples %...

language_zcx的博客 387
上一篇: Coursera-Machine-Learning-Review-W5
下一篇: Coursera-Machine-Learning-Review-W6
Avoke17
博客等级 码龄8年 0粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值