接下来将使用著名的Iris植物分类数据集。这个数据集共有150条植物数据,每条数据都
给出了四个特征:sepal length、sepal width、petal length、petal width(分别表示萼片和花瓣的长
与宽),单位均为cm。这是数据挖掘中的经典数据集之一。该
数据集共有三种类别:Iris Setosa(山鸢尾)、Iris Versicolour(变色鸢尾)和Iris Virginica(维吉尼
亚鸢尾)。我们这里的分类目的是根据植物的特征推测它的种类。

#准备数据集
from sklearn.datasets import load_iris
import numpy as np
dataset = load_iris()
X = dataset.data
y = dataset.target
# print(dataset.DESCR) 查看数据集
attribute_means = X.mean(axis=0)
assert attribute_means.shape == (n_features,)
X_d = np.array(X >= attribute_means,dtype='int')
n_samples, n_features = X.shape
print ("样例的个数为{0}".format(n_samples))
print ("特征的个数为{0}".format(n_features))

数据集中各特征值为连续型,也就是有无数个可能的值。测量得到的数据就是这个样子,比
如,测量结果可能是1、1.2或1.25,等等。连续值的另一个特点是,如果两个值相近,表示相似
度很大。一种萼片长1.2cm的植物跟一种萼片宽1.25cm的植物很相像。
与此相反,类别的取值为离散型。虽然常用数字表示类别,但是类别值不能根据数值大小比
较相似性。Iris数据集用不同的数字表示不同的类别,比如类别0、1、2分别表示Iris Setosa、Iris
Versicolour、Iris Virginica。但是这不能说明前两种植物,要比第一种和第三种更相近——尽管单
看表示类别的数字时确实如此。在这里,数字表示类别,只能用来判断两种植物是否属于同一种
数据集的特征为连续值,而我们即将使用的算法使用类别型特征值,因此我们需要把连续值
转变为类别型,这个过程叫作离散化。
最简单的离散化算法,莫过于确定一个阈值,将低于该阈值的特征值置为0,高于阈值的置
为1。我们把某项特征的阈值设定为该特征所有特征值的均值。每个特征的均值计算方法如下。

attribute_means = X.mean(axis=0)
X_d = np.array(X >= attribute_means,dtype='int')

OneR算法

OneR算法的思路很简单,它根据已有数据中,具有相同特征值的个体最可能属于哪个类别
进行分类。OneR是One Rule(一条规则)的简写,表示我们只选取四个特征中分类效果最好的一
个用作分类依据。

训练数据和测试数据

from sklearn.model_selection import train_test_split# Set the random state to the same number to get the same results as in the book
random_state = 14X_train, X_test, y_train, y_test = train_test_split(X_d, y, random_state=random_state)
print("There are {} training samples".format(X_train.shape))
print("There are {} testing samples".format(X_test.shape))

实现代码

from collections import defaultdict
from operator import itemgetterdef train(X, y_true, feature):# Check that variable is a valid numbern_samples, n_features = X.shapeassert 0 <= feature < n_features# Get all of the unique values that this variable hasvalues = set(X[:,feature])# Stores the predictors array that is returnedpredictors = 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_classerrors.append(error)# Compute the total error of using this feature to classify ontotal_error = sum(errors)return predictors, total_error# Compute what our predictors say each sample is based on its value
#y_predicted = np.array([predictors[sample[feature]] for sample in X])def train_feature_value(X, y_true, feature, value):# Create a simple dictionary to count how frequency they give certain predictionsclass_counts = defaultdict(int)# Iterate through each sample and count the frequency of each class/value pairfor sample, y in zip(X, y_true):if sample[feature] == value:class_counts[y] += 1# Now get the best one by sorting (highest first) and choosing the first itemsorted_class_counts = sorted(class_counts.items(), key=itemgetter(1), reverse=True)most_frequent_class = sorted_class_counts[0][0]# The error is the number of samples that do not classify as the most frequent class# *and* have the feature value.n_samples = X.shape[1]error = sum([class_count for class_value, class_count in class_counts.items()if class_value != most_frequent_class])return most_frequent_class, error
# Compute all of the predictors
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()}
# Now choose the best and save that as "model"
# Sort by error
best_variable, best_error = sorted(errors.items(), key=itemgetter(1))[0]
print("The best model is based on variable {0} and has error {1:.2f}".format(best_variable, best_error))# Choose the bset model
model = {'variable': best_variable,'predictor': all_predictors[best_variable][0]}
print(model)
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)
# Compute the accuracy by taking the mean of the amounts that y_predicted is equal to y_test
accuracy = np.mean(y_predicted == y_test) * 100
print("The test accuracy is {:.1f}%".format(accuracy))from sklearn.metrics import classification_report
print(classification_report(y_test, y_predicted))

