样本:

使用的算法:

代码:

  1. import numpy as np
  2. import pandas as pd
  3. import datetime
  4.  
  5. from sklearn.impute import SimpleImputer #预处理模块
  6. from sklearn.model_selection import train_test_split #训练集和测试集模块
  7. from sklearn.metrics import classification_report #预测结果评估模块
  8.  
  9. from sklearn.neighbors import KNeighborsClassifier #K近邻分类器
  10. from sklearn.tree import DecisionTreeClassifier #决策树分类器
  11. from sklearn.naive_bayes import GaussianNB #高斯朴素贝叶斯函数
  12.  
  13. starttime = datetime.datetime.now()
  14.  
  15. def load_datasets(feature_paths, label_paths):
  16. feature = np.ndarray(shape=(0, 41)) #列数量和特征维度为41
  17. label = np.ndarray(shape=(0, 1))
  18. for file in feature_paths:
  19. #逗号分隔符读取特征数据,将问号替换标记为缺失值,文件不包含表头
  20. df = pd.read_table(file, delimiter=',', na_values='?', header=None)
  21. #df = df.fillna(df.mean()) #若SimpleImputer无法处理nan,则用pandas本身处理
  22. #使用平均值补全缺失值,然后将数据进行补全
  23. imp = SimpleImputer(missing_values=np.nan, strategy='mean') #此处与教程不同,版本更新,需要使用最新的函数填充NAn,暂不明如何调用
  24. imp.fit(df) #训练预处理器 此句有问题
  25. df = imp.transform(df) #生产预处理结果
  26. feature = np.concatenate((feature, df))#将新读入的数据合并到特征集中
  27.  
  28. for file in label_paths:
  29. df = pd.read_table(file, header=None)
  30. #将新读入的数据合并到标签集合中
  31. label = np.concatenate((label, df))
  32. #将标签归整为一维向量
  33. label = np.ravel(label)
  34. return feature, label
  35.  
  36. if __name__ == '__main__':
  37. #读取文件,根据本地目录文件夹而设定
  38. path = 'D:\python_source\Machine_study\mooc_data\classification\dataset/'
  39. featurePaths, labelPaths = [], []
  40. for i in range(0, 5, 1): #chr(ord('A') + i)==B/C/D
  41. featurePath = path + chr(ord('A') + i) + '/' + chr(ord('A') + i) + '.feature'
  42. featurePaths.append(featurePath)
  43. labelPath = path + chr(ord('A') + i) + '/' + chr(ord('A') + i) + '.label'
  44. labelPaths.append(labelPath)
  45. #将前4个数据作为训练集读入
  46. x_train, y_train = load_datasets(featurePaths[:4], labelPaths[:4])
  47. #将最后一个数据作为测试集读入
  48. x_test, y_test = load_datasets(featurePaths[4:], labelPaths[4:])
  49. #使用全量数据作为训练集,借助函数将训练数据打乱,便于后续分类器的初始化和训练
  50. x_train, x_, y_train, y_ = train_test_split(x_train, y_train, test_size=0.0)
  51.  
  52. print('Start training knn')
  53. knn = KNeighborsClassifier().fit(x_train, y_train) #使用KNN算法进行训练
  54. print('Training done')
  55. answer_knn = knn.predict(x_test)
  56.  
  57. print('Start training DT')
  58. dt = DecisionTreeClassifier().fit(x_train, y_train) #使用决策树算法进行训练
  59. print('Training done')
  60. answer_dt = dt.predict(x_test)
  61. print('Prediction done')
  62.  
  63. print('Start training Bayes')
  64. gnb = GaussianNB().fit(x_train, y_train) #使用贝叶斯算法进行训练
  65. print('Training done')
  66. answer_gnb = gnb.predict(x_test)
  67. print('Prediction done')
  68.  
  69. #对分类结果从 精确率precision 召回率recall f1值fl-score和支持度support四个维度进行衡量
  70. print('\n\nThe classification report for knn:')
  71. print(classification_report(y_test, answer_knn))
  72. print('\n\nThe classification report for DT:')
  73. print(classification_report(y_test, answer_dt))
  74. print('\n\nThe classification report for Bayes:')
  75. print(classification_report(y_test, answer_gnb))
  76. endtime = datetime.datetime.now()
  77. print(endtime - starttime) #时间统计

效果图:

