Stanford 机器学习练习 Part 3 Neural Networks: Representation

简介: 从神经网络开始,感觉自己慢慢跟不上课程的节奏了,一些代码好多参考了别人的代码,而且,让我现在单独写也不一定写的出来了。学习就是一件慢慢积累的过程,两年前我学算法的时候,好多算法都完全看不懂,但后来,看的多了,做的多了,有一天就茅塞顿开。所有的困难都是一时的,只要坚持下去,一切问题都会解决的。没忍住发了点鸡汤文。

从神经网络开始,感觉自己慢慢跟不上课程的节奏了,一些代码好多参考了别人的代码,而且,让我现在单独写也不一定写的出来了。学习就是一件慢慢积累的过程,两年前我学算法的时候,好多算法都完全看不懂,但后来,看的多了,做的多了,有一天就茅塞顿开。所有的困难都是一时的,只要坚持下去,一切问题都会解决的。没忍住发了点鸡汤文。


   关于神经网络,我表示现在的理解就是每一层都每个神经元都是依靠logistics regression得出的,所以必须先要掌握logistics regression。关于如何训练这个模型的算法(比如 反向传播算法),我也在这周的课程中慢慢学。其中涉及到好多数据处理的技巧,这些都是得通过练习才能学会的。


   下面是我参考别人代码写的第四周神经网络的编程练习,仅作为参考。


关于lrCostFunction,我直接用了上周练习中CostFunction的代码,没想到竟然也可以通过。


lrCostFunction.m

