美文网首页
python机器学习入门-用鸢尾花data建立python机器学

python机器学习入门-用鸢尾花data建立python机器学

作者: reco171 | 来源:发表于2019-01-01 09:28 被阅读0次

    机器学习步骤

    机器学习的步骤一般为加载数据集、分割数据集、训练模型、验证模型精度

    鸢尾花data建立python机器学习

    本次运行Python版本为3.6.2,且已安装相关python库,参考博客python版本3以下,故做了适应性修改。运行方式为在python命令执行代码,或下载代码到本地目录,windows dos窗口或linux shell客户端,进入代码所在目录执行
    python mln_20181231.py
    代码如下所示:

    from sklearn.datasets import load_iris
    from sklearn import model_selection
    
    from sklearn.metrics import accuracy_score
    from sklearn.linear_model import LogisticRegression
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.neighbors import KNeighborsClassifier
    from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
    from sklearn.naive_bayes import GaussianNB
    from sklearn.svm import SVC
    
    from sklearn.metrics import confusion_matrix
    from sklearn.metrics import classification_report
    
    #load data
    dataset = load_iris()
    
    print(dataset.data.shape)
    print(dataset.feature_names)
    
    validation_size = 0.20 
    seed = 7 
    #分割数据集
    X_train, X_validation, Y_train, Y_validation=model_selection.train_test_split(dataset.data, dataset.target,test_size=validation_size, random_state=seed)
    
    scoring = 'accuracy' 
    models = []
    models.append(('LR', LogisticRegression())) 
    models.append(('LDA', LinearDiscriminantAnalysis()))
    models.append(('KNN', KNeighborsClassifier()))
    models.append(('CART', DecisionTreeClassifier())) 
    models.append(('NB', GaussianNB()))
    models.append(('SVM', SVC())) 
    results = [] 
    names = [] 
    kfold = model_selection.KFold(n_splits=10, random_state=seed)
    
    for name, model in models:
        kfold = model_selection.KFold(n_splits=10, random_state=seed)
        cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)#每一个算法模型作为其中的参数,计算每一模型的精度得分
        results.append(cv_results)
        names.append(name)
        msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) 
        print(msg) 
    #SVM: 0.991667 (0.025000)
    knn = KNeighborsClassifier()
    #knn拟合训练集
    knn.fit(X_train, Y_train)
    KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
               metric_params=None, n_jobs=None, n_neighbors=5, p=2,
               weights='uniform')
    predictions = knn.predict(X_validation)
    print(accuracy_score(Y_validation, predictions))#验证集精度得分
    
    print(confusion_matrix(Y_validation, predictions))
    
    print(classification_report(Y_validation, predictions))
    

    参考

    用鸢尾花data建立python机器学习的初步印象(一)
    用鸢尾花data建立python机器学习代码
    转:iris数据集及简介

    相关文章

      网友评论

          本文标题:python机器学习入门-用鸢尾花data建立python机器学

          本文链接:https://www.haomeiwen.com/subject/vazglqtx.html