找到【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%就是我们最好的得分。

相关推荐
AI营销快线4 分钟前
金融AI内容合规,三类系统怎么选?
大数据·人工智能
测试人社区-千羽5 分钟前
智能测试的终极形态:从自动化到自主化的范式变革
运维·人工智能·python·opencv·测试工具·自动化·开源软件
用户9186034312737 分钟前
AI重塑云原生应用开发实战-极客时间
人工智能
秋刀鱼 ..9 分钟前
2026年机器人感知与智能控制国际学术会议(RPIC 2026)
运维·人工智能·科技·金融·机器人·自动化
listhi5209 分钟前
使用Hopfield神经网络解决旅行商问题
人工智能·深度学习·神经网络
锐学AI11 分钟前
从零开始学MCP(八)- 构建一个MCP server
人工智能·python
木棉知行者12 分钟前
PyTorch 核心方法:state_dict ()、parameters () 参数打印与应用
人工智能·pytorch·python
爱打代码的小林12 分钟前
机器学习基础(线性,逻辑回归)
人工智能·机器学习·逻辑回归·线性回归
cetcht888814 分钟前
配电房 AI 巡检机器人系统:技术架构、核心功能与工程实现全解析
人工智能·架构·机器人
m0_6265352016 分钟前
看模型结构 分析模型结构
人工智能·机器学习