自定义数据集 使用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}")

相关推荐
机器人零零壹1 小时前
技术白皮书:iRobotCAM如何解决机器人激光切割应用中的核心难点,从CAD离线编程到双目视觉定位与轨迹自适应提升复杂空间曲线切割的精度、效率与柔性化水平
人工智能·算法
电子元件小说家2 小时前
2026年四季度电感市场观察:AI算力与汽车电子驱动下的选型与验证建议智能硬件
人工智能·汽车
网易CodeWave-小码哥2 小时前
支持多模块 Java 微服务导入|CodeWave SDD V4.5.10 上线
人工智能
AI你一生一世2 小时前
不止于时序存储:DolphinDB 如何成为 AI 时代的工业智能底座
java·人工智能·struts·时序数据库·工业智能·dolphindb·ai基础设施
belldeep2 小时前
python:genesis-world, Genesis-Embodied-AI
人工智能·python·ai·genesis
怕浪猫3 小时前
小程序成长计划上新:10 亿 Token 现在能调 DeepSeek-v4.1-flash了
人工智能·aigc·ai编程
ss2733 小时前
为什么PostgreSQL适合AI场景?
数据库·人工智能·postgresql
七牛云行业应用4 小时前
DeepSeek Super-agent 与 Grok Bot:开源 Agent 架构和聊天助手有何区别
人工智能·ai·架构·ai编程
维克兜率天4 小时前
【维克】趋势型CTA:期货市场的“追涨杀跌“
人工智能·python
u1301304 小时前
GitHub 热榜项目:日榜(2026-11-03)
人工智能·github