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

运行效果图

相关推荐
方见华Richard39 分钟前
世毫九量子原住民教育理念全书
人工智能·经验分享·交互·原型模式·空间计算
忆~遂愿40 分钟前
GE 引擎进阶:依赖图的原子性管理与异构算子协作调度
java·开发语言·人工智能
凯子坚持 c40 分钟前
CANN-LLM:基于昇腾 CANN 的高性能、全功能 LLM 推理引擎
人工智能·安全
MZ_ZXD00144 分钟前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·vue.js·spring boot·python·django·php
学电子她就能回来吗1 小时前
深度学习速成:损失函数与反向传播
人工智能·深度学习·学习·计算机视觉·github
The Straggling Crow1 小时前
model training platform
人工智能
爱吃泡芙的小白白1 小时前
突破传统:CNN卷积层(普通/空洞)核心技术演进与实战指南
人工智能·神经网络·cnn·卷积层·空洞卷积·普通卷积
人道领域1 小时前
AI抢人大战:谁在收割你的红包
大数据·人工智能·算法
初恋叫萱萱1 小时前
CANN 系列深度篇:基于 ge 图引擎构建高效 AI 执行图
人工智能
qq_12498707531 小时前
基于Hadoop的信贷风险评估的数据可视化分析与预测系统的设计与实现(源码+论文+部署+安装)
大数据·人工智能·hadoop·分布式·信息可视化·毕业设计·计算机毕业设计