python机器学习实现oneR算法(以鸢尾data为例)


Posted in Python onMarch 03, 2022

oneR即“一条规则”。oneR算法根据已有的数据中,具有相同特征值的个体最可能属于哪个类别来进行分类。
以鸢尾data为例,该算法实现过程可解读为以下六步:

一、 导包与获取数据

以均值为阈值,将大于或等于阈值的特征标记为1,低于阈值的特征标记为0。

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from collections import defaultdict
from operator import itemgetter
import warnings
from sklearn.metrics import classification_report

# 加载内置iris数据,并保存
dataset = load_iris()  
X = dataset.data
y = dataset.target

attribute_means = X.mean(axis=0)  # 得到一个列表,列表元素个数为特征值个数,列表值为每个特征的均值
X_d = np.array(X >= attribute_means, dtype='int')  # 转bool类型

数据到此已获取完毕,接下来将其划分为训练集和测试集。

二、划分为训练集和测试集

使用默认的0.25作为分割比例。即训练集:测试集=3:1。

X_train, X_test, y_train, y_test = train_test_split(X_d, y, random_state=random_state)

数据描述:
本例中共有四个特征,
原数据集有150个样本,分割后训练集有112个数据,测试集有38个数据。
标签一共分为三类,取值可以是0,1,2。

三、定义函数:获取某特征值出现次数最多的类别及错误率

首先遍历特征的每一个取值,对于每一个特征值,统计它在各个类别中出现的次数。
定义一个函数,有以下四个参数:

  • X, y_true即 训练集数据和标签
  • feature是特征的索引值,可以是0,1,2,3。
  • value是特征可以有的取值,这里为0,1。

该函数的意义在于,对于训练集数据,对于某个特征,依次遍历样本在该特征的真实取值,判断其是否等于特征的某个可以有的取值 (即value)(以0为例)。如果判定成功,则在字典class_counts中记录,以三个类别(0,1,2)中该样本对应的类别为键值,表示该类别出现的次数加一。

首先得到的字典(class_counts)形如:
{0: x1, 1.0: x2, 2.0:x3}
其中元素不一定是三个
x1:类别0中,某个特征feature的特征值为value(0或1)出现的次数
x2:类别0中,某个特征feature的特征值为value(0或1)出现的次数
x3:类别0中,某个特征feature的特征值为value(0或1)出现的次数

然后将class_counts按照值的大小排序,取出指定特征的特征值出现次数最多的类别:most_frequent_class。
该规则即为:该特征的该特征值出现在其出现次数最多的类别上是合理的,出现在其它类别上是错误的。

最后计算该规则的错误率:error
错误率具有该特征的个体在除出现次数最多的类别出现的次数,代表分类规则不适用的个体的数量

最后返回待预测的个体类别错误率

def train_feature_value(X, y_true, feature, value):
    class_counts = defaultdict(int)
    for sample, y_t in zip(X, y_true):
        if sample[feature] == value:
            class_counts[y_t] += 1
    sorted_class_counts = sorted(class_counts.items(), key=itemgetter(1), reverse=True) # 降序
    most_frequent_class = sorted_class_counts[0][0]
    error = sum([class_count for class_value, class_count in class_counts.items()
                 if class_value != most_frequent_class])
    return most_frequent_class, error

返回值most_frequent_class是一个字典, error是一个数字

四、定义函数:获取每个特征值下出现次数最多的类别、错误率

def train(X, y_true, feature):
    n_samples, n_features = X.shape
    assert 0 <= feature < n_features
    # 获取样本中某特征所有可能的取值
    values = set(X[:, feature])
    predictors = dict()
    errors = []
    for current_value in values:
        most_frequent_class, error = train_feature_value(X, y_true, feature, current_value)
        predictors[current_value] = most_frequent_class
        errors.append(error)
    total_error = sum(errors)
    return predictors, total_error

因为most_frequent_class是一个字典,所以predictors是一个键为特征可以的取值(0和1),值为字典most_frequent_class的 字典。
total_error是一个数字,为每个特征值下的错误率的和。

五、调用函数,获取最佳特征值

all_predictors = {variable: train(X_train, y_train, variable) for variable in range(X_train.shape[1])}
Errors = {variable: error for variable, (mapping, error) in all_predictors.items()}
# 找到错误率最低的特征
best_variable, best_error = sorted(Errors.items(), key=itemgetter(1))[0]  # 升序
print("The best model is based on feature {0} and has error {1:.2f}".format(best_variable, best_error))
# 找到最佳特征值,创建model模型
model = {'variable': best_variable,
         'predictor': all_predictors[best_variable][0]}
print(model)

python机器学习实现oneR算法(以鸢尾data为例)

根据代码运行结果,最佳特征值是特征2(索引值为2的feature,即第三个特征)。

对于初学者这里的代码逻辑比较复杂,可以对变量进行逐个打印查看,阅读blog学习时要盯准字眼,细品其逻辑。

print(all_predictors)
print(all_predictors[best_variable])
print(all_predictors[best_variable][0])

python机器学习实现oneR算法(以鸢尾data为例)

六、测试算法

