自定义数据集 使用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 小时前
Reflexion对ReAct的改进
人工智能
量化交易曾小健(金融号)1 小时前
GPT-5 Instant能修补模型情商漏洞了
人工智能
听到微笑1 小时前
LLM 只会生成文本?用 ReAct 模式手搓一个简易 Claude Code Agent
人工智能·langchain·llm
沐雪架构师1 小时前
让 Agent 说“机器能懂的话”——LlamaIndex 构建 Agent 的结构化输出策略
人工智能
Elastic 中国社区官方博客1 小时前
在 Elasticsearch 中改进 Agentic AI 工具的实验
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
AI数据皮皮侠2 小时前
中国地级市旅游人数、收入数据(2000-2023年)
大数据·人工智能·python·深度学习·机器学习·旅游
mooooon L2 小时前
DAY 43 复习日-2025.10.7
人工智能·pytorch·python·深度学习·神经网络
zzywxc7872 小时前
AI 在金融、医疗、教育、制造业等领域都有广泛且深入的应用,以下是这些领域的一些落地案例
人工智能·金融·自动化·prompt·ai编程·xcode
你的大佬9992 小时前
阿里云百炼ai模型
人工智能·阿里云·云计算
koo3642 小时前
李宏毅机器学习笔记16
人工智能·笔记·机器学习