python sklearn常用分类算法模型的调用

作者:海涛anywn 时间:2021-06-18 11:42:25 

本文实例为大家分享了python sklearn分类算法模型调用的具体代码,供大家参考,具体内容如下

实现对'NB', 'KNN', 'LR', 'RF', 'DT', 'SVM','SVMCV', 'GBDT'模型的简单调用。


# coding=gbk

import time
from sklearn import metrics
import pickle as pickle
import pandas as pd

# Multinomial Naive Bayes Classifier
def naive_bayes_classifier(train_x, train_y):
 from sklearn.naive_bayes import MultinomialNB
 model = MultinomialNB(alpha=0.01)
 model.fit(train_x, train_y)
 return model

# KNN Classifier
def knn_classifier(train_x, train_y):
 from sklearn.neighbors import KNeighborsClassifier
 model = KNeighborsClassifier()
 model.fit(train_x, train_y)
 return model

# Logistic Regression Classifier
def logistic_regression_classifier(train_x, train_y):
 from sklearn.linear_model import LogisticRegression
 model = LogisticRegression(penalty='l2')
 model.fit(train_x, train_y)
 return model

# Random Forest Classifier
def random_forest_classifier(train_x, train_y):
 from sklearn.ensemble import RandomForestClassifier
 model = RandomForestClassifier(n_estimators=8)
 model.fit(train_x, train_y)
 return model

# Decision Tree Classifier
def decision_tree_classifier(train_x, train_y):
 from sklearn import tree
 model = tree.DecisionTreeClassifier()
 model.fit(train_x, train_y)
 return model

# GBDT(Gradient Boosting Decision Tree) Classifier
def gradient_boosting_classifier(train_x, train_y):
 from sklearn.ensemble import GradientBoostingClassifier
 model = GradientBoostingClassifier(n_estimators=200)
 model.fit(train_x, train_y)
 return model

# SVM Classifier
def svm_classifier(train_x, train_y):
 from sklearn.svm import SVC
 model = SVC(kernel='rbf', probability=True)
 model.fit(train_x, train_y)
 return model

# SVM Classifier using cross validation
def svm_cross_validation(train_x, train_y):
 from sklearn.grid_search import GridSearchCV
 from sklearn.svm import SVC
 model = SVC(kernel='rbf', probability=True)
 param_grid = {'C': [1e-3, 1e-2, 1e-1, 1, 10, 100, 1000], 'gamma': [0.001, 0.0001]}
 grid_search = GridSearchCV(model, param_grid, n_jobs = 1, verbose=1)
 grid_search.fit(train_x, train_y)
 best_parameters = grid_search.best_estimator_.get_params()
 for para, val in list(best_parameters.items()):
   print(para, val)
 model = SVC(kernel='rbf', C=best_parameters['C'], gamma=best_parameters['gamma'], probability=True)
 model.fit(train_x, train_y)
 return model

def read_data(data_file):
 data = pd.read_csv(data_file)
 train = data[:int(len(data)*0.9)]
 test = data[int(len(data)*0.9):]
 train_y = train.label
 train_x = train.drop('label', axis=1)
 test_y = test.label
 test_x = test.drop('label', axis=1)
 return train_x, train_y, test_x, test_y

if __name__ == '__main__':
 data_file = "H:\\Research\\data\\trainCG.csv"
 thresh = 0.5
 model_save_file = None
 model_save = {}

test_classifiers = ['NB', 'KNN', 'LR', 'RF', 'DT', 'SVM','SVMCV', 'GBDT']
 classifiers = {'NB':naive_bayes_classifier,  
        'KNN':knn_classifier,
         'LR':logistic_regression_classifier,
         'RF':random_forest_classifier,
         'DT':decision_tree_classifier,
        'SVM':svm_classifier,
       'SVMCV':svm_cross_validation,
        'GBDT':gradient_boosting_classifier
 }

print('reading training and testing data...')
 train_x, train_y, test_x, test_y = read_data(data_file)

for classifier in test_classifiers:
   print('******************* %s ********************' % classifier)
   start_time = time.time()
   model = classifiers[classifier](train_x, train_y)
   print('training took %fs!' % (time.time() - start_time))
   predict = model.predict(test_x)
   if model_save_file != None:
     model_save[classifier] = model
   precision = metrics.precision_score(test_y, predict)
   recall = metrics.recall_score(test_y, predict)
   print('precision: %.2f%%, recall: %.2f%%' % (100 * precision, 100 * recall))
   accuracy = metrics.accuracy_score(test_y, predict)
   print('accuracy: %.2f%%' % (100 * accuracy))  

if model_save_file != None:
   pickle.dump(model_save, open(model_save_file, 'wb'))

来源:https://blog.csdn.net/lihaitao000/article/details/66972039

标签:python,sklearn,分类算法模型
0
投稿

猜你喜欢

  • 分析python请求数据

    2023-09-26 08:46:08
  • Pycharm运行程序时,控制台输出PyDev console:starting问题

    2022-09-27 14:26:32
  • PHP中PDO基础教程 入门级

    2023-11-14 16:34:39
  • C#处理MySql多个返回集的方法

    2024-01-21 15:30:08
  • Python PyQt5学习之样式设置详解

    2022-11-04 20:48:46
  • JS的Form表单转JSON格式的操作代码

    2023-07-02 05:24:03
  • python爬虫 猫眼电影和电影天堂数据csv和mysql存储过程解析

    2024-01-20 23:51:58
  • ASP使用wsImage组件给图片加水印

    2008-12-29 19:14:00
  • PyQt5笔记之弹出窗口大全

    2021-06-30 06:53:14
  • 高考要来啦!用Python爬取历年高考数据并分析

    2021-06-10 04:08:25
  • javascript globalStorage类代码

    2024-04-22 12:51:08
  • 记一次MySQL更新语句update的踩坑

    2024-01-16 19:35:29
  • Python+OpenCV图像处理——实现轮廓发现

    2023-12-12 23:30:31
  • pytorch permute维度转换方法

    2023-09-07 17:49:32
  • viper配置框架的介绍支持zookeeper的读取和监听

    2024-04-27 15:32:12
  • TensorFlow模型保存和提取的方法

    2022-04-30 05:19:54
  • js模仿php中strtotime()与date()函数实现方法

    2024-04-18 10:01:55
  • SQL语句解析执行的过程及原理

    2024-01-26 21:11:55
  • mysql中limit查询踩坑实战记录

    2024-01-16 13:38:45
  • SQLServer行转列实现思路记录

    2024-01-18 05:42:43
  • asp之家 网络编程 m.aspxhome.com