matlab中logistic模型代码
时间: 2023-04-20 09:03:38 浏览: 111
数学建模Logistic模型Matlab代码[通过logistic回归分析,可以得到自变量的权重]
5星 · 资源好评率100%
以下是一个简单的 MATLAB 代码实现逻辑回归模型:
% 加载数据
data = load('data.txt');
X = data(:, 1:2);
y = data(:, 3);
% 初始化参数
[m, n] = size(X);
X = [ones(m, 1) X];
initial_theta = zeros(n + 1, 1);
% 定义代价函数
function [J, grad] = costFunction(theta, X, y)
m = length(y);
J = ;
grad = zeros(size(theta));
h = sigmoid(X * theta);
J = (-1 / m) * sum(y .* log(h) + (1 - y) .* log(1 - h));
grad = (1 / m) * X' * (h - y);
end
% 定义 sigmoid 函数
function g = sigmoid(z)
g = 1 ./ (1 + exp(-z));
end
% 使用 fminunc 函数进行优化
options = optimset('GradObj', 'on', 'MaxIter', 400);
[theta, cost] = fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);
% 绘制决策边界
plotData(X(:, 2:3), y);
hold on;
if size(X, 2) <= 3
plot_x = [min(X(:, 2))-2, max(X(:, 2))+2];
plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));
plot(plot_x, plot_y)
legend('Admitted', 'Not admitted', 'Decision Boundary')
axis([30, 100, 30, 100])
else
u = linspace(-1, 1.5, 50);
v = linspace(-1, 1.5, 50);
z = zeros(length(u), length(v));
for i = 1:length(u)
for j = 1:length(v)
z(i,j) = mapFeature(u(i), v(j))*theta;
end
end
z = z';
contour(u, v, z, [, ], 'LineWidth', 2)
end
hold off;
% 预测新数据
prob = sigmoid([1 45 85] * theta);
fprintf('For a student with scores 45 and 85, we predict an admission probability of %f\n', prob);
阅读全文