Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Logistic Regression

Logistic Regression

Logistic Regression is a statistical learning method widely used for classification problems. Although its name contains "regression", it is actually an algorithm used for binary or multi-class classification problems.

Logistic Regression maps the output of linear regression to between 0 and 1 by using the logistic function (also called the Sigmoid function), thereby predicting the probability of a certain event occurring.

Logistic Regression is widely used in various classification problems, for example:

The Logistic Regression Model

Loss function

The loss function of Logistic Regression is the Log Loss function, whose form is as follows:

Solving with Gradient Descent

Like linear regression, Logistic Regression typically uses gradient descent to optimize the loss function and solve for the parameters w and b. The gradient update rules for Logistic Regression are as follows:

By continuously updating w and b until the loss function converges.


Implementing Logistic Regression in Python

Next, we will use Python and the Scikit-learn library to implement a simple Logistic Regression model.

1. Import the Necessary Libraries

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

linear_model

import

LogisticRegression

from

sklearn.

metrics

import

accuracy_score

,

confusion_matrix

,

classification_report

2. Load the Dataset

We will use the Iris dataset that comes with Scikit-learn. The Iris dataset contains 150 samples, each with 4 features, and the goal is to classify the samples into 3 categories. To simplify the problem, we will use only the first two features and transform the problem into a binary classification problem.

Example

Load the dataset

iris

=

load_iris

(

)

X

=

iris.

data

[

:

,

:

2

]

 

Use only the first two features

y

=

(

iris.

target

!=

0

)

1

 

Transform the target into a binary classification problem

Split into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

3. Train the Logistic Regression Model

Example

Create the logistic regression model

model

=

LogisticRegression

(

)

Train the model

model.

fit

(

X_train

,

y_train

)

4. Model Evaluation

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

linear_model

import

LogisticRegression

from

sklearn.

metrics

import

accuracy_score

,

confusion_matrix

,

classification_report

Load the dataset

iris

=

load_iris

(

)

X

=

iris.

data

[

:

,

:

2

]

 

Use only the first two features

y

=

(

iris.

target

!=

0

)

1

 

Transform the target into a binary classification problem

Split into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

Create the logistic regression model

model

=

LogisticRegression

(

)

Train the model

model.

fit

(

X_train

,

y_train

)

Predict on the test set

y_pred

=

model.

predict

(

X_test

)

Compute accuracy

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

print

(

f

"Model Accuracy: {accuracy:.2f}"

)

Confusion matrix

conf_matrix

=

confusion_matrix

(

y_test

,

y_pred

)

print

(

"Confusion matrix:"

)

print

(

conf_matrix

)

Classification report

class_report

=

classification_report

(

y_test

,

y_pred

)

print

(

"Classification report:"

)

print

(

class_report

)

The output is:

模型准确率: 1.00

Confusion matrix:

[[19  0]

 [ 0 26]]

Classification Report:

              precision    recall  f1-score   support



           0       1.00      1.00      1.00        19

           1       1.00      1.00      1.00        26



    accuracy                           1.00        45

   macro avg       1.00      1.00      1.00        45

weighted avg       1.00      1.00      1.00        45

5. Visualize the Decision Boundary

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

linear_model

import

LogisticRegression

from

sklearn.

metrics

import

accuracy_score

,

confusion_matrix

,

classification_report

Load the dataset

iris

=

load_iris

(

)

X

=

iris.

data

[

:

,

:

2

]

 

Use only the first two features

y

=

(

iris.

target

!=

0

)

1

 

Transform the target into a binary classification problem

Split into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

Create the logistic regression model

model

=

LogisticRegression

(

)

Train the model

model.

fit

(

X_train

,

y_train

)

Predict on the test set

y_pred

=

model.

predict

(

X_test

)

Visualize the decision boundary

x_min

,

x_max

=

X

[

:

,

0

]

.

min

(

)

1

,

X

[

:

,

0

]

.

max

(

)

1

y_min

,

y_max

=

X

[

:

,

1

]

.

min

(

)

1

,

X

[

:

,

1

]

.

max

(

)

1

xx

,

yy

=

np.

meshgrid

(

np.

arange

(

x_min

,

x_max

,

0.01

)

,

                     np.

arange

(

y_min

,

y_max

,

0.01

)

)

Z

=

model.

predict

(

np.

c_

[

xx.

ravel

(

)

,

yy.

ravel

(

)

]

)

Z

=

Z.

reshape

(

xx.

shape

)

plt.

contourf

(

xx

,

yy

,

Z

,

alpha

=

0.8

)

plt.

scatter

(

X

[

:

,

0

]

,

X

[

:

,

1

]

,

c

=

y

,

edgecolors

=

'k'

,

marker

=

'o'

)

plt.

xlabel

(

'Sepal length'

)

plt.

ylabel

(

'Sepal width'

)

plt.

title

(

'Logistic Regression Decision Boundary'

)

plt.

show

(

)

The display is as follows:

Summary

w w w and bb b. - The `scikit-learn` library in Python provides a simple and easy-to-use interface for implementing Logistic Regression, and allows for easy model training, evaluation, and visualization.