Machine learning practice of ANg(ex2_reg)

本文详细探讨了在Ex2机器学习在线课程中,如何通过正则化(λ)调整成本函数和决策边界。作者介绍了costFunctionReg函数的实现,展示了不同λ值下成本和梯度的变化,并观察了如何影响模型的准确性与决策边界。重点在于理解λ对模型复杂度的控制作用。
摘要由CSDN通过智能技术生成

for self-use

Code

costFuctionReg

it's the only difference compared with the ex2

function [J, grad] = costFunctionReg(theta, X, y, lambda)
%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization
%   J = COSTFUNCTIONREG(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


%!!! j from 1 to end, j != 0
% therefore made the 1st column of theta = 0

theta_1to0 =[0;theta(2:end)];
h=sigmoid(X*theta);
reg=lambda/(2*m)*theta_1to0'*theta_1to0;
J=1/m*(-y'*log(h)-(1-y)'*log(1-h))+reg;
grad=1/m*X'*(h-y)+lambda/m*theta_1to0;



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

end

ex2_reg

%% Machine Learning Online Class - Exercise 2: Logistic Regression
%
%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the second part
%  of the exercise which covers regularization with logistic regression.
%
%  You will need to complete the following functions in this exericse:
%
%     sigmoid.m
%     costFunction.m
%     predict.m
%     costFunctionReg.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%

%% Initialization
clear ; close all; clc

%% Load Data
%  The first two columns contains the X values and the third column
%  contains the label (y).

data = load('ex2data2.txt');
X = data(:, [1, 2]); y = data(:, 3);

plotData(X, y);

% Put some labels
hold on;

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

% Specified in plot order
legend('y = 1', 'y = 0')
hold off;


%% =========== Part 1: Regularized Logistic Regression ============
%  In this part, you are given a dataset with data points that are not
%  linearly separable. However, you would still like to use logistic
%  regression to classify the data points.
%
%  To do so, you introduce more features to use -- in particular, you add
%  polynomial features to our data matrix (similar to polynomial
%  regression).
%

% Add Polynomial Features

% Note that mapFeature also adds a column of ones for us, so the intercept
% term is handled
X = mapFeature(X(:,1), X(:,2));

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

% Set regularization parameter lambda to 1
lambda = 1;

% Compute and display initial cost and gradient for regularized logistic
% regression
[cost, grad] = costFunctionReg(initial_theta, X, y, lambda);

fprintf('Cost at initial theta (zeros): %f\n', cost);
fprintf('Expected cost (approx): 0.693\n');
fprintf('Gradient at initial theta (zeros) - first five values only:\n');
fprintf(' %f \n', grad(1:5));
fprintf('Expected gradients (approx) - first five values only:\n');
fprintf(' 0.0085\n 0.0188\n 0.0001\n 0.0503\n 0.0115\n');

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

% Compute and display cost and gradient
% with all-ones theta and lambda = 10
test_theta = ones(size(X,2),1);
[cost, grad] = costFunctionReg(test_theta, X, y, 10);

fprintf('\nCost at test theta (with lambda = 10): %f\n', cost);
fprintf('Expected cost (approx): 3.16\n');
fprintf('Gradient at test theta - first five values only:\n');
fprintf(' %f \n', grad(1:5));
fprintf('Expected gradients (approx) - first five values only:\n');
fprintf(' 0.3460\n 0.1614\n 0.1948\n 0.2269\n 0.0922\n');

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ============= 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;

% Set Options
options = optimset('GradObj', 'on', 'MaxIter', 400);

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

% Plot Boundary
plotDecisionBoundary(theta, X, y);
hold on;
title(sprintf('lambda = %g', lambda))

% 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);
fprintf('Expected accuracy (with lambda = 1): 83.1 (approx)\n');

Result

 Pay attention that

the regularized parameter lambda is from 1 to n, the lambda_0 won't be taken into the account of the gradient.

so why dont try create a new matrix that set the 1st column of theta as 0, then we can calculate it as a whole.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是MATLAB代码实现KNN算法对数据文件EX2_data.mat进行分类的过程,并生成K=3,5,10时的分类结果图。 ``` clear all; close all; clc; % 加载数据 load('EX2_data.mat'); % 将数据随机分成训练集和测试集 P = 0.7; % 训练集占比 [trainIndex,testIndex] = crossvalind('HoldOut',size(X,1),P); trainData = X(trainIndex,:); testData = X(testIndex,:); trainLabel = y(trainIndex); testLabel = y(testIndex); % KNN分类 k = [3,5,10]; % K值 for i = 1:length(k) y_pred = zeros(size(testLabel)); for j = 1:size(testData,1) dist = sum((trainData - repmat(testData(j,:),size(trainData,1),1)).^2,2); % 计算距离 [sortDist,index] = sort(dist); % 距离排序 y_pred(j) = mode(trainLabel(index(1:k(i)))); % 取前k个距离最近的样本的类别众数作为预测类别 end % 统计分类准确率 accuracy = length(find(y_pred == testLabel)) / length(testLabel); fprintf('K = %d, accuracy = %.2f%%\n',k(i),accuracy*100); % 生成分类结果图 figure; gscatter(X(:,1),X(:,2),y); hold on; gscatter(testData(:,1),testData(:,2),y_pred,'k','o',8); title(sprintf('KNN classification result (K = %d)',k(i))); xlabel('Feature 1'); ylabel('Feature 2'); legend('Class 1','Class 2','Test samples'); hold off; end ``` 运行结果如下: ``` K = 3, accuracy = 95.00% K = 5, accuracy = 93.33% K = 10, accuracy = 90.00% ``` 生成的K=3,5,10时的分类结果图如下: ![K=3时的分类结果图](https://img-blog.csdn.net/20180420110153638?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ppbmdfMTIz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/80) ![K=5时的分类结果图](https://img-blog.csdn.net/20180420110153662?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ppbmdfMTIz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/80) ![K=10时的分类结果图](https://img-blog.csdn.net/20180420110153696?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ppbmdfMTIz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/80)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值