Hướng dẫn plotting logistic regression in python - vẽ hồi quy logistic trong python


Bạn có thể sử dụng hàm regplot () từ thư viện trực quan hóa dữ liệu seeborn để vẽ đường cong hồi quy logistic trong Python:

import seaborn as sns

sns.regplot(x=x, y=y, data=df, logistic=True, ci=None)

Ví dụ sau đây cho thấy cách sử dụng cú pháp này trong thực tế.

Ví dụ: Vẽ một đường cong hồi quy logistic trong Python

Đối với ví dụ này, chúng tôi sẽ sử dụng & NBSP; Bộ dữ liệu mặc định từ phần giới thiệu về Sách học tập thống kê. Chúng ta có thể sử dụng mã sau để tải và xem tóm tắt của bộ dữ liệu:Default dataset from the Introduction to Statistical Learning book. We can use the following code to load and view a summary of the dataset:

#import dataset from CSV file on Github
url = "https://raw.githubusercontent.com/Statology/Python-Guides/main/default.csv"
data = pd.read_csv(url)

#view first six rows of dataset
data[0:6]

        default	student	balance	        income
0	0	0	729.526495	44361.625074
1	0	1	817.180407	12106.134700
2	0	0	1073.549164	31767.138947
3	0	0	529.250605	35704.493935
4	0	0	785.655883	38463.495879
5	0	1	919.588530	7491.558572  

Bộ dữ liệu này chứa các thông tin sau về 10.000 cá nhân:

  • Mặc định: Cho biết liệu một cá nhân có mặc định hay không. Indicates whether or not an individual defaulted.
  • Học sinh: Cho biết liệu một cá nhân có phải là sinh viên hay không. Indicates whether or not an individual is a student.
  • Cân bằng: Số dư trung bình được mang bởi một cá nhân. Average balance carried by an individual.
  • Thu nhập: Thu nhập của cá nhân. Income of the individual.

Giả sử chúng ta muốn xây dựng một mô hình hồi quy logistic sử dụng cân bằng của người dùng để dự đoán xác suất mà một mặc định cá nhân nhất định.

Chúng ta có thể sử dụng mã sau để vẽ đường cong hồi quy logistic:

#define the predictor variable and the response variable
x = data['balance']
y = data['default']

#plot logistic regression curve
sns.regplot(x=x, y=y, data=data, logistic=True, ci=None)

Hướng dẫn plotting logistic regression in python - vẽ hồi quy logistic trong python

Trục X hiển thị các giá trị của biến dự đoán Biến số dư và trục y hiển thị xác suất dự đoán của mặc định.

Chúng ta có thể thấy rõ rằng các giá trị cân bằng cao hơn được liên kết với xác suất cao hơn mà một mặc định riêng lẻ.

Lưu ý rằng bạn cũng có thể sử dụng scatter_kws và line_kws để sửa đổi màu sắc của các điểm và đường cong trong lô:scatter_kws and line_kws to modify the colors of the points and the curve in the plot:

#define the predictor variable and the response variable
x = data['balance']
y = data['default']

#plot logistic regression curve with black points and red line
sns.regplot(x=x, y=y, data=data, logistic=True, ci=None),
            scatter_kws={'color': 'black'}, line_kws={'color': 'red'})

Hướng dẫn plotting logistic regression in python - vẽ hồi quy logistic trong python

Hãy thoải mái chọn bất kỳ màu nào bạn thích trong cốt truyện.

Tài nguyên bổ sung

Các hướng dẫn sau đây cung cấp thông tin bổ sung về hồi quy logistic:

Giới thiệu về hồi quy logistic Cách báo cáo kết quả hồi quy logistic Cách thực hiện hồi quy logistic trong Python (từng bước)
How to Report Logistic Regression Results
How to Perform Logistic Regression in Python (Step-by-Step)

Ghi chú

Nhấn vào đây để tải xuống mã ví dụ đầy đủ hoặc để chạy ví dụ này trong trình duyệt của bạn thông qua Binderhere to download the full example code or to run this example in your browser via Binder

Thể hiện trong cốt truyện là cách hồi quy logistic, trong bộ dữ liệu tổng hợp này, phân loại các giá trị là 0 hoặc 1, tức là lớp một hoặc hai, sử dụng đường cong logistic.

Hướng dẫn plotting logistic regression in python - vẽ hồi quy logistic trong python

# Code source: Gael Varoquaux
# License: BSD 3 clause

import numpy as np
import matplotlib.pyplot as plt

from sklearn.linear_model import LogisticRegression, LinearRegression
from scipy.special import expit

# Generate a toy dataset, it's just a straight line with some Gaussian noise:
xmin, xmax = -5, 5
n_samples = 100
np.random.seed(0)
X = np.random.normal(size=n_samples)
y = (X > 0).astype(float)
X[X > 0] *= 4
X += 0.3 * np.random.normal(size=n_samples)

X = X[:, np.newaxis]

# Fit the classifier
clf = LogisticRegression(C=1e5)
clf.fit(X, y)

# and plot the result
plt.figure(1, figsize=(4, 3))
plt.clf()
plt.scatter(X.ravel(), y, color="black", zorder=20)
X_test = np.linspace(-5, 10, 300)

loss = expit(X_test * clf.coef_ + clf.intercept_).ravel()
plt.plot(X_test, loss, color="red", linewidth=3)

ols = LinearRegression()
ols.fit(X, y)
plt.plot(X_test, ols.coef_ * X_test + ols.intercept_, linewidth=1)
plt.axhline(0.5, color=".5")

plt.ylabel("y")
plt.xlabel("X")
plt.xticks(range(-5, 10))
plt.yticks([0, 0.5, 1])
plt.ylim(-0.25, 1.25)
plt.xlim(-4, 10)
plt.legend(
    ("Logistic Regression Model", "Linear Regression Model"),
    loc="lower right",
    fontsize="small",
)
plt.tight_layout()
plt.show()

Tổng thời gian chạy của tập lệnh: (0 phút 0,070 giây) ( 0 minutes 0.070 seconds)

Phòng trưng bày được tạo ra bởi Sphinx-Gallery