python 两种分类算法的组合 可视化代码
时间: 2023-07-05 11:10:08 浏览: 79
算法的可视化
以下是使用Python编写的将两种分类算法组合并可视化的示例代码:
```python
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import VotingClassifier
import matplotlib.pyplot as plt
# 创建模拟数据集
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_classes=2, random_state=42)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义两种分类器
clf1 = LogisticRegression(random_state=42)
clf2 = DecisionTreeClassifier(random_state=42)
# 定义投票分类器
voting_clf = VotingClassifier(estimators=[('lr', clf1), ('dt', clf2)], voting='hard')
# 训练模型
for clf in (clf1, clf2, voting_clf):
clf.fit(X_train, y_train)
# 可视化分类结果
fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, s=50, cmap='coolwarm', alpha=0.7)
ax.set_title('Classification Results')
ax.set_xlabel('Feature 1')
ax.set_ylabel('Feature 2')
plt.show()
```
这段代码使用`make_classification`函数生成一个模拟数据集,并将其划分为训练集和测试集。然后定义了两种分类器(逻辑回归和决策树),将它们放入投票分类器中进行训练。最后,使用可视化库matplotlib将分类结果可视化。
阅读全文