不同的λ(0,1,10,100)值对regularization的影响\ 预测新的值和计算模型的精度

%% ============= Part 2: Regularization and Accuracies =============
% Optional Exercise:
% In this part, you will get to try different values of lambda and
% see how regularization affects the decision coundart
%
% Try the following values of lambda (0, 1, 10, 100).
%
% How does the decision boundary change when you vary lambda? How does
% the training set accuracy vary?
%

% Initialize fitting parameters
initial_theta = zeros(size(X, 2), 1);

% Set regularization parameter lambda to 1 (you should vary this)
lambda = 1;    %在这里设置λ=(0,1,10,100)

由下图可见,lambda=1时的效果最好,

λ=0时No regularization(overfitting);

λ=100时会too much regularization(underfitting),

% Set Options
options = optimset('GradObj', 'on', 'MaxIter', 400);   %计算gradient,迭代的次数为400次

% Optimize
[theta, J, exit_flag] = ...
fminunc(@(t)(costFunctionReg(t, X, y, lambda)), initial_theta, options);

% Plot Boundary
plotDecisionBoundary(theta, X, y);  %X已经mapFeature过了
hold on;
title(sprintf('lambda = %g', lambda))    % 会在%e和%f中自动选择一种格式,且无后缀0。

% Labels and Legend
xlabel('Microchip Test 1')
ylabel('Microchip Test 2')

legend('y = 1', 'y = 0', 'Decision boundary')
hold off;

% Compute accuracy on our training set
p = predict(theta, X);

fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);

plotDecisionBoundary.m文件

function plotDecisionBoundary(theta, X, y)
%PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with
%the decision boundary defined by theta
% PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the
% positive examples and o for the negative examples. X is assumed to be
% a either
% 1) Mx3 matrix, where the first column is an all-ones column for the
% intercept.
% 2) MxN, N>3 matrix, where the first column is all-ones

% Plot Data
plotData(X(:,2:3), y);
hold on

if size(X, 2) <= 3
% Only need 2 points to define a line, so choose two endpoints
   plot_x = [min(X(:,2))-2, max(X(:,2))+2];

% Calculate the decision boundary line
   plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));

% Plot, and adjust axes for better viewing
   plot(plot_x, plot_y)

% Legend, specific for the exercise
   legend('Admitted', 'Not admitted', 'Decision Boundary')
   axis([30, 100, 30, 100])
else      %X已经mapFeature过了(有28个features),调用这部分的程序
% Here is the grid range
   u = linspace(-1, 1.5, 50);
   v = linspace(-1, 1.5, 50);

z = zeros(length(u), length(v));
% Evaluate z = theta*x over the grid
for i = 1:length(u)
    for j = 1:length(v)
       z(i,j) = mapFeature(u(i), v(j))*theta;
    end
end
z = z'; % important to transpose z before calling contour

% Plot z = 0
% Notice you need to specify the range [0, 0]
contour(u, v, z, [0, 0], 'LineWidth', 2)    %画等值线.contour(X,Y,Z,[v v]) to draw contours for the single level v.
end  %if size(X, 2) <= 3  else的end
hold off

end

predict.m文件

function p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic
%regression parameters theta
% p = PREDICT(theta, X) computes the predictions for X using a
% threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
% your learned logistic regression parameters.
% You should set p to a vector of 0's and 1's
%
for i=1:m
    if sigmoid(X(i,:) * theta) >=0.5
        p(i) = 1;
    else
        p(i) = 0;
    end
end

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

end

