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()

运行效果图

相关推荐
duyinbi75171 分钟前
感受野坐标注意力卷积改进YOLOv26双向空间加权与自适应通道建模协同突破
人工智能·yolo·目标跟踪
炎爆的土豆翔3 分钟前
bitwise_not`性能测试:手写普通循环、AVX2 与 OpenCV 内置实现对比
人工智能·opencv·webpack
INDEMIND6 分钟前
牵手海尔、TCL,INDEMIND家用具身陪伴机器人AI平台加速家庭AI陪伴落地
人工智能·机器人·陪伴机器人
wheelmouse77887 分钟前
AI 时代的 Git 进阶术:如何优雅地让多个 Agent 并行开发
人工智能·git·ai编程
輕華7 分钟前
矿物成分数据智能分类实战(三):以平均值填充数据集的pytorch框架和MLP算法实现与性能分析
pytorch·分类·数据挖掘
ZPC821010 分钟前
PPO (Proximal Policy Optimization) 算法模块详细拆解
人工智能·pytorch·算法·机器人
仙女修炼史11 分钟前
FCOS: Fully Convolutional One-Stage Object Detection
人工智能·目标检测·目标跟踪
大傻^13 分钟前
Spring AI Alibaba 多模态开发:集成视觉理解与视频分析能力
人工智能·spring·音视频·springai·springaialibaba·混合检索
前端摸鱼匠15 分钟前
面试题3:自注意力机制(Self-Attention)的计算流程是什么?
人工智能·ai·面试·职场和发展
wertyuytrewm18 分钟前
用Python实现自动化的Web测试(Selenium)
jvm·数据库·python