sklearn分类场景案例01

python 复制代码
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.pipeline import make_pipeline

# 1. 加载数据
iris = datasets.load_iris()
X = iris.data[:, :2]  # 只取前两个特征便于可视化
y = iris.target

# 2. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42
)

# 3. 创建模型管道(预处理+分类器)
model = make_pipeline(
    StandardScaler(),  # 特征标准化
    SVC(kernel='rbf', gamma='auto')  # 使用SVM分类器
)

# 4. 训练模型
model.fit(X_train, y_train)

# 5. 预测与评估
y_pred = model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}")
print("Classification Report:\n", classification_report(y_test, y_pred))

# 6. 可视化决策边界
plt.figure(figsize=(10, 6))
h = 0.02  # 网格步长
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, h), np.arange(y_min, y_max, h))

Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3)

# 绘制训练点
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, edgecolors='k', label='Train')
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, marker='x', label='Test')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.title('SVM Classification on Iris Dataset')
plt.legend()
plt.show()

运行效果图

相关推荐
ZKNOW甄知科技几秒前
重构企业运维智慧:低代码 ITSM 知识管理平台的创新与实践
大数据·运维·人工智能·程序人生·低代码·重构·it
金融小师妹3 分钟前
基于多源政策信号解析与量化因子的“12月降息预期降温”重构及黄金敏感性分析
人工智能·深度学习·1024程序员节
北邮刘老师10 分钟前
智能家居,需要的是“主控智能体”而不是“主控节点”
人工智能·算法·机器学习·智能体·智能体互联网
nvd1112 分钟前
Python 迭代器 (Iterator) vs. 生成器 (Generator)
开发语言·python
盼小辉丶14 分钟前
PyTorch实战(10)——从零开始实现GPT模型
人工智能·pytorch·gpt·深度学习
老罗-Mason33 分钟前
Apache Flink运行环境搭建
python·flink·apache
mit6.82433 分钟前
[AI tradingOS] AI自动交易器 | 绩效追踪与日志
人工智能·区块链
AAA阿giao42 分钟前
用 AI 工程师 Trae Solo ,一个人打造“绘本岛”:从想法到上线只需三步
人工智能·全栈·trae
Blossom.1181 小时前
大模型量化压缩实战:从FP16到INT4的生产级精度保持之路
开发语言·人工智能·python·深度学习·神经网络·目标检测·机器学习
K2_BPM1 小时前
打通 AI 与业务的 “最后一公里”:流程优化的底层逻辑与三种战略选择
人工智能·机器学习