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转码问题的解决方法
Oct 07 Python
python和shell变量互相传递的几种方法
Nov 20 Python
python3+PyQt5重新实现QT事件处理程序
Apr 19 Python
python 对key为时间的dict排序方法
Oct 17 Python
python面向对象入门教程之从代码复用开始(一)
Dec 11 Python
python 修改本地网络配置的方法
Aug 14 Python
python3 实现的对象与json相互转换操作示例
Aug 17 Python
如何关掉pycharm中的python console(图解)
Oct 31 Python
详解pycharm连接不上mysql数据库的解决办法
Jan 10 Python
python如何判断IP地址合法性
Apr 05 Python
python利用tkinter实现图片格式转换的示例
Sep 28 Python
python Tkinter模块使用方法详解
Apr 07 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
PHP中通过ADO调用Access数据库的方法测试不通过
2006/12/31 PHP
php学习笔记 面向对象中[接口]与[多态性]的应用
2011/06/16 PHP
PHP字符串中特殊符号的过滤方法介绍
2014/02/18 PHP
[原创]php token使用与验证示例【测试可用】
2017/08/30 PHP
Yii2框架类自动加载机制实例分析
2018/05/02 PHP
qTip 基于JQuery的Tooltip插件[兼容性好]
2010/09/01 Javascript
遍历DOM对象内的元素属性示例代码
2014/02/08 Javascript
js给网页加上背景音乐及选择音效的方法
2015/03/03 Javascript
jQuery获得包含margin的outerWidth和outerHeight的方法
2015/03/25 Javascript
jQuery实现的背景动态变化导航菜单效果
2015/08/24 Javascript
Bootstrap每天必学之按钮(一)
2015/11/24 Javascript
三个js循环的关键字示例(for与while)
2016/02/16 Javascript
Nodejs进阶:基于express+multer的文件上传实例
2016/11/21 NodeJs
详解前端自动化工具gulp自动添加版本号
2016/12/20 Javascript
纯javaScript、jQuery实现个性化图片轮播【推荐】
2017/01/08 Javascript
javascript中BOM基础知识总结
2017/02/14 Javascript
详解Nodejs之npm&amp;package.json
2017/06/15 NodeJs
vue使用pdfjs显示PDF可复制的实现方法
2018/12/14 Javascript
Vue.js递归组件实现组织架构树和选人功能案例分析
2019/07/03 Javascript
如何给element添加一个抽屉组件的方法步骤
2019/07/14 Javascript
微信小程序实现滑动翻页效果(完整代码)
2019/12/06 Javascript
[05:07]DOTA2英雄梦之声_第14期_暗影恶魔
2014/06/20 DOTA
Python中easy_install 和 pip 的安装及使用
2017/06/05 Python
Python使用cx_Freeze库生成msi格式安装文件的方法
2018/07/10 Python
Python http接口自动化测试框架实现方法示例
2018/12/06 Python
python实发邮件实例详解
2019/11/11 Python
浅谈Python3中print函数的换行
2020/08/05 Python
虚拟环境及venv和virtualenv的区别说明
2021/02/05 Python
Kent & Curwen:与大卫·贝克汉姆合作
2017/06/13 全球购物
怎样写好自我鉴定
2013/12/04 职场文书
标准化管理实施方案
2014/02/25 职场文书
党员政治学习材料
2014/05/14 职场文书
2014国庆节国旗下演讲稿(精选版)
2014/09/26 职场文书
心术观后感
2015/06/11 职场文书
SQL Server数据定义——模式与基本表操作
2021/04/05 SQL Server
一次项目中Thinkphp绕过禁用函数的实战记录
2021/11/17 PHP