Python 多种算法模型对比

Posted ShenLiang2025

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 多种算法模型对比相关的知识,希望对你有一定的参考价值。

                                 Python 多种算法模型对比

1 声明

本文的数据来自网络,部分代码也有所参照,这里做了注释和延伸,旨在技术交流,如有冒犯之处请联系博主及时处理。

2 算法模型对比简介

可以对同一份训练数据集应用多个算法模型,通过交叉验证的方法计算出准确率进行比较以选择效果较好的算法。应用交叉验证的好处是当用新的数据检验模型的表现时,可以在一定程度上减小过拟合。

1 这里的数据集来自pima-indians-diabetes(最初来自国家糖尿病/消化/肾脏疾病研究所。数据集的目标是基于数据集中包含的某些诊断测量来诊断性的预测 患者是否患有糖尿病)。

2 当前代码仅为演示多模型对比的用法,该数据集的特征并未做预处理。

3 KNN代码示例

# Step1 加载数据、各种分类包
from pandas import read_csv
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import KFold
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import cross_val_score
from matplotlib import pyplot
from sklearn.neighbors import KNeighborsClassifier
# 导入数据
filename = '../input/pima-indians-diabetes.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(filename, names=names)
# 将数据分为输入数据和输出结果
array = data.values
X = array[:, 0:8]
Y = array[:, 8]
num_folds = 10
seed = 1007
kfold = KFold(n_splits=num_folds, random_state=seed)
models = 
models['LR'] = LogisticRegression(solver='liblinear')
models['LDA'] = LinearDiscriminantAnalysis()
models['KNN'] = KNeighborsClassifier()
models['CART'] = DecisionTreeClassifier()
models['SVM'] = SVC(gamma='auto')
models['NB'] = GaussianNB()
results = []
for name in models:
    result = cross_val_score(models[name], X, Y, cv=kfold)
    results.append(result)
    msg = '%s: %.3f (%.3f)' % (name, result.mean(), result.std())
    print(msg)
# 图表显示
fig = pyplot.figure()
from matplotlib.font_manager import FontProperties
#设置支持中文字体
fp= FontProperties(fname="c:/windows/fonts/simsun.ttc", size=12)
fig.suptitle('各分类算法比较',fontproperties=fp)
ax = fig.add_subplot(111)
pyplot.boxplot(results)
ax.set_xticklabels(models.keys())
pyplot.show()

 

LR: 0.770 (0.048)
LDA: 0.773 (0.052)
KNN: 0.727 (0.062)
CART: 0.689 (0.067)
SVM: 0.651 (0.072)
NB: 0.755 (0.043)

 

4 总结

 

 

以上是关于Python 多种算法模型对比的主要内容,如果未能解决你的问题,请参考以下文章

Python | 基于LendingClub数据的分类预测研究Part01——问题重述+特征选择+算法对比

一种简单的三维重建算法的实现源码

增加摄影测量模型的深度细节

基于Python的智能视频分析之人数统计的多种实现

如何在python中测量算法的运行时间[重复]

基于三角网格排序的人体三围测量算法