逻辑回归代码matlab
时间: 2023-09-20 08:03:46 浏览: 62
Sure! Here's an example of logistic regression code in MATLAB:
```matlab
% Load your dataset
load('dataset.mat'); % Replace with your dataset
% Extract features and labels from the dataset
X = dataset(:, 1:end-1); % Features
y = dataset(:, end); % Labels
% Set initial parameters
m = size(X, 1); % Number of training examples
n = size(X, 2); % Number of features
theta = zeros(n+1, 1); % Initialize parameters
% Add intercept term (bias) to X
X = [ones(m, 1), X];
% Define sigmoid function
sigmoid = @(z) 1 ./ (1 + exp(-z));
% Define cost function
cost = @(theta) (-1/m) * sum(y .* log(sigmoid(X*theta)) + (1-y) .* log(1 - sigmoid(X*theta)));
% Define gradient function
gradient = @(theta) (1/m) * X' * (sigmoid(X*theta) - y);
% Set optimization options
options = optimset('GradObj', 'on', 'MaxIter', 100);
% Run logistic regression using fminunc function
[theta, cost] = fminunc(cost, theta, options);
% Display the optimized parameters
disp('Optimized Theta:');
disp(theta);
% Predict the labels for new examples
new_X = [ones(size(new_examples, 1), 1), new_examples]; % Replace with new examples
predictions = sigmoid(new_X * theta);
% Display the predictions
disp('Predictions:');
disp(predictions);
```
Please note that you need to replace 'dataset.mat' with the path to your own dataset file, and 'new_examples' with the input for which you want to make predictions.