机器学习小工具集合

我!李英俊!觉得这篇文章超级有用!值得你一看!

功能: 机器学习工具集合,直接导入一个类,传参训练集,验证集就能生成报告

使用方式:

  1. 需要自己传入X_train, y_train, X_test, y_test作为输入(并没有用交叉验证,因为我在用的时候考虑到了样本不均衡的问题,交叉验证无法分层采样),下面有鸢尾花和手写数字集两种样本作为输入样例。
  2. 传入save_path作为输出报告和模型的路径,例如save_path='./models/'。里面包括了每个模型的输出报告(测试集,验证集都有),每个模型(10个模型加最后的集成模型,对所有数据进行了重新学习),使用joblib保存的,使用的话直接joblib.load就行。还有一个优化报告,即对四种集成学习模型进行优化后的结果。
  3. 传入target_names作为优化报告里面两种分类的名字,暂时只支持二分类。

tips: 下面会附上代码和两个使用demo,也会贴上github上的链接,如果大家需要什么新的功能可以留言告诉我,最新的更新应该会在github上同步,希望大家星星我,有空的话再更新博客。求个赞不过分吧!转载请一定表明出处哟~

点我打开github地址,求关注

结果展示:

  • 输出example

  • 输出报告example

  • 优化报告example

  • 代码具体实现:

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    # coding=utf-8 """
    @author: Li Tian
    @contact: 694317828@qq.com
    @software: pycharm
    @file: ML_combines.py
    @time: 2019/9/23 8:53
    @desc: 机器学习工具集合,直接写一个类,传参训练集,验证集就能生成报告
    """
    from sklearn.metrics import f1_score
    from sklearn.model_selection import train_test_split
    from collections import OrderedDictclass MLTools:"""包含:多项式朴素贝叶斯, 高斯朴素贝叶斯, K最近邻, 逻辑回归, 支持向量机, 决策树, 随机森林, Adaboost, GBDT, xgboost"""random_state = 42# 粗略 随机森林调参数值# 参考链接1:https://blog.csdn.net/geduo_feng/article/details/79558572# 参考链接2:https://blog.csdn.net/qq_35040963/article/details/88832030parameter_tree = {# 集成模型数量越小越简单'n_estimators': range(10, 200, 20),# 最大树深度越小越简单'max_depth': range(1, 10, 1),# 最小样本分割数越大越简单'min_samples_split': list(range(2, 10, 1))[::-1],}parameter_tree = OrderedDict(parameter_tree)def __init__(self, X_train, y_train, X_test, y_test):self.X_train = X_trainself.y_train = y_trainself.X_test = X_testself.y_test = y_test# Multinomial Naive Bayes Classifier / 多项式朴素贝叶斯def multinomial_naive_bayes_classifier(self):from sklearn.naive_bayes import MultinomialNBmodel = MultinomialNB(alpha=0.01)model.fit(self.X_train, self.y_train)return model, None# Gaussian Naive Bayes Classifier / 高斯朴素贝叶斯def gaussian_naive_bayes_classifier(self):from sklearn.naive_bayes import GaussianNBmodel = GaussianNB()model.fit(self.X_train, self.y_train)return model, None# KNN Classifier / K最近邻def knn_classifier(self):from sklearn.neighbors import KNeighborsClassifiermodel = KNeighborsClassifier()model.fit(self.X_train, self.y_train)return model, None# Logistic Regression Classifier / 逻辑回归def logistic_regression_classifier(self):from sklearn.linear_model import LogisticRegressionmodel = LogisticRegression(penalty='l2')model.fit(self.X_train, self.y_train)return model, None# SVM Classifier / 支持向量机def svm_classifier(self):from sklearn.svm import SVCmodel = SVC(kernel='rbf', probability=True)model.fit(self.X_train, self.y_train)return model, None# Decision Tree Classifier / 决策树def decision_tree_classifier(self):from sklearn.tree import DecisionTreeClassifiermodel = DecisionTreeClassifier()model.fit(self.X_train, self.y_train)return model, None# Random Forest Classifier / 随机森林def random_forest_classifier(self, is_adjust=True):from sklearn.ensemble import RandomForestClassifier# 训练普通模型model = RandomForestClassifier()model.fit(self.X_train, self.y_train)test_pred = model.predict(self.X_test)min_score = f1_score(self.y_test, test_pred, average='macro')if not is_adjust:return model, Nonemax_score = 0best_param = [None, None, None]for p1 in MLTools.parameter_tree['n_estimators']:for p2 in MLTools.parameter_tree['max_depth']:for p3 in MLTools.parameter_tree['min_samples_split']:test_model = RandomForestClassifier(random_state=MLTools.random_state, n_estimators=p1,max_depth=p2, min_samples_split=p3, n_jobs=-1)test_model.fit(self.X_train, self.y_train)test_pred = test_model.predict(self.X_test)new_score = f1_score(self.y_test, test_pred, average='macro')# 输出检查每一个细节,可能存在不同的参数得到相同的精度值# print('n_estimators=' + str(p1) + 'max_depth=' + str(p2) + 'min_samples_split=' + str(p3) + '-->' + str(new_score))if new_score > max_score:max_score = new_scorebest_param = [p1, p2, p3]best_model = RandomForestClassifier(random_state=MLTools.random_state, n_estimators=best_param[0],max_depth=best_param[1], min_samples_split=best_param[2], n_jobs=-1)best_model.fit(self.X_train, self.y_train)word = '-- optimized parameters: \n'count = 0for name in MLTools.parameter_tree.keys():word = word + name + ' = ' + str(best_param[count]) + '\n'count += 1word = word + 'f1_macro: ' + '%.4f' % min_score + '-->' + '%.4f' % max_score + "\n"return best_model, word# AdaBoost Classifier / 自适应提升法def adaboost_classifier(self, is_adjust=True):from sklearn.ensemble import AdaBoostClassifierfrom sklearn.tree import DecisionTreeClassifiermodel = AdaBoostClassifier()model.fit(self.X_train, self.y_train)test_pred = model.predict(self.X_test)min_score = f1_score(self.y_test, test_pred, average='macro')if not is_adjust:return model, Nonemax_score = 0best_param = [None, None, None]for p1 in MLTools.parameter_tree['n_estimators']:for p2 in MLTools.parameter_tree['max_depth']:for p3 in MLTools.parameter_tree['min_samples_split']:test_model = AdaBoostClassifier(DecisionTreeClassifier(random_state=MLTools.random_state,max_depth=p2, min_samples_split=p3),random_state=MLTools.random_state, n_estimators=p1)test_model.fit(self.X_train, self.y_train)test_pred = test_model.predict(self.X_test)new_score = f1_score(self.y_test, test_pred, average='macro')if new_score > max_score:max_score = new_scorebest_param = [p1, p2, p3]best_model = AdaBoostClassifier(DecisionTreeClassifier(random_state=MLTools.random_state,max_depth=best_param[1], min_samples_split=best_param[2]),random_state=MLTools.random_state, n_estimators=best_param[0])best_model.fit(self.X_train, self.y_train)word = '-- optimized parameters: \n'count = 0for name in MLTools.parameter_tree.keys():word = word + name + ' = ' + str(best_param[count]) + '\n'count += 1word = word + 'f1_macro: ' + '%.4f' % min_score + '-->' + '%.4f' % max_score + "\n"return best_model, word# GBDT(Gradient Boosting Decision Tree) Classifier / 梯度提升决策树def gradient_boosting_classifier(self, is_adjust=True):from sklearn.ensemble import GradientBoostingClassifiermodel = GradientBoostingClassifier()model.fit(self.X_train, self.y_train)test_pred = model.predict(self.X_test)min_score = f1_score(self.y_test, test_pred, average='macro')if not is_adjust:return model, Nonemax_score = 0best_param = [None, None, None]for p1 in MLTools.parameter_tree['n_estimators']:for p2 in MLTools.parameter_tree['max_depth']:for p3 in MLTools.parameter_tree['min_samples_split']:test_model = GradientBoostingClassifier(random_state=MLTools.random_state, n_estimators=p1,max_depth=p2, min_samples_split=p3)test_model.fit(self.X_train, self.y_train)test_pred = test_model.predict(self.X_test)new_score = f1_score(self.y_test, test_pred, average='macro')if new_score > max_score:max_score = new_scorebest_param = [p1, p2, p3]best_model = GradientBoostingClassifier(random_state=MLTools.random_state, n_estimators=best_param[0],max_depth=best_param[1], min_samples_split=best_param[2])best_model.fit(self.X_train, self.y_train)word = '-- optimized parameters: \n'count = 0for name in MLTools.parameter_tree.keys():word = word + name + ' = ' + str(best_param[count]) + '\n'count += 1word = word + 'f1_macro: ' + '%.4f' % min_score + '-->' + '%.4f' % max_score + "\n"return best_model, word# xgboost / 极端梯度提升def xgboost_classifier(self, is_adjust=True):from xgboost import XGBClassifiermodel = XGBClassifier()model.fit(self.X_train, self.y_train)test_pred = model.predict(self.X_test)min_score = f1_score(self.y_test, test_pred, average='macro')if not is_adjust:return model, Nonemax_score = 0best_param = [0, 0, 0]for p1 in MLTools.parameter_tree['n_estimators']:for p2 in MLTools.parameter_tree['max_depth']:for p3 in MLTools.parameter_tree['min_samples_split']:test_model = XGBClassifier(random_state=MLTools.random_state, n_estimators=p1,max_depth=p2, min_samples_split=p3, n_jobs=-1)test_model.fit(self.X_train, self.y_train)test_pred = test_model.predict(self.X_test)new_score = f1_score(self.y_test, test_pred, average='macro')if new_score > max_score:max_score = new_scorebest_param = [p1, p2, p3]best_model = XGBClassifier(random_state=MLTools.random_state, n_estimators=best_param[0],max_depth=best_param[1], min_samples_split=best_param[2], n_jobs=-1)best_model.fit(self.X_train, self.y_train)word = '-- optimized parameters: \n'count = 0for name in MLTools.parameter_tree.keys():word = word + name + ' = ' + str(best_param[count]) + '\n'count += 1word = word + 'f1_macro: ' + '%.4f' % min_score + '-->' + '%.4f' % max_score + "\n"return best_model, worddef model_building(X_train, y_train, X_test, y_test, save_path, target_names=None, just_emsemble=False):"""训练模型,并得到结果,并重新训练所有数据,保存模型:param save_path: 模型的保存路径:param target_names: 样本标签名:param just_emsemble: 已经有了其他模型,只对模型进行集成"""from sklearn.metrics import classification_reportimport joblibimport osimport numpy as npif not just_emsemble:tool = MLTools(X_train, y_train, X_test, y_test)models = [tool.multinomial_naive_bayes_classifier(),tool.gaussian_naive_bayes_classifier(),tool.knn_classifier(),tool.logistic_regression_classifier(),tool.svm_classifier(),tool.decision_tree_classifier(),tool.random_forest_classifier(),tool.adaboost_classifier(),tool.gradient_boosting_classifier(),tool.xgboost_classifier()]model_names = ['多项式朴素贝叶斯', '高斯朴素贝叶斯', 'K最近邻', '逻辑回归', '支持向量机', '决策树', '随机森林', 'Adaboost', 'GBDT', 'xgboost']# 遍历每个模型f = open(save_path + 'report.txt', 'w+')g = open(save_path + 'optimized.txt', 'w+')for count in range(len(models)):model, optimized = models[count]model_name = model_names[count]print(str(count + 1) + '. 正在运行:', model_name, '...')train_pred = model.predict(X_train)test_pred = model.predict(X_test)train = classification_report(y_train, train_pred, target_names=target_names)test = classification_report(y_test, test_pred, target_names=target_names)f.write('- ' + model_name + '\n')f.write('-- 【训练集】' + '\n')f.writelines(train)f.write('\n')f.write('-- 【测试集】' + '\n')f.writelines(test)f.write('\n')g.write('- ' + model_name + '\n')if optimized:g.write(optimized)g.write('\n')model.fit(np.r_[np.array(X_train), np.array(X_test)], np.r_[np.array(y_train), np.array(y_test)])joblib.dump(model, os.path.join(save_path, model_name + '.plk'))f.close()g.close()# 开始集成模型from sklearn.ensemble import VotingClassifierf = open(save_path + 'report.txt', 'a+')emsemble_names = ['随机森林', 'Adaboost', 'GBDT', 'xgboost']emsemble_path = [os.path.join(save_path, i + '.plk') for i in emsemble_names]estimators = []for x, y in zip(emsemble_names, emsemble_path):estimators.append((x, joblib.load(y)))voting_clf = VotingClassifier(estimators, voting='soft', n_jobs=-1)voting_clf.fit(X_train, y_train)print('11.  正在运行:集成模型...')train_pred = voting_clf.predict(X_train)test_pred = voting_clf.predict(X_test)train = classification_report(y_train, train_pred, target_names=target_names)test = classification_report(y_test, test_pred, target_names=target_names)f.write('- ' + '集成模型' + '\n')f.write('-- 【训练集】' + '\n')f.writelines(train)f.write('\n')f.write('-- 【测试集】' + '\n')f.writelines(test)f.write('\n')voting_clf.fit(np.r_[np.array(X_train), np.array(X_test)], np.r_[np.array(y_train), np.array(y_test)])joblib.dump(voting_clf, os.path.join(save_path, '集成模型' + '.plk'))f.close()def example1():"""鸢尾花数据集进行测试"""from sklearn.datasets import load_irisiris = load_iris()iris_data = iris['data']iris_target = iris['target']iris_names = iris['target_names']X_train, X_test, y_train, y_test = train_test_split(iris_data, iris_target, test_size=0.2, random_state=42)model_building(X_train, y_train, X_test, y_test, save_path='./models/', target_names=iris_names)def example2():"""手写数据集进行测试"""from sklearn.datasets import load_digitsimport numpy as npdigits = load_digits()digits_data = digits['images']digits_target = digits['target']digits_names = digits['target_names']shape = digits_data.shapeX = np.array(digits_data).reshape(shape[0], shape[1] * shape[2])a, b = 4, 9index1 = digits_target == aindex2 = digits_target == bX = np.r_[X[index1], X[index2]]y = np.r_[digits_target[index1], digits_target[index2]]names = [str(a), str(b)]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)model_building(X_train, y_train, X_test, y_test, save_path='./models2/', target_names=names)if __name__ == '__main__':example1()
    

我的CSDN:https://blog.csdn.net/qq_21579045

我的博客园:https://www.cnblogs.com/lyjun/

我的Github:https://github.com/TinyHandsome

纸上得来终觉浅,绝知此事要躬行~

欢迎大家过来OB~

by 李英俊小朋友

【新手福音】分享一个自己制作的机器学习工具集合相关推荐

  1. 分享一个发送http请求的工具类

    分享一个发送http请求的工具类 maven依赖只需要导入一个 <dependencies><dependency><groupId>commons-httpcli ...

  2. 分享一个非常好的机器学习基础,自己回顾总结,共同学习

    ## 机器学习 概述 `机器学习(Machine Learning,ML)` 是使用计算机来彰显数据背后的真实含义,它为了把无序的数据转换成有用的信息.是一门多领域交叉学科,涉及概率论.统计学.逼近论 ...

  3. 分享一个在线占位图制作工具

    给大家分享一个在线占位置,生成图片的一个工具 先说一下为什么需要这个? 我们在制作一个网站,或者交付前端项目时,难免会使用到图片素材,有的喜欢使用在线地址来引用图片路径,还有的比较喜欢搜图片保存之后再 ...

  4. 工具 | 分享一个好用的绘图工具

    1024G 嵌入式资源大放送!包括但不限于C/C++.单片机.Linux等.关注微信公众号[嵌入式大杂烩],回复1024,即可免费获取! 前言 一些优秀的.清晰的技术文档.技术博客.工作汇报都少不了一 ...

  5. 分享一个视频大小压缩小工具

    分享一个视频压缩小工具 配置环境变量 命令行使用命令进行压缩 工具名称是:ffmpeg 配置环境变量 配置环境变量,把你的工具放置的目录路径配置在系统path变量中,后面需要在命令行中使用 命令行使用 ...

  6. 快过年了,来分享一个个人制作的节日祝福软件

    扫下面二维码,即可下载使用: (马云巴巴发福利,支付宝搜索619015079领红包) 个人想着过年了,要发祝福短信之类的,于是想着想着,就自己动手随便弄了一个小小的祝福软件,功能很简单,供大家开心发祝 ...

  7. 工具分享 --- 分享一个在线制作ico的网站

    还不错- 生成后一般放在imgs的下面. link:favicon + tab 导入链接 http://www.faviconico.org/

  8. 分享一个安卓app自动化遍历工具--Appetizer

    原文:https://blog.csdn.net/xgh1951/article/details/87159355 今天在群里面无意中有小伙伴介绍了这么一款安卓app自动化测试的神器,Appetize ...

  9. 分享一个盟重英雄脚本挂机工具(附随机数生成源码)

    游戏脚本基本只能做到和真实玩家一样的事情,只是不怕苦不怕累,能一直干活而已.由于不涉及修改游戏信息,因此也没有外挂的那些法律风险,而且上手也简单啊,毕竟我这种半路出家的都能用按键精灵之类的第三方软件去 ...

  10. 分享一个app内日志查看工具

      很早之前为上家公司写过一个日志查看搜索的组件,方便在开发,内测阶段调试bug.但是感觉不太满意,最近自己 重新完善了一下,开源给大家.主要完善的内容如下: 1,每次app杀死,重新启动都会新创建一 ...

最新文章

  1. conda安装qiime2-清华镜像源替换法解决安装失败
  2. delphi 怎么获取工程版本号
  3. “个人核心竞争力”与“危机感”
  4. android连接ecs sql server_MySQL 执行 SQL 语句的过程解析
  5. java Switch里面的类型问题
  6. CPU设计学习-流水线
  7. 集群、RAC和MAA
  8. 【Kafka】kafka消费报错 no brokers found in zk
  9. Kylin 2.6.0JDBC方式访问
  10. 监听是否到达页面滑动的可视区域最底部
  11. tomcat可以直接起jar吗_天津买房可以直接落户吗
  12. Android性能检测--traceview工具各个参数的意思
  13. android SDK安装以及环境变量配置(windows)
  14. OSPF综合实验(三)
  15. FaceX-Zoo: A PyTocrh Toolbox for Face Recognition
  16. 位(bit)、字节(Byte)、MB(兆位)之间的换算关系
  17. 弘辽科技:淘宝开店后就可以直播吗?淘宝直播技巧是什么?
  18. mysql关联删除(删除不存在另一张表的记录)
  19. 如何使用使用 HAVING 与 ORDER BY?
  20. 什么是链接?(动态链接库和静态链接库的对比)

热门文章

  1. 建筑能耗管理系统如何应用到办公楼中?
  2. MySQL 8.0完美卸载(windows)
  3. CentOS7.6安装VNC
  4. ul li img标签 图片不显示的问题
  5. Python-玩转数据-Scrapy中Spiders
  6. 世界银行贷款可持续发展农业项目商业计划书
  7. 硬盘重新分区后数据丢失如何恢复?
  8. 浅谈前端开发必备知识点及未来发展方向
  9. python——operator详解
  10. 笔记本怎么设置WIfi热点