【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参数来继续优化。

相关推荐
我材不敲代码4 分钟前
Python爬虫介绍——简单了解一下爬虫
开发语言·爬虫·python
Katecat996639 分钟前
古巽伽罗语字符识别与分类_Cascade-Mask-RCNN_RegNetX-400MF实现
人工智能·目标跟踪
说文科技12 分钟前
大模型项目实战之dpo微调
人工智能·算法
周杰伦_Jay18 分钟前
【Mac 上命令行安装 Claude Code】(Claude 的终端版 AI 编程助手)完整指南
人工智能·macos·claude code
一只理智恩23 分钟前
AI辅助,两天实现一个IM系统?
人工智能
薛定谔的猫198225 分钟前
二十、使用PyTorch和Hugging Face Transformers训练中文GPT-2模型的技术实践
人工智能·pytorch·gpt
naruto_lnq26 分钟前
Python日志记录(Logging)最佳实践
jvm·数据库·python
yuankoudaodaokou27 分钟前
高帧率扫描如何重塑动态三维扫描与思看科技300fps解决方案
python·科技
rainbow688928 分钟前
Python零基础到精通全攻略
python
zhangfeng113329 分钟前
大模型微调主要框架 Firefly vs LLaMA Factory 全方位对比表
人工智能·语言模型·开源·llama