python算法演练_One Rule 算法(详解)


Posted in Python onMay 17, 2017

这样某一个特征只有0和1两种取值,数据集有三个类别。当取0的时候,假如类别A有20个这样的个体,类别B有60个这样的个体,类别C有20个这样的个体。所以,这个特征为0时,最有可能的是类别B,但是,还是有40个个体不在B类别中,所以,将这个特征为0分到类别B中的错误率是40%。然后,将所有的特征统计完,计算所有的特征错误率,再选择错误率最低的特征作为唯一的分类准则——这就是OneR。

现在用代码来实现算法。

# OneR算法实现
import numpy as np
from sklearn.datasets import load_iris
# 加载iris数据集
dataset = load_iris()
# 加载iris数据集中的data数组(数据集的特征)
X = dataset.data
# 加载iris数据集中的target数组(数据集的类别)
y_true = dataset.target
# 计算每一项特征的平均值
attribute_means = X.mean(axis=0)
# 与平均值比较,大于等于的为“1”,小于的为“0”.将连续性的特征值变为离散性的类别型。
x = np.array(X >= attribute_means, dtype="int")


from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y_true, random_state=14)
from operator import itemgetter
from collections import defaultdict
# 找到一个特征下的不同值的所属的类别。
def train_feature_class(x, y_true, feature_index, feature_values):
  num_class = defaultdict(int)
  for sample, y in zip(x, y_true):
    if sample[feature_index] == feature_values:
      num_class[y] += 1
  # 进行排序,找出最多的类别。按从大到小排列
  sorted_num_class = sorted(num_class.items(), key=itemgetter(1), reverse=True)
  most_frequent_class = sorted_num_class[0][0]
  error = sum(value_num for class_num , value_num in sorted_num_class if class_num != most_frequent_class)
  return most_frequent_class, error
# print train_feature_class(x_train, y_train, 0, 1)
# 接着定义一个以特征为自变量的函数,找出错误率最低的最佳的特征,以及该特征下的各特征值所属的类别。
def train_feature(x, y_true, feature_index):
  n_sample, n_feature = x.shape
  assert 0 <= feature_index < n_feature
  value = set(x[:, feature_index])
  predictors = {}
  errors = []
  for current_value in value:
    most_frequent_class, error = train_feature_class(x, y_true, feature_index, current_value)
    predictors[current_value] = most_frequent_class
    errors.append(error)
  total_error = sum(errors)
  return predictors, total_error
# 找到所有特征下的各特征值的类别,格式就如:{0:({0: 0, 1: 2}, 41)}首先为一个字典,字典的键是某个特征,字典的值由一个集合构成,这个集合又是由一个字典和一个值组成,字典的键是特征值,字典的值为类别,最后一个单独的值是错误率。
all_predictors = {feature: train_feature(x_train, y_train, feature) for feature in xrange(x_train.shape[1])}
# print all_predictors
# 筛选出每个特征下的错误率出来
errors = {feature: error for feature, (mapping, error) in all_predictors.items()}
# 对错误率排序,得到最优的特征和最低的错误率,以此为模型和规则。这就是one Rule(OneR)算法。
best_feature, best_error = sorted(errors.items(), key=itemgetter(1), reverse=False)[0]
# print "The best model is based on feature {0} and has error {1:.2f}".format(best_feature, best_error)
# print all_predictors[best_feature][0]
# 建立模型
model = {"feature": best_feature, "predictor": all_predictors[best_feature][0]}
# print model
# 开始测试——对最优特征下的特征值所属类别进行分类。
def predict(x_test, model):
  feature = model["feature"]
  predictor = model["predictor"]
  y_predictor = np.array([predictor[int(sample[feature])] for sample in x_test])
  return y_predictor

y_predictor = predict(x_test, model)
# print y_predictor
# 在这个最优特征下,各特征值的所属类别与测试数据集相对比,得到准确率。
accuracy = np.mean(y_predictor == y_test) * 100
print "The test accuracy is {0:.2f}%".format(accuracy)

from sklearn.metrics import classification_report

# print(classification_report(y_test, y_predictor))

总结:OneR算法,我在最开始的以为它是找到一个错误率最低的特征之后可以判断所有特征的分类,其实,现在明白它只能判断这个特征下的各特征值的分类,所以,明显它会有一些局限性。只是说它比较快捷也比较简单明了。但是,还是得是情况而判断是否使用它。

class      precision recall f1-score support

