Python之数据挖掘

栏目: Python · 发布时间: 7年前

内容简介:Python之数据挖掘

自用笔记,目前在看《Learning Data Mining with Python 2nd Edition》。

在图书馆发现这本书(第一版译本),顿时就吸引了我的注意力,之前学校也开过《数据挖掘》的课,蛮有意思的,也就纯理论相关,一直没实践。

然后通过书上给的源代码链接,发现这本书今年4月份出了第二版,就下了电子版来研究了。

Getting Started with Data Mining

affinity analysis

第一个例子是关于 affinity analysis ,给出历史订单,可以找出如下规则:

当用户买了X( premise ),有多大可能性买Y( conclusion )。

  • 支持度( support ): 历史订单中出现premise->conclusion的个数
  • 置信度( confidence ):支持度/历史订单中出现premise的个数

最后可以根据置信度从大到小排序,从而帮助我们做出决策。

实现OneR算法

第二个例子是分类问题,通过 scikit-learn 库的数据集IRIS(花的数据集,有3种类别)来介绍OneR( One Rule )算法,也就是通过选择 一个 最好的特征来判断类别。

该数据集有150个样本,4个特征,以及每个样本对应的类别。首先对各个特征值进行 离散化 ,书上是通过各个特征值的均值来作为阈值,大于均值为1,否则为0,这样各个特征值只有2种数值了。

然后实现OneR算法:

  • 依次遍历每个特征
    • 遍历特征的每个值( train_feature_value )
      • 根据所有样本中的特征为该值找出最频繁的类
      • 计算错误的样本(不属于最频繁的类)个数
    • 计算该特征总的错误个数
  • 使用错误个数最少的特征来分类
# X样本, y_true样本对应的类别,feature选择的特征,value特征的值
def train_feature_value(X, y_true, feature, value):
    class_count = defaultdict(int)
    for sample, cls in zip(X, y_true):
        if sample[feature] == value:
            class_count[cls] += 1
    most_frequent_class = sorted(class_count.items(), key=itemgetter(1), reverse=True)[0][0]
    error = sum([cnt for cls, cnt in class_count.items() if cls != most_frequent_class])
    return most_frequent_class, error

def train(X, y_true, feature):
    n_samples, n_features = X.shape
    values = set(X[:, feature])
    predictors = {}
    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

续…


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Seasoned Schemer

The Seasoned Schemer

Daniel P. Friedman、Matthias Felleisen / The MIT Press / 1995-12-21 / USD 38.00

drawings by Duane Bibbyforeword and afterword by Guy L. Steele Jr.The notion that "thinking about computing is one of the most exciting things the human mind can do" sets both The Little Schemer (form......一起来看看 《The Seasoned Schemer》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具