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

运行效果图

相关推荐
秋邱9 分钟前
AR 应用流量增长与品牌 IP 打造:从被动接单到主动获客
开发语言·人工智能·后端·python·ar·restful
AI_Auto7 小时前
智能制造 - 人工智能、隐私保护、信息安全
人工智能·制造
yLDeveloper7 小时前
一只菜鸟学深度学习的日记:入门卷积
机器学习·dive into deep learning
一只乔哇噻7 小时前
java后端工程师+AI大模型开发进修ing(研一版‖day60)
java·开发语言·人工智能·学习·语言模型
千里码aicood7 小时前
计算机大数据、人工智能与智能系统开发定制开发
大数据·人工智能·深度学习·决策树·机器学习·森林树
币圈菜头8 小时前
【空投速递】GAEA项目解析:首个集成人类情感数据的去中心化AI训练网络
人工智能·web3·去中心化·区块链
ID_180079054739 小时前
基于 Python 的 Cdiscount 商品详情 API 调用与 JSON 核心字段解析(含多规格 SKU 提取)
开发语言·python·json
Dcs9 小时前
你的 Prompt 都该重写?
人工智能·ai编程
木卫二号Coding9 小时前
第五十三篇-Ollama+V100+Qwen3:4B-性能
人工智能
飞哥数智坊9 小时前
AI 不只是聊天:聊聊我最近在做的新方向
人工智能