创建虚拟数据集,使得数据集不能线性可分,分别使用Hard Voting和Soft Voting来进行分类, 要求总结两者之间的区别。

代码:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

# 生成非线性可分的数据集(月亮形状)
X, y = make_moons(n_samples=1000, noise=0.3, random_state=42)

# 可视化生成的数据集
plt.figure(figsize=(8, 6))
plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='red', label='Class 0')
plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='blue', label='Class 1')
plt.title('Generated Non-linearly Separable Dataset')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.show()

# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import VotingClassifier

# 初始化基分类器
clf1 = RandomForestClassifier(random_state=42)
clf2 = SVC(random_state=42, probability=True)
clf3 = LogisticRegression(random_state=42)

# 使用 Hard Voting 进行分类
voting_clf_hard = VotingClassifier(estimators=[('rf', clf1), ('svm', clf2), ('lr', clf3)], voting='hard')
voting_clf_hard.fit(X_train, y_train)

# 计算 Hard Voting 在测试集上的准确率
hard_voting_accuracy = voting_clf_hard.score(X_test, y_test)
print("Hard Voting Accuracy:", hard_voting_accuracy)

# 使用 Soft Voting 进行分类
voting_clf_soft = VotingClassifier(estimators=[('rf', clf1), ('svm', clf2), ('lr', clf3)], voting='soft')
voting_clf_soft.fit(X_train, y_train)

# 计算 Soft Voting 在测试集上的准确率
soft_voting_accuracy = voting_clf_soft.score(X_test, y_test)
print("Soft Voting Accuracy:", soft_voting_accuracy)

结果:


  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值