matlab逻辑回归代码
时间: 2023-10-13 20:07:51 浏览: 93
在MATLAB中,可以使用以下代码实现逻辑回归:
```matlab
% 步骤1:准备数据
X = [x1, x2, x3, ...]; % 输入特征矩阵
y = [y1, y2, y3, ...]; % 标签向量
% 步骤2:初始化参数
theta = zeros(size(X, 2), 1); % 参数向量
% 步骤3:定义假设函数和Sigmoid函数
function h = hypothesis(X, theta)
h = 1 ./ (1 + exp(-X * theta));
end
% 步骤4:定义损失函数
function J = costFunction(X, y, theta)
m = length(y);
h = hypothesis(X, theta);
J = (1 / m) * sum(-y .* log(h) - (1 - y) .* log(1 - h));
end
% 步骤5:定义梯度下降函数
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y);
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
h = hypothesis(X, theta);
theta = theta - (alpha / m) * X' * (h - y);
J_history(iter) = costFunction(X, y, theta);
end
end
% 步骤6:调用梯度下降函数进行训练
alpha = 0.01; % 学习率
num_iters = 1000; % 迭代次数
[theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters);
% 步骤7:预测新样本
function prediction = predict(X, theta)
h = hypothesis(X, theta);
prediction = h >= 0.5;
end
% 示例调用
new_data = [new_x1, new_x2, new_x3, ...]; % 新样本
prediction = predict(new_data, theta); % 预测结果
% 绘制损失函数曲线
plot(1:num_iters, J_history);
xlabel('迭代次数');
ylabel('损失函数值');
```
阅读全文