自定义数据集 使用scikit-learn中svm的包实现svm分类

数据集生成:

  • 使用 make_classification 函数生成包含1000个样本的数据集,设置20个特征,其中10个是有信息的特征,类别数为2,通过设置 random_state = 42 保证每次运行生成的数据相同。

数据划分:

  • 使用 train_test_split 函数将生成的数据集划分为训练集和测试集,测试集占比为20%,同样通过 random_state = 42 保证划分的一致性。

SVM模型:

  • 初始化 SVC 类,这里使用线性核函数 kernel='linear' 。还有其他核函数可供选择,如 'rbf' (径向基函数核)、 'poly' (多项式核)等,不同的核函数适用于不同的数据分布。

  • 使用 fit 方法将模型拟合到训练集数据 X_train 和对应的标签 y_train 上。

预测与评估:

  • 使用训练好的模型对测试集 X_test 进行预测,得到预测标签 y_pred 。

  • 使用 accuracy_score 函数计算预测准确率,评估模型在测试集上的性能。

import numpy as np

from sklearn.datasets import make_classification

from sklearn.model_selection import train_test_split

from sklearn.svm import SVC

from sklearn.metrics import accuracy_score

生成自定义数据集

X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, n_classes=2, random_state=42)

划分训练集和测试集

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

初始化并拟合SVM模型

svm_classifier = SVC(kernel='linear')

svm_classifier.fit(X_train, y_train)

预测

y_pred = svm_classifier.predict(X_test)

计算准确率

accuracy = accuracy_score(y_test, y_pred)

print(f"Accuracy of SVM classifier: {accuracy}")

相关推荐
清风lsq17 小时前
大模型-解析vllm lora 模块
人工智能·vllm·大模型推理
alajl17 小时前
Hermes 源码阅读1
人工智能
碳基硅坊18 小时前
Mac Studio 部署 Qwen3.6-27B omlx & dflash 深度评测
人工智能·大模型部署·qwen3.6-27b
cci18 小时前
Moveit2 安装
人工智能
cci18 小时前
Moveit2 快速入门
人工智能
俊哥V18 小时前
每日 AI 研究简报 · 2026-05-28
人工智能·ai
wabs66618 小时前
本科毕业设计项目——基于RAG与大语言模型的408问答系统设计与实现【检索与生成功能的第三步答案生成是怎么实现的?】
人工智能·语言模型·自然语言处理
geneculture18 小时前
从“巴别塔”到“耶路撒冷”:融智学应对AI时代治理困境的系统方案
大数据·人工智能·融智学的重要应用·哲学与科学统一性·融智时代(杂志)·人际间性·人机间性
Engineer邓祥浩18 小时前
宏观认知(1):AI 是什么——吴恩达《AI for Everyone》Week1 学习笔记
人工智能·笔记·学习
小程故事多_8018 小时前
深入解析FlashAttention,大模型长序列训练的底层优化核心技术
人工智能·transformer