定义预测函数,对测试集数据进行预测

def predict(X_test, model):
    variable = model['variable']
    predictor = model['predictor']
    y_predicted = np.array([predictor[int(sample[variable])] for sample in X_test])
    return y_predicted

# 对测试集数据进行预测
y_predicted = predict(X_test, model)
print(y_predicted)

预测结果:

python机器学习实现oneR算法(以鸢尾data为例)

# 统计预测准确率
accuracy = np.mean(y_predicted == y_test) * 100
print("The test accuracy is {:.1f}%".format(accuracy))

python机器学习实现oneR算法(以鸢尾data为例)

根据打印结果,该模型预测的准确率可达65.8%,对于只有一条规则的oneR算法而言,结果是比较良好的。到此便实现了oneR算法的一次完整应用。

最后,还可以使用classification_report()方法,传入测试集的真实值和预测值,打印出模型评估报告。

# 屏蔽警告
warnings.filterwarnings("ignore") 
# 打印模型评估报告
print(classification_report(y_test, y_predicted))  # 参数为测试集的真实数据和预测数据

python机器学习实现oneR算法(以鸢尾data为例)

 到此这篇关于python机器学习实现oneR算法(以鸢尾data为例)的文章就介绍到这了,更多相关python oneR算法内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
浅谈Python数据类型判断及列表脚本操作
Nov 04 Python
Python3.5编程实现修改IIS WEB.CONFIG的方法示例
Aug 18 Python
JS设计模式之责任链模式实例详解
Feb 03 Python
Python实现的端口扫描功能示例
Apr 08 Python
对numpy中array和asarray的区别详解
Apr 17 Python
python判断计算机是否有网络连接的实例
Dec 15 Python
python内置模块collections知识点总结
Dec 19 Python
python如何操作mysql
Aug 17 Python
Python SMTP发送电子邮件的示例
Sep 23 Python
浅谈anaconda python 版本对应关系
Oct 07 Python
Python爬虫中Selenium实现文件上传
Dec 04 Python
python statsmodel的使用
Dec 21 Python
详解python的异常捕获
Mar 03 #Python
分享提高 Python 代码的可读性的技巧
Mar 03 #Python
使用python创建股票的时间序列可视化分析
Python Pandas读取Excel日期数据的异常处理方法
pytorch中的torch.nn.Conv2d()函数图文详解
Feb 28 #Python
python3中apply函数和lambda函数的使用详解
Feb 28 #Python
你需要掌握的20个Python常用技巧
Feb 28 #Python
You might like
DSP接收机前端设想
2021/03/02 无线电
CodeIgniter生成网站sitemap地图的方法
2013/11/13 PHP
初识php MVC
2014/09/10 PHP
CodeIgniter常用知识点小结
2016/05/26 PHP
Laravel 加载第三方类库的方法
2018/04/20 PHP
PHP PDO数据库操作预处理与注意事项
2019/03/16 PHP
php解决crontab定时任务不能写入文件问题的方法分析
2019/09/16 PHP
javascript陷阱 一不小心你就中招了(字符运算)
2013/11/10 Javascript
js实现背景图片感应鼠标变化的方法
2015/02/28 Javascript
Bootstrap中表单控件状态(验证状态)
2016/08/04 Javascript
AngularJS使用自定义指令替代ng-repeat的方法
2016/09/17 Javascript
AngularJS实现表单验证功能详解
2017/10/12 Javascript
nodejs项目windows下开机自启动的方法
2017/11/22 NodeJs
vue2.0与bootstrap3实现列表分页效果
2017/11/28 Javascript
React 使用browserHistory项目访问404问题解决
2018/06/01 Javascript
详解React服务端渲染从入门到精通
2019/03/28 Javascript
原生JS实现动态添加新元素、删除元素方法
2019/05/05 Javascript
antd 表格列宽自适应方法以及错误处理操作
2020/10/27 Javascript
[03:15]DOTA2-DPC中国联赛1月22日Recap集锦
2021/03/11 DOTA
Python open()文件处理使用介绍
2014/11/30 Python
python cx_Oracle模块的安装和使用详细介绍
2017/02/13 Python
python中如何使用朴素贝叶斯算法
2017/04/06 Python
python matplotlib 在指定的两个点之间连线方法
2018/05/25 Python
Windows 8.1 64bit下搭建 Scrapy 0.22 环境
2018/11/18 Python
pygame游戏之旅 如何制作游戏障碍
2018/11/20 Python
Pandas之ReIndex重新索引的实现
2019/06/25 Python
python自动循环定时开关机(非重启)测试
2019/08/26 Python
python多线程扫描端口(线程池)
2019/09/04 Python
python3中for循环踩过的坑记录
2020/12/14 Python
"引用"与指针的区别是什么
2016/09/07 面试题
C#和SQL Server的面试题
2016/08/12 面试题
顶碗少年教学反思
2014/02/21 职场文书
股权收购意向书
2014/04/01 职场文书
学习十八大的心得体会
2014/09/01 职场文书
法人身份证明书
2014/10/08 职场文书
2015暑假打工实践报告
2015/07/13 职场文书