样本:

使用的算法:

代码:

import numpy as np
import pandas as pd
import datetime from sklearn.impute import SimpleImputer #预处理模块
from sklearn.model_selection import train_test_split #训练集和测试集模块
from sklearn.metrics import classification_report #预测结果评估模块 from sklearn.neighbors import KNeighborsClassifier #K近邻分类器
from sklearn.tree import DecisionTreeClassifier #决策树分类器
from sklearn.naive_bayes import GaussianNB #高斯朴素贝叶斯函数 starttime = datetime.datetime.now() def load_datasets(feature_paths, label_paths):
feature = np.ndarray(shape=(0, 41)) #列数量和特征维度为41
label = np.ndarray(shape=(0, 1))
for file in feature_paths:
#逗号分隔符读取特征数据,将问号替换标记为缺失值,文件不包含表头
df = pd.read_table(file, delimiter=',', na_values='?', header=None)
#df = df.fillna(df.mean()) #若SimpleImputer无法处理nan,则用pandas本身处理
#使用平均值补全缺失值,然后将数据进行补全
imp = SimpleImputer(missing_values=np.nan, strategy='mean') #此处与教程不同,版本更新,需要使用最新的函数填充NAn,暂不明如何调用
imp.fit(df) #训练预处理器 此句有问题
df = imp.transform(df) #生产预处理结果
feature = np.concatenate((feature, df))#将新读入的数据合并到特征集中 for file in label_paths:
df = pd.read_table(file, header=None)
#将新读入的数据合并到标签集合中
label = np.concatenate((label, df))
#将标签归整为一维向量
label = np.ravel(label)
return feature, label if __name__ == '__main__':
#读取文件,根据本地目录文件夹而设定
path = 'D:\python_source\Machine_study\mooc_data\classification\dataset/'
featurePaths, labelPaths = [], []
for i in range(0, 5, 1): #chr(ord('A') + i)==B/C/D
featurePath = path + chr(ord('A') + i) + '/' + chr(ord('A') + i) + '.feature'
featurePaths.append(featurePath)
labelPath = path + chr(ord('A') + i) + '/' + chr(ord('A') + i) + '.label'
labelPaths.append(labelPath)
#将前4个数据作为训练集读入
x_train, y_train = load_datasets(featurePaths[:4], labelPaths[:4])
#将最后一个数据作为测试集读入
x_test, y_test = load_datasets(featurePaths[4:], labelPaths[4:])
#使用全量数据作为训练集,借助函数将训练数据打乱,便于后续分类器的初始化和训练
x_train, x_, y_train, y_ = train_test_split(x_train, y_train, test_size=0.0) print('Start training knn')
knn = KNeighborsClassifier().fit(x_train, y_train) #使用KNN算法进行训练
print('Training done')
answer_knn = knn.predict(x_test) print('Start training DT')
dt = DecisionTreeClassifier().fit(x_train, y_train) #使用决策树算法进行训练
print('Training done')
answer_dt = dt.predict(x_test)
print('Prediction done') print('Start training Bayes')
gnb = GaussianNB().fit(x_train, y_train) #使用贝叶斯算法进行训练
print('Training done')
answer_gnb = gnb.predict(x_test)
print('Prediction done') #对分类结果从 精确率precision 召回率recall f1值fl-score和支持度support四个维度进行衡量
print('\n\nThe classification report for knn:')
print(classification_report(y_test, answer_knn))
print('\n\nThe classification report for DT:')
print(classification_report(y_test, answer_dt))
print('\n\nThe classification report for Bayes:')
print(classification_report(y_test, answer_gnb))
endtime = datetime.datetime.now()
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. ArchLinux - 脚本安装使用指南

    前面不想废话,讲什么脚本说明,功能什么的!只讲使用方法,其他的可以去Gitee看,去Github看. 脚本虽然支持Boot和UEFI,但是我打算一起讲,因为它们安装时的区别,只有3处不同. 第一步 先 ...

  2. Kubernetes中Pod健康检查

    目录 1.何为健康检查 2.探针分类 2.1.LivenessProbe探针(存活性探测) 2.2.ReadinessProbe探针(就绪型探测) 3.探针实现方法 3.1.Container Exe ...

  3. android 练习效果(界面一)

  4. 【HDU5934】Bomb——有向图强连通分量+重建图

    题目大意 二维平面上有 n 个爆炸桶,i−thi-thi−th爆炸桶位置为 (xi,yi)(x_i, y_i)(xi​,yi​) 爆炸范围为 rir_iri​ ,且需要 cic_ici​ 的价格引爆, ...

  5. java 实现全排列

    public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = n ...

  6. AI的博弈论,一份插图教程

    介绍 我想先问一个简单的问题--你能认出下图中的两个人吗? 我肯定你说对了.对于我们这些早期数学发烧友来说,电影<美丽心灵>(A Beautiful Mind)已经深深地印在了我们的记忆中 ...

  7. CSS3 - 新单位vw、vh、vmin、vmax使用详解

    参考文章出自:https://www.hangge.com/blog/cache/detail_1715.html

  8. (连续的矩形)HDU - 1506

    题意:7 2 1 4 5 1 3 3  直接讲数据 :给出7个矩形的高,底长都为1,求最大的连通的矩形块的面积 思路:如果暴力的话肯定超时,有一个特别巧妙的预处理,如果我们知道每一个矩形的左右两边能延 ...

  9. Spring 事务注意事项

    使用事务注意事项 1,事务是程序运行如果没有错误,会自动提交事物,如果程序运行发生异常,则会自动回滚. 如果使用了try捕获异常时.一定要在catch里面手动回滚. 事务手动回滚代码 Transact ...

  10. if-else、switch、while、for

    文章主要会涉及如下几个问题: if-else 和 switch-case 两者相比谁的效率会高些?在日常开发中该如何抉择? 如何基于赫夫曼树结构减少 if-else 分支判断次数? 如何巧妙的应用 d ...