0              0.94     1.00    0.97       17
1              0.00     0.00    0.00       13
2              0.40     1.00    0.57        8

avg / total 0.51     0.66    0.55       38

注:

# 在上面代码中。
for sample in x_test:
print sample[0]
# 得到的是x_test的第一列数据。而用下面的代码得到的是x_test的第一行数据。
print x_test[0]
# 注意两者区别

以上这篇python算法演练_One Rule 算法(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中删除文件的程序代码
Mar 13 Python
Python数组条件过滤filter函数使用示例
Jul 22 Python
python通过索引遍历列表的方法
May 04 Python
Python抽象类的新写法
Jun 18 Python
Python 读取指定文件夹下的所有图像方法
Apr 27 Python
对python判断ip是否可达的实例详解
Jan 31 Python
深度辨析Python的eval()与exec()的方法
Mar 26 Python
python实现对服务器脚本敏感信息的加密解密功能
Aug 13 Python
python实现KNN分类算法
Oct 16 Python
Python3.7实现验证码登录方式代码实例
Feb 14 Python
解决Keyerror ''acc'' KeyError: ''val_acc''问题
Jun 18 Python
Django后端分离 使用element-ui文件上传方式
Jul 12 Python
浅谈pyhton学习中出现的各种问题(新手必看)
May 17 #Python
Python入门_学会创建并调用函数的方法
May 16 #Python
Python入门_浅谈逻辑判断与运算符
May 16 #Python
Python入门_条件控制(详解)
May 16 #Python
Python入门_浅谈for循环、while循环
May 16 #Python
Python入门_浅谈数据结构的4种基本类型
May 16 #Python
Python入门_浅谈字符串的分片与索引、字符串的方法
May 16 #Python
You might like
PHP面向对象的使用教程 简单数据库连接
2006/11/25 PHP
PHP获取文件的MD5值并判断是否被修改的例子
2014/06/19 PHP
PHP遍历目录函数opendir()、readdir()、closedir()、rewinddir()总结
2014/11/18 PHP
JS Timing
2007/04/21 Javascript
JavaScript sup方法入门实例(把字符串显示为上标)
2014/10/20 Javascript
javascript实现通过表格绘制颜色填充矩形的方法
2015/04/21 Javascript
JS实现的左侧竖向滑动菜单效果代码
2015/10/19 Javascript
Bootstrap实现响应式导航栏效果
2015/12/28 Javascript
JavaScript检测原始值、引用值、属性
2016/06/20 Javascript
JS将unicode码转中文方法
2017/05/08 Javascript
jQuery选择器之属性过滤选择器详解
2017/09/28 jQuery
JavaScript判断变量名是否存在数组中的实例
2017/12/28 Javascript
jQuery实现数字自动增加或者减少的动画效果示例
2018/12/11 jQuery
详解Vue.js v-for不支持IE9的解决方法
2018/12/29 Javascript
jQuery 函数实例分析【函数声明、函数表达式、匿名函数等】
2020/05/19 jQuery
Python抽象类的新写法
2015/06/18 Python
Python+matplotlib+numpy实现在不同平面的二维条形图
2018/01/02 Python
python使用Matplotlib画条形图
2020/03/25 Python
python 动态生成变量名以及动态获取变量的变量名方法
2019/01/20 Python
python requests库爬取豆瓣电视剧数据并保存到本地详解
2019/08/10 Python
QML使用Python的函数过程解析
2019/09/26 Python
python基于FTP实现文件传输相关功能代码实例
2019/09/28 Python
浅谈PyQt5中异步刷新UI和Python多线程总结
2019/12/13 Python
python 利用panda 实现列联表(交叉表)
2021/02/06 Python
汤米巴哈马官方网站:Tommy Bahama
2017/05/13 全球购物
Love, Bonito国际官网:新加坡女装品牌
2021/03/13 全球购物
优秀员工评语
2014/02/10 职场文书
土建施工员岗位职责
2014/07/16 职场文书
党的群众路线对照检查材料
2014/09/22 职场文书
教师党的群众路线教育实践活动个人整改方案
2014/10/31 职场文书
2016年寒假学习心得体会
2015/10/09 职场文书
2016年世界人口日宣传活动总结
2016/04/05 职场文书
《敬重卑微》读后感3篇
2019/11/26 职场文书
pytorch 如何使用amp进行混合精度训练
2021/05/24 Python
JavaScript原型链详解
2021/11/07 Javascript
Python Matplotlib绘制动画的代码详解
2022/05/30 Python