Python数据挖掘(2)简单的分类问题相关推荐

  1. python输入水果求个数问题_水果爱好者:用Python解决一个简单的分类问题

    作者 | Ocktavia Nurima Putri 来源 | Medium 编辑 | 代码医生团队 在这篇文章中,将使用Scikit-learn在Python中实现几种机器学习算法.将使用一个简单的 ...

  2. Python数据挖掘学习笔记】九.回归模型LinearRegression简单分析氧化物数据

    #2018-03-23 16:26:20 March Friday the 12 week, the 082 day SZ SSMR [Python数据挖掘学习笔记]九.回归模型LinearRegre ...

  3. Python数据挖掘入门与实践-OneR分类算法

    Python数据挖掘入门与实践-OneR分类算法 OneR算法 OneR算法是根据已有的数据中,具有相同特征值的个体最可能属于哪个类别进行分类. 在本例中,只需选区Iris是个特征中分类效果最好的一个 ...

  4. Python数据挖掘学习——鸢尾花分类、OneR算法

    <Python数据挖掘入门与实践>第一章内容,实现一个简单的分类处理,实现OneR算法. OneR算法的思路很简单,它根据已有的数据中,具有相同特征值的个体最可能属于哪个类别进行分类.On ...

  5. 【Python数据挖掘课程】九.回归模型LinearRegression简单分析氧化物数据

    这篇文章主要介绍三个知识点,也是我<数据挖掘与分析>课程讲课的内容.同时主要参考学生的课程提交作业内容进行讲述,包括:         1.回归模型及基础知识:         2.UCI ...

  6. python数据挖掘与入门实践(2.2)用sciket-learn估计器分类

    接python数据挖掘与入门实践(2.1)用sciket-learn估计器分类 三.运行算法 交叉验证一般分为三类:double-fold CV 即经常所说的2折交叉:10-fold交叉和LOO(le ...

  7. python 数据挖掘 之 对数据进行简单预处理(1)

    python 数据挖掘 之 对数据进行简单预处理 在我们对数据集进行数据挖掘之前,需要先对数据集进行简单的处理,让数据集变得更规范更具有代表性. 对数据集进行的预处理又许多种,接下来我就简单说几种常用 ...

  8. 带你入门Python数据挖掘与机器学习(附代码、实例)

    作者:韦玮 来源:Python爱好者社区 本文共7800字,建议阅读10+分钟. 本文结合代码实例待你上手python数据挖掘和机器学习技术. 本文包含了五个知识点: 1. 数据挖掘与机器学习技术简介 ...

  9. python数据挖掘与机器学习实战_Python数据挖掘与机器学习技术入门实战(1)

    什么是数据挖掘?数据挖掘指的是对现有的一些数据进行相应的处理和分析,最终得到数据与数据之间深层次关系的一种技术.例如在对超市货品进行摆放时,牛奶到底是和面包摆放在一起销量更高,还是和其他商品摆在一起销 ...

  10. python 数据挖掘论文,Orange:一个基于 Python 的数据挖掘和机器学习平台

    Orange 简介 Orange 是一个开源的数据挖掘和机器学习软件.Orange 基于 Python 和 C/C++ 开发,提供了一系列的数据探索.可视化.预处理以及建模组件. Orange 拥有漂 ...

最新文章

  1. linux系统中指定端口连接数限制
  2. RuntimeError: each element in list of batch should be of equal size
  3. 计算机组成原理的中央控制器,计算机组成原理第六章中央控制器(6-7,8,9).pdf
  4. Tungsten Fabric SDN — 报文转发流程
  5. .NET6之MiniAPI(三):Response
  6. MySQL UPDATE 语句一个“经典”的坑
  7. 聊一下CPU占用高的解决方案
  8. java mian 方法_Java mian函数
  9. eclipse中git的author和commiter的修改
  10. 电脑安装ubuntu linux操作系统
  11. 高德地图:No implementation found for void com.autonavi.base.ae.gmap.GLMapEngine.nativeInitParam
  12. TCL语言语法简介(上)
  13. 云计算中的第二个boss——网络虚拟化
  14. pat 训练题 7-5 基友团 (25分) 暴力判团和最大团
  15. js中获得月份getmonth()+1,为什么要加1?
  16. 2021年高处安装、维护、拆除新版试题及高处安装、维护、拆除考试试卷
  17. dlib重新训练dlib_face_recognition_resnet_model_v1.dat
  18. winRE环境下使用xcopy时显示未找到文件
  19. 用新开放的 notion api 结合 python 爬虫搞个羊毛线报页面
  20. easyExcel设置水印

热门文章

  1. List集合关于Stream的操作
  2. 阿里云应用防火墙WAF部署和使用
  3. 岳阳的第一场雪,我这辈子的第一场雪。
  4. 新年亲朋好友最经典的“互相伤害”,你中过几条?
  5. 快速启动软件之 Rolan ,你真的会用?
  6. 对于因果模型的常见评估函数:SHD 和 FDR
  7. CSP 201809-2 买菜
  8. win10用易语言需要C环境,win10系统易语言打开支持库配置就崩溃的具体教程
  9. 电商流水的3大策略:流量、转化率、客单价
  10. 在用户输入手机号或者要求输入纯数字时,输入法自动切换到数字的代码