版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40883132/article/details/83244669
具体代码请参照:https://github.com/RobertWang2/Python-/tree/master/ml-class-ex/machine-learning-ex2
黑色的代表被录取;
蓝色的代表未被录取;
绿色的是边缘条件;
重要代码解析:
好,我们看到数据有三列,第一、二列是单个学生的成绩,第三列是是否被录取,0未被录取,1录取。
X = data(:, [1, 2]); y = data(:, 3);
X代表单个学生的成绩,y代表改学生是否被录取。
扫描二维码关注公众号,回复:
3753220 查看本文章
接下来看plotData这个函数:
figure; hold on;
%继续绘制图形
% ====================== YOUR CODE HERE ======================
% Instructions: Plot the positive and negative examples on a
% 2D plot, using the option 'k+' for the positive
% examples and 'ko' for the negative examples.
%
pos=find(y==1);
neg=find(y==0);
plot(X(pos,1),X(pos,2),'k+','LineWidth',2,'MarkerSize',7);
plot(X(neg,1),X(neg,2),'ko','MarkerFaceColor','y','MarkerSize',7);
pos是在y(n*1)中找到y=1的下标,neg同理;
每一个标记的(x,y)是根据该同学y的状态确定的X中的第一列和第二列的值。比如:
该同学被录取的情况下,前两次的成绩的行坐标row1,row2分别作为该标记的(x,y);
costFunction:
function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
% J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
% parameter for 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
%
% Note: grad should have the same dimensions as theta
%
h=sigmoid(X*theta);
J=sum(-y'*log(h)-(1-y)'*log(1-h))/m;
grad=(h-y)'*X/m;
% =============================================================
end
预测:
很简单,p>=0.5 ,则认为被录取,反之,未被录取。
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
%
v=sigmoid(X*theta);
for i=1:m
if v(i,1)>=0.5
p(i,1)=1;
else
p(i,1)=0;
end
% =========================================================================
end