Coursera吴恩达机器学习编程作业(ex2)正则化的LogisticRegression

本文详细介绍了Logistic回归算法的实现过程,包括Sigmoid函数计算、代价函数计算、梯度计算及正则化处理等内容,并提供了预测函数的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现函数:

sigmoid.m

function g = sigmoid(z)
%SIGMOID Compute sigmoid function
%   g = SIGMOID(z) computes the sigmoid of z.

% You need to return the following variables correctly 
g = zeros(size(z));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
%               vector or scalar).
A=-1*z;
B=exp(A)+1;
g=1./B;
% =============================================================

end

计算代价函数以及

costFunction.m

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);%hypothesis function
A=-1*y'*log(h);
B=(1.-y)'*log(1.-h);
J=1/m*sum(A-B);%cost

grad=1/m*(X'*(h-y));%derivative of theta


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

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
%
h=sigmoid(X*theta);
for i=1:m
  if(h(i)<0.5)
  p(i)=0;
  else
  p(i)=1;
end;
% =========================================================================


end

costFunctionReg.m

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

h=sigmoid(X*theta);
A=-1*y'*log(h);
B=(1.-y)'*log(1.-h);
thetao=theta;
thetao(1,1)=0;
C=thetao.^2;
J=1/m*sum(A-B)+lambda/(2*m)*sum(C);%cost

grad=1/m*(X'*(h-y));
d=grad(1);
grad=grad+lambda/m*theta;
grad(1)=d;
% =============================================================

end


<think>嗯,用户正在寻找吴恩达机器学习课程中逻辑回归的源码,特别是GitHub或Python实现。首先,我需要回忆一下吴恩达的课程结构。记得他的课程有配套的编程作业,通常使用Octave/MATLAB,但后来社区可能有Python版本的实现。用户可能希望找到Python的代码,因为现在更多人用Python。 接下来,用户的需求是逻辑回归的源码。可能需要先确认课程中逻辑回归的部分在哪里,通常是在分类问题部分。然后,考虑用户可能遇到的问题,比如找不到官方Python代码,或者希望有第三方实现。可能需要引导用户去GitHub搜索相关关键词,比如“吴恩达 机器学习 逻辑回归 Python”,或者查看一些知名的机器学习仓库,比如scikit-learn的文档,但那里可能不是课程中的具体实现。 另外,用户可能希望代码的结构和课程中的讲解一致,比如使用梯度下降法,包含代价函数和梯度的计算。这时候,可能需要提供一个简单的示例代码,帮助用户理解逻辑回归的实现步骤,同时建议他们参考课程材料中的数学公式。 还需要注意引用中的信息,用户提供的引用3提到了线性回归的代码实现,可能类似的结构可以应用到逻辑回归上。因此,在回答中可以提到参考线性回归的实现方式,但调整损失函数和梯度计算部分。 另外,用户可能不知道如何验证自己的代码是否正确,所以建议他们使用公开数据集,比如鸢尾花数据集,或者课程中的练习数据。同时,提醒用户注意数据预处理,比如特征缩放和添加偏置项,这对逻辑回归的性能很重要。 最后,可能需要预见到用户后续的问题,比如逻辑回归的多分类扩展,或者正则化的应用,所以在相关问题里可以提前列出这些,帮助他们进一步学习。</think># 吴恩达机器学习》逻辑回归源码实现指引 根据课程内容和开源社区实践,逻辑回归的Python实现需要重点掌握假设函数、损失函数和梯度下降三个核心模块[^3]。以下是实现步骤和资源指引: ### 一、算法核心实现步骤 1. **Sigmoid函数** $$g(z) = \frac{1}{1 + e^{-z}}$$ 2. **代价函数** $$J(\theta) = -\frac{1}{m}\sum_{i=1}^m [y^{(i)}\log(h_\theta(x^{(i)})) + (1-y^{(i)})\log(1-h_\theta(x^{(i)}))]$$ 3. **梯度计算** $$\frac{\partial J(\theta)}{\partial \theta_j} = \frac{1}{m}\sum_{i=1}^m (h_\theta(x^{(i)}) - y^{(i)})x_j^{(i)}$$ ### 二、Python代码示例 ```python import numpy as np class LogisticRegression: def __init__(self, lr=0.01, num_iter=100000): self.lr = lr self.num_iter = num_iter def sigmoid(self, z): return 1 / (1 + np.exp(-z)) def fit(self, X, y): m, n = X.shape self.theta = np.zeros(n) for _ in range(self.num_iter): z = np.dot(X, self.theta) h = self.sigmoid(z) gradient = np.dot(X.T, (h - y)) / m self.theta -= self.lr * gradient def predict(self, X): return self.sigmoid(np.dot(X, self.theta)) >= 0.5 ``` ### 三、资源获取建议 1. **官方资源**:Coursera课程编程作业含MATLAB实现(可转换为Python) 2. **GitHub搜索建议**: - 使用关键词 `"Andrew Ng" logistic regression python` - 过滤含ex2/ex3的仓库(对应课程编程作业编号) 3. **第三方实现参考**: - 参考scikit-learn的LogisticRegression源码架构 - 推荐仓库:https://github.com/anantzoid/Coursera-Machine-Learning **注意事项**: - 数据预处理需添加偏置项(X = np.c_[np.ones((m,1)), X]) - 推荐使用鸢尾花数据集进行验证 - 正则化版本需修改损失函数项[^1]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值