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

运行效果图

相关推荐
Jamence8 分钟前
多模态大语言模型arxiv论文略读(八十九)
论文阅读·人工智能·语言模型·自然语言处理·论文笔记
AI technophile39 分钟前
OpenCV计算机视觉实战(7)——色彩空间详解
人工智能·opencv·计算机视觉
绝顶大聪明41 分钟前
[欠拟合过拟合]机器学习-part10
人工智能·机器学习
芷栀夏1 小时前
Dify大语言模型应用开发环境搭建:打造个性化本地LLM应用开发工作台
人工智能·语言模型·自然语言处理
星辰生活说1 小时前
零碳办会新范式!第十届国际贸易发展论坛——生物能源和可持续发展专场,在京举办
大数据·人工智能·能源
寰宇视讯1 小时前
第 25 届中国全电展即将启幕,构建闭环能源生态系统推动全球能源转型
大数据·人工智能·能源
百锦再1 小时前
微信小程序学习基础:从入门到精通
前端·vue.js·python·学习·微信小程序·小程序·pdf
Icoolkj1 小时前
谷歌 AI Ultra:开启人工智能新时代
人工智能
白熊1881 小时前
【机器学习基础】机器学习入门核心算法:线性回归(Linear Regression)
人工智能·算法·机器学习·回归·线性回归
PWRJOY1 小时前
Flask 路由跳转机制:url_for生成动态URL、redirect页面重定向
后端·python·flask