逻辑回归python实现
时间: 2024-06-16 16:02:23 浏览: 107
逻辑回归是一种常用的二分类模型,它基于概率论和最大似然估计来预测离散的结果。在Python中,可以使用Scikit-learn库方便地实现逻辑回归。以下是基本的步骤:
1. 导入所需的库:
```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, confusion_matrix
```
2. 加载数据并预处理:
```python
# 假设你有一个名为df的数据框,包含特征(X)和标签(y)
X = df.drop('target', axis=1)
y = df['target']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 数据标准化(可选,提高模型性能)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
3. 创建并训练逻辑回归模型:
```python
model = LogisticRegression(random_state=42)
model.fit(X_train, y_train)
```
4. 预测和评估:
```python
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
conf_mat = confusion_matrix(y_test, y_pred)
print(f"Accuracy: {accuracy}")
print("Confusion Matrix:")
print(conf_mat)
```
阅读全文