2019-08-01【机器学习】有监督学习之分类 KNN,决策树,Nbayes算法实例 (人体运动状态信息评级)的更多相关文章

  1. 吴裕雄 python 机器学习——半监督学习标准迭代式标记传播算法LabelPropagation模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn import d ...

  2. 【纪中集训】2019.08.01【NOIP提高组】模拟 A 组TJ

    T1 Description 给定一个\(N*N(N≤8)\)的矩阵,每一格有一个0~5的颜色.每次可将左上角的格子所在连通块变为一种颜色,求最少操作数. Solution IDA*=启发式迭代加深 ...

  3. 机器学习--最邻近规则分类KNN算法

    理论学习: 3. 算法详述        3.1 步骤:      为了判断未知实例的类别,以所有已知类别的实例作为参照      选择参数K      计算未知实例与所有已知实例的距离      选 ...

  4. 机器学习——十大数据挖掘之一的决策树CART算法

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是机器学习专题的第23篇文章,我们今天分享的内容是十大数据挖掘算法之一的CART算法. CART算法全称是Classification ...

  5. 【Todo】【转载】Spark学习 & 机器学习(实战部分)-监督学习、分类与回归

    理论原理部分可以看这一篇:http://www.cnblogs.com/charlesblc/p/6109551.html 这里是实战部分.参考了 http://www.cnblogs.com/shi ...

  6. Python 机器学习实战 —— 监督学习(下)

    前言 近年来AI人工智能成为社会发展趋势,在IT行业引起一波热潮,有关机器学习.深度学习.神经网络等文章多不胜数.从智能家居.自动驾驶.无人机.智能机器人到人造卫星.安防军备,无论是国家级军事设备还是 ...

  7. Python 机器学习实战 —— 监督学习(上)

    前言 近年来AI人工智能成为社会发展趋势,在IT行业引起一波热潮,有关机器学习.深度学习.神经网络等文章多不胜数.从智能家居.自动驾驶.无人机.智能机器人到人造卫星.安防军备,无论是国家级军事设备还是 ...

  8. python_机器学习_监督学习模型_决策树

    决策树模型练习:https://www.kaggle.com/c/GiveMeSomeCredit/overview 1. 监督学习--分类 机器学习肿分类和预测算法的评估: a. 准确率 b.速度 ...

  9. 机器学习实战 - 读书笔记(07) - 利用AdaBoost元算法提高分类性能

    前言 最近在看Peter Harrington写的"机器学习实战",这是我的学习笔记,这次是第7章 - 利用AdaBoost元算法提高分类性能. 核心思想 在使用某个特定的算法是, ...

随机推荐

  1. kerberos系列之hive认证配置

    大数据安全系列之hive的kerberos认证配置,其它系列链接如下 https://www.cnblogs.com/bainianminguo/p/12548076.html-----------安 ...

  2. Redis缓存设计与性能优化

    Redis我们一般是用作缓存,扛并发:或者用于某些特定的业务场景,比如前面说到redis各种数据类型的使用场景以及redis的哨兵和集群模式. 这里主要整理了下redis用作缓存,存在的一些问题,以及 ...

  3. 【codeforces】Codeforces Round #612 (Div. 2) C. Garland——DP

    题目链接 贪心模拟了半天,最后放弃了 题意 给你一串从1−n1-n1−n的序列,其中部分未知(表示为0),补全序列使得相邻数值奇偶性相反的数量最少 相邻数值的奇偶性相反:两个相邻的两个数值,其中一个为 ...

  4. Data Management and Data Management Tools

    Data Management ObjectivesBy the end o this module, you should understand the fundamentals of data m ...

  5. Building Applications with Force.com and VisualForce (DEV401) (二) : Application Essentials:Designing Application on the Force.com Platform

    Dev 401-002:Application Essentials:Designing Application on the Force.com Platform Course Objectives ...

  6. TensorFlow v2.0实现逻辑斯谛回归

    使用TensorFlow v2.0实现逻辑斯谛回归 此示例使用简单方法来更好地理解训练过程背后的所有机制 MNIST数据集概览 此示例使用MNIST手写数字.该数据集包含60,000个用于训练的样本和 ...

  7. 万字综述,核心开发者全面解读PyTorch内部机制

    斯坦福大学博士生与 Facebook 人工智能研究所研究工程师 Edward Z. Yang 是 PyTorch 开源项目的核心开发者之一.他在 5 月 14 日的 PyTorch 纽约聚会上做了一个 ...

  8. [算法]合并链表&删除数组重复项

    合并链表 题目 将两个有序链表合并为一个新的有序链表并返回.新链表是通过拼接给定的两个链表的所有节点组成的. 示例: 输入:1->2->4, 1->3->4 输出:1-> ...

  9. [tyvj2032]升降梯上<dp&spfa>

    题目背景 开启了升降梯的动力之后,探险队员们进入了升降梯运行的那条竖直的隧道,映入眼帘的是一条直通塔顶的轨道.一辆停在轨道底部的电梯.和电梯内一杆控制电梯升降的巨大手柄. 题目描述 Nescafe 之 ...

  10. 常见SQL语句和SQL基础知识

    引自:http://blog.csdn.net/u012467492/article/details/46790205 SQL语句考察(一) 1.查询出每门课都大于80 分的学生姓名 name   k ...