matlab(8) Regularized logistic regression : 不同的λ(0,1,10,100)值对regularization的影响,对应不同的decision boundary\ 预测新的值和计算模型的精度predict.m的更多相关文章

  1. matlab(7) Regularized logistic regression : mapFeature(将feature增多) and costFunctionReg

    Regularized logistic regression : mapFeature(将feature增多) and costFunctionReg ex2_reg.m文件中的部分内容 %% == ...

  2. matlab(6) Regularized logistic regression : plot data(画样本图)

    Regularized logistic regression :  plot data(画样本图) ex2data2.txt 0.051267,0.69956,1-0.092742,0.68494, ...

  3. machine learning(15) --Regularization:Regularized logistic regression

    Regularization:Regularized logistic regression without regularization 当features很多时会出现overfitting现象,图 ...

  4. matlab(5) : 求得θ值后用模型来预测 / 计算模型的精度

    求得θ值后用模型来预测 / 计算模型的精度  ex2.m部分程序 %% ============== Part 4: Predict and Accuracies ==============% Af ...

  5. ResourceWarning: unclosed <socket.socket fd=864, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('10.100.x.x', 37321), raddr=('10.1.x.x', 8500)>解决办法

    将代码封装,并使用unittest调用时,返回如下警告: C:\python3.6\lib\collections\__init__.py:431: ResourceWarning: unclosed ...

  6. Regularized logistic regression

    要解决的问题是,给出了具有2个特征的一堆训练数据集,从该数据的分布可以看出它们并不是非常线性可分的,因此很有必要用更高阶的特征来模拟.例如本程序中个就用到了特征值的6次方来求解. Data To be ...

  7. 编程作业2.2:Regularized Logistic regression

    题目 在本部分的练习中,您将使用正则化的Logistic回归模型来预测一个制造工厂的微芯片是否通过质量保证(QA),在QA过程中,每个芯片都会经过各种测试来保证它可以正常运行.假设你是这个工厂的产品经 ...

  8. 吴恩达机器学习笔记22-正则化逻辑回归模型(Regularized Logistic Regression)

    针对逻辑回归问题,我们在之前的课程已经学习过两种优化算法:我们首先学习了使用梯度下降法来优化代价函数

  9. Matlab实现线性回归和逻辑回归: Linear Regression & Logistic Regression

    原文:http://blog.csdn.net/abcjennifer/article/details/7732417 本文为Maching Learning 栏目补充内容,为上几章中所提到单参数线性 ...

随机推荐

  1. 剑指offer27:按字典序打印出该字符串中字符的所有排列

    1 题目描述 输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba. 输入描述: ...

  2. SQL——INSERT INTO(增)

    一.INSERT INTO语句的基本用法 INSERT INTO 语句用于往表中插入新记录. student表: INSERT INTO语句有2种语法格式: 1.不指定列名,直接插入记录. 语法格式如 ...

  3. Linux下实现web服务器

    说明:暂时只是实现了静态网页的响应 #include <stdio.h> #include <sys/types.h> /* See NOTES */ #include < ...

  4. Go语言学习笔记(10)——错误处理示例

    // 定义一个 DivideError 结构 type DivideError struct { dividee int divider int } // 实现 `error` 接口 func (de ...

  5. 在vue中使用ElementUI

    完整引用ElementUI: 安装:在需要使用到的vue项目目录下,使用npm下载安装: npm/cnpm i element-ui -S/--save <!-- 引入样式 --> < ...

  6. Consul基本使用

    原文: Consul基本使用 date: 2019-05-13 17:01:37 前言 官网介绍Consul是一个分布式服务网格(Service Mesh)解决方案... 而我目前的理解是提供了分布式 ...

  7. 《图解HTTP》读后总结

    阅读时间:2019.10.30-2019.11.6 阅读心得: 从知乎上看到有人推荐这本书,本身对计算机网络方面学习的比较少,于是就买来这本书开始看.这本书总体看下来比较轻松,因为书中的插画非常卡通, ...

  8. VBA子程序(十六)

    子程序(Sub Procedures,也叫子过程)与函数类似,但有一些差异. 子过程不需要有返回一个值,而函数可能会或可能不会有返回一个值. 子程序可以不用call关键字来调用. 子程序总是包含在Su ...

  9. VBA循环(十一)

    当需要多次执行一段代码时,就可以使用循环语句. 一般来说,语句是按顺序执行的:函数中的第一个语句首先执行,然后是第二个,依此类推. 编程语言提供了各种控制结构,允许更复杂的执行路径. 循环语句允许多次 ...

  10. JS权威指南读书笔记(一)

    第一章 JavaScript概述 1 JS是一门高端的.动态的.弱类型的编程语言,非常适合面向对象和函数式的编程风格.   第二章 词法结构 1 JS程序是用Unicode字符集编写的. 2 JS是区 ...