1.lrCostFunction:

和第三周的那个一样的;

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);
for i=1:m,
J=J+1/m*(-y(i)*log(h(i))-(1-y(i))*log(1-h(i)));
endfor
n=length(theta);
for i=2:n,
J=J+lambda/(2*m)*theta(i)^2;
endfor grad(1)=1/m*(h-y)'*X(:,1);
for i=2:n,
grad(i)=1/m*(h-y)'*X(:,i)+lambda/m*theta(i);
endfor % ============================================================= grad = grad(:); end

  

2.oneVsAll 

注意的一点是:

fmincg中的 initial_theta为列向量,所以需要转置一下;

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
% logistic 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 you
% 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);
% options=optimset('GradObj','on','MaxIter',50); for i=1:num_labels,
all_theta(i,:)=fmincg(@(t)(lrCostFunction(t,X,(y==i),lambda)),all_theta(i,:)',options);
endfor % ========================================================================= end

  

3.PredictOneVSAll

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.
% [Max,p]=max(X*all_theta',[],2); % ========================================================================= end

  

4.predict

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];
a2=[ones(m,1) sigmoid(X*Theta1')]; [Max,p]=max(sigmoid(a2*Theta2'),[],2); % ========================================================================= end

  

Machine learning第四周code 编程作业的更多相关文章

  1. Machine learning 第7周编程作业 SVM

    1.Gaussian Kernel function sim = gaussianKernel(x1, x2, sigma) %RBFKERNEL returns a radial basis fun ...

  2. Machine learning第6周编程作业

    1.linearRegCostFunction: function [J, grad] = linearRegCostFunction(X, y, theta, lambda) %LINEARREGC ...

  3. Machine learning 第8周编程作业 K-means and PCA

    1.findClosestCentroids function idx = findClosestCentroids(X, centroids) %FINDCLOSESTCENTROIDS compu ...

  4. Machine learning 第5周编程作业

    1.Sigmoid Gradient function g = sigmoidGradient(z) %SIGMOIDGRADIENT returns the gradient of the sigm ...

  5. Hand on Machine Learning第三章课后作业(1):垃圾邮件分类

    import os import email import email.policy 1. 读取邮件数据 SPAM_PATH = os.path.join( "E:\\3.Study\\机器 ...

  6. 【machine learning通俗讲解code逐行注释】之线性回归实现

    现在机器学习算法在分类.回归.数据挖掘等问题上运用的十分广泛,对于初学者来说,可能一听到'算法'或其他的专属名词都感觉高深莫测,以致很多人望而却步,这让很多人在处理很多问题上失去了一个很有用的工具.机 ...

  7. Hand on Machine Learning第三章课后作业(2):其余小练习

    -#!/usr/bin/env python -# # # -- coding: utf-8 -- -# # # @Time : 2019.5.22 14:09 -# # # @Author : An ...

  8. 機器學習基石 (Machine Learning Foundations) 作业1 Q15-17的C++实现

    大家好,我是Mac Jiang.今天和大家分享Coursera-台湾大学-機器學習基石 (Machine Learning Foundations) -作业1的Q15-17题的C++实现. 这部分作业 ...

  9. 機器學習基石(Machine Learning Foundations) 机器学习基石 作业三 课后习题解答

    今天和大家分享coursera-NTU-機器學習基石(Machine Learning Foundations)-作业三的习题解答.笔者在做这些题目时遇到非常多困难,当我在网上寻找答案时却找不到,而林 ...

随机推荐

  1. git忽略某个文件

    data/config/config.ini.php

  2. 开始第一个Android应用程序

    Android应用程序建立在应用程序框架之上,所以Android编程就是面向应用程序框架API编程---与编写普通的Java SE没有太大区别,只是增加了一些API. 1.使用eclipse开发第一个 ...

  3. SpringBoot里的一些注解

    Spring不仅可以通过xml配置获取*.properties,还可以通过@Value注解的方式来获取,将properties配置文件中的属性值注入到java成员变量. 如果不想每次都写private ...

  4. HDU 5117 Fluorescent (数学+状压DP)

    题意:有 n 个灯,初始状态都是关闭,有m个开关,每个开关都控制若干个.问在m个开关按下与否的2^m的情况中,求每种情况下亮灯数量的立方和. 析:首先,如果直接做的话,时间复杂度无法接受,所以要对其进 ...

  5. php 访问用友u8数据

    <?php namespace app\api\controller; use think\Controller; use think\Db; use think\Log; /** * desc ...

  6. ZOJ3767 Elevator 2017-04-13 23:32 37人阅读 评论(0) 收藏

    Elevator Time Limit: 2 Seconds      Memory Limit: 65536 KB How time flies! The graduation of this ye ...

  7. 在Github注册账户

    https://github.com/JasonHaoz

  8. [Postgres]Postgres复制表

    在需要把含有分表的总表备份的时候想到的笨办法,如果有什么更先进的办法万望告知. 比如TableOld是由TableOld1,TableOld2,TableOld3组合而成,现在需要对TableOld进 ...

  9. Oracle 程序中超好用的日志记录TYPE,可以直接Copy使用

    创建类型名称:LOGGER_FACTORY Type 说明: CREATE OR REPLACE TYPE "LOGGER_FACTORY" AS OBJECT( v_progra ...

  10. threadpoolExecutor----自动执行任务

    使用threadpoolExecutor,主要是任务的提交的执行和获取结果. 提交任务的方法有: 1.submit 2.execute 3.queue的add 其中1和2的使用必须是threadpoo ...