找到【SVM】中最优的惩罚项系数C

因为本来SVM是想找到间隔最大的分割面,所以C越大,SVC会选择边际更小的,能够更好的分类所有训练点的决策边界,不过模型的训练时间也会越长。如果C的设定值较小,那SVC会尽量最大化边界,决策功能会更简单,但代价是训练的准确度。

我们先来调线性核函数:

python 复制代码
#调线性核函数
score = []
C_range = np.linspace(0.01,30,50)
for i in C_range:
    clf = SVC(kernel="linear",C=i,cache_size=5000).fit(Xtrain,Ytrain)
    score.append(clf.score(Xtest,Ytest))
print(max(score), C_range[score.index(max(score))])
plt.plot(C_range,score)
plt.show()

输出结果为:0.9766081871345029 1.2340816326530613

可以看到准确率最高是97%以上。接下来我们来看看在rbf上的结果:

python 复制代码
score = []
C_range = np.linspace(0.01,30,50)
for i in C_range:
    clf = SVC(kernel="rbf",C=i,gamma = 0.012742749857031322,cache_size=5000).fit(Xtrain,Ytrain)
    score.append(clf.score(Xtest,Ytest))
    
print(max(score), C_range[score.index(max(score))])
plt.plot(C_range,score)
plt.show()

输出结果为:0.9824561403508771 6.130408163265306

既然最高的得分所对应的C值是6,那么我们可以在5-7之间进一步细化,看能否找到一个更好的局部最优:

python 复制代码
#进一步细化
score = []
C_range = np.linspace(5,7,50)
for i in C_range:
    clf = SVC(kernel="rbf",C=i,gamma = 
0.012742749857031322,cache_size=5000).fit(Xtrain,Ytrain)
    score.append(clf.score(Xtest,Ytest))
    
print(max(score), C_range[score.index(max(score))])
plt.plot(C_range,score)
plt.show()

输出结果为:0.9824561403508771 5.938775510204081

可以看到,98.2456%就是我们最好的得分。

相关推荐
阳光是sunny6 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
冬奇Lab6 小时前
每日一个开源项目(第148篇):obsidian-skills - Obsidian CEO 亲写的 AI Agent 格式规范,让 Agent 不再破坏你的 Vault
人工智能·开源·资讯
ethantan7 小时前
AI Agent 组成:像人一样思考的智能体
人工智能·程序员·架构
冬奇Lab7 小时前
Workflow 系列(05):评测体系——三层测试结构与 Trace 追踪
人工智能·工作流引擎
ethantan7 小时前
一篇讲解AI Agent 组成:像人一样思考的智能体
人工智能·后端·程序员
Cosolar9 小时前
vLLM 生产级部署完全指南
人工智能·后端·架构
CodePlayer竟然被占用了10 小时前
被美国政府封杀18天,Claude Fable 5 回来了——但代价是什么?
人工智能
IT_陈寒10 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
smartpi11 小时前
SmartPi GPIO 脉冲与回复语执行时序指南
人工智能
阿里云大数据AI技术11 小时前
PAI支持一键部署GLM-5.2,Coding能力比肩Claude Opus 4.8
人工智能