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. android textview 显示一行,且超出自动截断,显示"..."

    android textview 显示一行,且超出自动截断,显示"..." <TextView android:layout_width="wrap_content ...

  2. 关于使用 ps脚本来处理图片的排层问题

    问题是这样,在三维软件 把模型切割,给切割的部件排上序号 如 :tianji_1-431_bujian13.png 中间一段数据就是表示的 1.431 该数据之后 会到ps总排层使用 在ps排层出三维 ...

  3. mybatis小工具

    1.其实也不算是针对mybatis的其他都可以用 lombok 2.mybatis的小插件,可以快速定位到mapper.xml和接口之间 mybatisx

  4. join sql图

    SELECT * FROM TableA INNER JOIN TableB ON TableA.name = TableB.name   id  name       id   name --  - ...

  5. kalilinux、parrotsecos没有声音

    Kali Linux系统默认状态下,root用户是无法使用声卡的,也就没有声音.启用的方法如下: (1)在终端执行命令:systemctl --user enable pulseaudio (2)在/ ...

  6. javascript编码规范[原创]

    一些命名规范书或js书命名规范章节,喜欢将命名规范跟语法混在一块例如: 1.使用“var”定义.初始化变量防止产生全局变量,多变量一块定义使用“,”(本身这种方式就很有争议). 2.结尾必加“;”防止 ...

  7. Linux 基础教程 36-查看系统性能

    uptime     uptime命令功能比较简单,主要功能如下所示: 查看服务器的开机时长 查看CPU负载 基本用法 uptime 用法示例 [root@localhost ~]# uptime 1 ...

  8. Spring IOC 和 AOP概述

    IoC(控制反转,(Inversion of Control):本来是由应用程序管理的对象之间的依赖关系,现在交给了容器管理,这就叫控制反转,即交给了IoC容器,Spring的IoC容器主要使用DI方 ...

  9. [label][OS] 制作 U 盘安装 Windows 7

    U盘安装完美的WIN7操作系统教程 [编辑] 请使用正版系统   http://item.jd.com/965031.html   以保证您的电脑信息安全 此教程适用与 win7及win8 准备工作 ...

  10. 简明的sql优化

    网上关于SQL优化的教程很多,但是比较杂乱.近日有空整理了一下,写出来跟大家分享一下,其中有错误和不足的地方,还请大家纠正补充. 这篇文章我花费了大量的时间查找资料.修改.排版,希望大家阅读之后,感觉 ...