function [J, grad] = lrCostFunction(theta, X, y, lambda)
%LRCOSTFUNCTION Compute cost and gradient for logistic regression with 
%regularization
%   J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using
%   theta as the parameter for regularized logistic regression and the
%   gradient of the cost w.r.t. to the parameters. 
% Initialize some useful values
m = length(y); % number of training examples
% You need to return the following variables correctly 
J = 0;
grad = zeros(size(theta));
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta
%
% Hint: The computation of the cost function and gradients can be
%       efficiently vectorized. For example, consider the computation
%
%           sigmoid(X * theta)
%
%       Each row of the resulting matrix will contain the value of the
%       prediction for that example. You can make use of this to vectorize
%       the cost function and gradient computations. 
%
% Hint: When computing the gradient of the regularized cost function, 
%       there're many possible vectorized solutions, but one solution
%       looks like:
%           grad = (unregularized gradient for logistic regression)
%           temp = theta; 
%           temp(1) = 0;   % because we don't add anything for j = 0  
%           grad = grad + YOUR_CODE_HERE (using the temp variable)
%
h = sigmoid(X*theta);  
J = m^-1 * sum(((-1) * y.*log(h)).-((1- y).*log(1 - h)));
theta(1) = 0;
tmp = lambda/(2*m)*sum(theta.^2);
J = J + tmp;
grad = m^-1 * ((h.-y)'*X)' + lambda/m * theta; 
% =============================================================
grad = grad(:);
end



oneVsAll.m

function [all_theta] = oneVsAll(X, y, num_labels, lambda)
%ONEVSALL trains multiple logistic regression classifiers and returns all
%the classifiers in a matrix all_theta, where the i-th row of all_theta 
%corresponds to the classifier for label i
%   [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels
%   logisitc regression classifiers and returns each of these classifiers
%   in a matrix all_theta, where the i-th row of all_theta corresponds 
%   to the classifier for label i
% Some useful variables
m = size(X, 1);
n = size(X, 2);
% You need to return the following variables correctly 
all_theta = zeros(num_labels, n + 1);
% Add ones to the X data matrix
X = [ones(m, 1) X];
% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the following code to train num_labels
%               logistic regression classifiers with regularization
%               parameter lambda. 
%
% Hint: theta(:) will return a column vector.
%
% Hint: You can use y == c to obtain a vector of 1's and 0's that tell use 
%       whether the ground truth is true/false for this class.
%
% Note: For this assignment, we recommend using fmincg to optimize the cost
%       function. It is okay to use a for-loop (for c = 1:num_labels) to
%       loop over the different classes.
%
%       fmincg works similarly to fminunc, but is more efficient when we
%       are dealing with large number of parameters.
%
% Example Code for fmincg:
%
%     % Set Initial theta
%     initial_theta = zeros(n + 1, 1);
%     
%     % Set options for fminunc
%     options = optimset('GradObj', 'on', 'MaxIter', 50);
% 
%     % Run fmincg to obtain the optimal theta
%     % This function will return theta and the cost 
%     [theta] = ...
%         fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
%                 initial_theta, options);
%
for k=1:num_labels
    initial_theta = zeros(n + 1, 1);
    options = optimset('GradObj', 'on', 'MaxIter', 50);
    [theta] = fmincg (@(t)(lrCostFunction(t, X, (y == k), lambda)),initial_theta, options);
    all_theta(k,:) = theta';
end
% =========================================================================
end


predictOneVsAll.m


function p = predictOneVsAll(all_theta, X)
%PREDICT Predict the label for a trained one-vs-all classifier. The labels 
%are in the range 1..K, where K = size(all_theta, 1). 
%  p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions
%  for each example in the matrix X. Note that X contains the examples in
%  rows. all_theta is a matrix where the i-th row is a trained logistic
%  regression theta vector for the i-th class. You should set p to a vector
%  of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2
%  for 4 examples) 
m = size(X, 1);
num_labels = size(all_theta, 1);
% You need to return the following variables correctly 
p = zeros(size(X, 1), 1);
% Add ones to the X data matrix
X = [ones(m, 1) X];
% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters (one-vs-all).
%               You should set p to a vector of predictions (from 1 to
%               num_labels).
%
% Hint: This code can be done all vectorized using the max function.
%       In particular, the max function can also return the index of the 
%       max element, for more information see 'help max'. If your examples 
%       are in rows, then, you can use max(A, [], 2) to obtain the max 
%       for each row.
%       
[c,i] = max(sigmoid(X * all_theta'), [], 2);
p = i;
% =========================================================================
end


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);
% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned neural network. You should set p to a 
%               vector containing labels between 1 to num_labels.
%
% Hint: The max function might come in useful. In particular, the max
%       function can also return the index of the max element, for more
%       information see 'help max'. If your examples are in rows, then, you
%       can use max(A, [], 2) to obtain the max for each row.
%
X = [ones(m, 1) X];
z2 = Theta1 * X';
a2 = sigmoid(z2);
a2 = [ones(1, m);a2];
z3 = Theta2 * a2;
a3 = sigmoid(z3);
output =a3';
[c,i] = max(output, [], 2);
p = i;
% =========================================================================
end
目录
相关文章
|
机器学习/深度学习
Stanford 机器学习练习 Part 2 Logistics Regression
以下是我学习Andrew Ng machine learning 课程时logistic regression的相关代码,仅作为参考,因为是初学,暂时没办法做出总结。
50 1
|
机器学习/深度学习
Stanford 机器学习练习 Part 1 Linear Regression
In octave, we return values by defining which variables % represent the return values (at the top of the file)
50 0
|
机器学习/深度学习 算法
阿旭机器学习实战【5】KNN算法实战练习2:利用KNN模型进行手写体数字识别
阿旭机器学习实战【5】KNN算法实战练习2:利用KNN模型进行手写体数字识别
阿旭机器学习实战【5】KNN算法实战练习2:利用KNN模型进行手写体数字识别
|
机器学习/深度学习 算法
阿旭机器学习实战【4】KNN算法实战练习1:利用KNN算法预测某人对你喜欢程度
阿旭机器学习实战【4】KNN算法实战练习1:利用KNN算法预测某人对你喜欢程度
阿旭机器学习实战【4】KNN算法实战练习1:利用KNN算法预测某人对你喜欢程度
|
机器学习/深度学习 存储 数据可视化
吴恩达机器学习ex3 Multi-class Classfication and Neural Networks(python)
吴恩达机器学习ex3 Multi-class Classfication and Neural Networks(python)
吴恩达机器学习ex3 Multi-class Classfication and Neural Networks(python)
|
机器学习/深度学习 算法 数据挖掘
cs224w(图机器学习)2021冬季课程学习笔记16 Community Detection in Networks
本章主要内容: 本章首先介绍了网络中社区community(或cluster / group)的概念,以及从社会学角度来证明了网络中社区结构的存在性。 接下来介绍了modularity概念衡量community识别效果。 然后介绍了Louvain算法1识别网络中的community。 对于overlapping communiteis,本章介绍了BigCLAM2 方法来进行识别。
cs224w(图机器学习)2021冬季课程学习笔记16 Community Detection in Networks
|
机器学习/深度学习 索引
cs224w(图机器学习)2021冬季课程学习笔记11 Theory of Graph Neural Networks
cs224w(图机器学习)2021冬季课程学习笔记11 Theory of Graph Neural Networks
cs224w(图机器学习)2021冬季课程学习笔记11 Theory of Graph Neural Networks
|
机器学习/深度学习 数据挖掘 异构计算
cs224w(图机器学习)2021冬季课程学习笔记10 Applications of Graph Neural Networks
cs224w(图机器学习)2021冬季课程学习笔记10 Applications of Graph Neural Networks
cs224w(图机器学习)2021冬季课程学习笔记10 Applications of Graph Neural Networks
|
机器学习/深度学习 Java 知识图谱
cs224w(图机器学习)2021冬季课程学习笔记9 Graph Neural Networks 2: Design Space
cs224w(图机器学习)2021冬季课程学习笔记9 Graph Neural Networks 2: Design Space
cs224w(图机器学习)2021冬季课程学习笔记9 Graph Neural Networks 2: Design Space
|
7月前
|
机器学习/深度学习 存储 搜索推荐
利用机器学习算法改善电商推荐系统的效率
电商行业日益竞争激烈,提升用户体验成为关键。本文将探讨如何利用机器学习算法优化电商推荐系统,通过分析用户行为数据和商品信息,实现个性化推荐,从而提高推荐效率和准确性。
248 14