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

运行效果图

相关推荐
电棍2331 小时前
工程记录:使用tello edu无人机进行计算机视觉工作(手势识别,yolo3搭载)
人工智能·计算机视觉·无人机
wan5555cn1 小时前
国产电脑操作系统与硬盘兼容性现状分析:挑战与前景评估
人工智能·笔记·深度学习·机器学习·电脑·生活
派森先生1 小时前
sk08.【scikit-learn基础】--『监督学习』之K近邻算法
学习·scikit-learn·近邻算法
BullSmall2 小时前
汽车HIL测试:电子开发的关键验证环节
人工智能·机器学习·自动驾驶
woshihonghonga2 小时前
停止Conda开机自动运行方法
linux·人工智能·conda
海洲探索-Hydrovo4 小时前
TTP Aether X 天通透传模块丨国产自主可控大数据双向通讯定位模组
网络·人工智能·科技·算法·信息与通信
触想工业平板电脑一体机4 小时前
【触想智能】工业安卓一体机在人工智能领域上的市场应用分析
android·人工智能·智能电视
Bellafu6665 小时前
selenium常用的等待有哪些?
python·selenium·测试工具
墨染天姬6 小时前
【AI】数学基础之矩阵
人工智能·线性代数·矩阵
小白学大数据6 小时前
Python爬虫常见陷阱:Ajax动态生成内容的URL去重与数据拼接
爬虫·python·ajax