python 逻辑回归 sklearn
时间: 2025-05-24 21:59:48 浏览: 12
### 使用 Python 和 sklearn 库实现逻辑回归
#### 示例代码
以下是基于 `sklearn` 的逻辑回归实现示例:
```python
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import matplotlib.pyplot as plt
# 1. 数据生成
X, y = make_classification(n_samples=1000, n_features=20, n_informative=2,
n_redundant=10, n_classes=2, random_state=42)
# 2. 数据划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 3. 创建并训练模型
model = LogisticRegression(max_iter=1000, solver='liblinear')
model.fit(X_train, y_train)
# 4. 预测
y_pred = model.predict(X_test)
# 5. 性能评估
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)
print(f"Accuracy: {accuracy:.4f}")
print("Confusion Matrix:")
print(conf_matrix)
print("Classification Report:")
print(class_report)
# 6. 可视化决策边界(仅适用于二维数据)
if X.shape[1] == 2:
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.02),
np.arange(y_min, y_max, 0.02))
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', s=20)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Decision Boundary of Logistic Regression')
plt.show()
```
---
#### 参数解释
- **n_samples**: 表示生成的数据集中样本的数量[^4]。
- **n_features**: 表示每个样本的特征数量[^4]。
- **n_informative**: 表示具有信息量的有效特征数,其余特征可能是冗余或噪声。
- **test_size**: 划分测试集的比例,默认为 0.25。此处设置为 0.3,表示将 30% 的数据用于测试[^2]。
- **solver**: 指定优化算法。常用选项有 `'lbfgs'`, `'liblinear'`, `'newton-cg'`, `'sag'`, `'saga'` 等。对于小型数据集推荐使用 `'liblinear'`,而对于大型数据集则可以选择 `'sag'` 或 `'saga'`[^3]。
- **max_iter**: 设置迭代的最大次数。如果收敛速度较慢,可能需要增加该参数值[^3]。
---
#### 注意事项
- 如果数据维度较高,则无法直观地绘制决策边界图表。此时可以通过降维技术(如 PCA)降低到两维后再进行可视化。
- 默认情况下,`LogisticRegression` 类会应用 L2 正则化项。如果不希望启用正则化,可将参数 `penalty` 设为 `'none'`。
---
阅读全文
相关推荐




















