【Python机器学习】SVM——预处理数据

为了解决特征特征数量级差异过大,导致的模型过拟合问题,有一种方法就是对每个特征进行缩放,使其大致处于同一范围。核SVM常用的缩放方法是将所有的特征缩放到0和1之间。

"人工"处理方法:

python 复制代码
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
cancer=load_breast_cancer()
X_train,X_test,y_train,y_test=train_test_split(cancer.data,cancer.target,random_state=0)

#计算训练集中每个特征的最小值
min_on_train=X_train.min(axis=0)
#计算训练集中每个特征的范围(最小值-最大值)
range_on_train=(X_train-min_on_train).max(axis=0)
#减去最小值,然后除以范围,这样最大值都是1,最小值都是0
X_train_scales=(X_train-min_on_train)/range_on_train

print('每个特征的最小值:{}'.format(X_train_scales.min(axis=0)))
print('每个特征的最大值:{}'.format(X_train_scales.max(axis=0)))

X_test_scales=(X_test-min_on_train)/range_on_train

svc=SVC(C=1,gamma=1)
svc.fit(X_train_scales,y_train)
print('训练集精度:{:.3f}'.format(svc.score(X_train_scales,y_train)))
print('测试集精度:{:.3f}'.format(svc.score(X_test_scales,y_test)))

可以看到,最终的结果上训练集和测试集的精度都非常好,但还没有接近100%的精度,可能存在欠拟合,后续可以通过调整C参数来继续优化。

相关推荐
Albert Edison35 分钟前
【Python】学生管理系统
开发语言·数据库·python
love530love3 小时前
【ComfyUI】解决 ModuleNotFoundError: No module named ‘inference_core_nodes‘ 问题
人工智能·windows·python·comfyui·inference-core
大模型任我行3 小时前
华为:构建特征级LLM编码评测基准
人工智能·语言模型·自然语言处理·论文笔记
Jason_Honey23 小时前
【平安Agent算法岗面试-二面】
人工智能·算法·面试
Godspeed Zhao3 小时前
现代智能汽车中的无线技术106——ETC(0)
网络·人工智能·汽车
恋猫de小郭3 小时前
AGENTS.md 真的对 AI Coding 有用吗?或许在此之前你没用对?
前端·人工智能·ai编程
久邦科技4 小时前
OpenCode 完整入门(安装 + 配置 + 使用 + 模板)
人工智能
zhangshuang-peta4 小时前
模型上下文协议(MCP):演进历程、功能特性与Peta的崛起
人工智能·ai agent·mcp·peta
heimeiyingwang4 小时前
企业供应链 AI 优化:需求预测与智能调度
大数据·数据库·人工智能·机器学习