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 分钟前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
算家计算12 分钟前
马斯克突然裁掉500名AI训练师!重心转向招募专业领域AI导师
人工智能·资讯·grok
什么都想学的阿超14 分钟前
【大语言模型 58】分布式文件系统:训练数据高效存储
人工智能·语言模型·自然语言处理
ViperL129 分钟前
[智能算法]可微的神经网络搜索算法-FBNet
人工智能·深度学习·神经网络
新智元29 分钟前
马斯克深夜挥刀,Grok 幕后员工 1/3 失业!谷歌 AI 靠人肉堆起,血汗工厂曝光
人工智能·openai
带娃的IT创业者29 分钟前
Windows 平台上基于 MCP 构建“文心一言+彩云天气”服务实战
人工智能·windows·文心一言·mcp
Dxy12393102161 小时前
python把文件从一个文件复制到另一个文件夹
开发语言·python
金井PRATHAMA1 小时前
认知语义学隐喻理论对人工智能自然语言处理中深层语义分析的赋能与挑战
人工智能·自然语言处理·知识图谱
J_Xiong01171 小时前
【VLMs篇】07:Open-Qwen2VL:在学术资源上对完全开放的多模态大语言模型进行计算高效的预训练
人工智能·语言模型·自然语言处理