购物篮分析是一个很经典的数据挖掘案例,运用到了Apriori算法。下面从网上下载的一超市某月份的数据库,利用Apriori算法进行管理分析。例子使用Python+MongoDB

  处理过程1 数据建模(将Excel中的数据写入到MongoDB数据库), 2 从数据库中读取数据进行分析。

  Excel文件http://download.csdn.net/detail/artscrafts/6805689

  案例配置文件 setting.py

  1. data_source = 'supermarket.xls'
  2. host = 'localhost'
  3. port = 27017
  4. db_name = 'shopping_basket'
  5. items_name = 'goods_items'
  6. record_name = 'transaction_record'

  读取Excel数据到MongoDB中 load_basket.py

  1. from xlrd import open_workbook
  2. from pymongo import MongoClient
  3. import setting
  4.  
  5. wb = open_workbook(setting.data_source, encoding_override='utf-8')
  6. client = MongoClient(setting.host, setting.port)
  7. db = client[setting.db_name]
  8. items = []
  9.  
  10. #read xls
  11. def read_one_line(workbook, sheet_index=0, row_index=0, start_col_index=0):
  12. sheet = workbook.sheets()[0]
  13. max_row = sheet.nrows
  14. max_col = sheet.ncols
  15. start_col_index = (start_col_index if (start_col_index > 0 and start_col_index <= max_col) else max_col)
  16. if row_index < 0 or row_index >= max_row:
  17. raise IndexError()
  18. for col_index in xrange(start_col_index, max_col):
  19. yield sheet.cell(row_index, col_index).value
  20.  
  21. #read xls
  22. def readlines(workbook, sheet_index=0, start_row_index=0, end_row_index=None, start_col_index=0, end_col_index=None):
  23. sheet = workbook.sheets()[sheet_index]
  24. max_row = sheet.nrows
  25. max_col = sheet.ncols
  26. end_row_index = (end_row_index if end_row_index else max_row)
  27. end_col_index = (end_col_index if end_col_index else max_col)
  28. for row_index in xrange(start_row_index, end_row_index):
  29. yield [sheet.cell(row_index, col_index).value for col_index in xrange(start_col_index, end_col_index)]
  30.  
  31. #from xls to mongodb
  32. def load_items():
  33. collection = db[setting.items_name]
  34. items_line = read_one_line(wb, row_index=1, start_col_index=1)
  35. id = 1
  36. tmp = []
  37. for item in items_line:
  38. if id % 100 == 0:
  39. collection.insert(tmp)
  40. tmp = []
  41. tmp.append({'id':id, 'name':item})
  42. items.append(item)
  43. id += 1
  44.  
  45. # from xls to mongodb
  46. def load_record():
  47. collection = db[setting.record_name]
  48. lines = readlines(wb,start_row_index=2, start_col_index = 1)
  49. tmp = []
  50. id = 1
  51. for line in lines:
  52. if id % 100 == 0:
  53. collection.insert(tmp)
  54. tmp = []
  55. tmp.append({'id':id, 'items':[items[i] for i in xrange(len(line)) if line[i] == 'T']})
  56. id += 1
  57.  
  58. def main():
  59. print '........start loading........'
  60. load_items()
  61. load_record()
  62. client.close()
  63. print '.........end loading.........'
  64.  
  65. if __name__ == '__main__':
  66. main()

  进行数据分析 analysis_basket.py

  1. #Apriori
  2. from pymongo import MongoClient
  3. import setting
  4.  
  5. client = MongoClient(setting.host, setting.port)
  6. db = client[setting.db_name]
  7. data = []
  8.  
  9. #from mongodb to items
  10. def filldata():
  11. collection = db[setting.record_name]
  12. cur = collection.find()
  13. for row in cur:
  14. data.append(row['items'])
  15.  
  16. def connect(items):
  17. result = {}
  18. keys = items.keys()
  19. length = len(keys)
  20. for i in range(length):
  21. prev = keys[i][:len(keys[i]) - 1]
  22. for j in range(i + 1, length):
  23. tmp = keys[j][:len(keys[j]) - 1]
  24. if prev == tmp:
  25. key = keys[i] + (keys[j][len(keys[i]) - 1],)
  26. result[key] = getsupp(key)
  27. else:
  28. break
  29. return result
  30.  
  31. def pruning(items, minsupp):
  32. result = {}
  33. for key in items.keys():
  34. if items[key] >= minsupp:
  35. result[key] = items[key]
  36. return result
  37.  
  38. def contain(par, sub):
  39. for v in sub:
  40. if not v in par:
  41. return False
  42. return True
  43.  
  44. def getsupp(item):
  45. supp = 0
  46. for row in data:
  47. if contain(row, item):
  48. supp+=1
  49. return supp
  50.  
  51. def apriori(data, minsupp, k):
  52. candidate_set = {}
  53. for row in data:
  54. for i in row:
  55. key = (i,)
  56. candidate_set[key] = candidate_set.get(key, 0) + 1
  57. frequently_set = pruning(candidate_set, minsupp)
  58. result = {}
  59. result['k=1'] = frequently_set
  60. for n in range(2, k):
  61. candidate_set = connect(frequently_set)
  62. frequently_set = pruning(candidate_set, minsupp)
  63. if len(frequently_set) <= 1:
  64. return result
  65. result['K=' + str(n)] = frequently_set
  66. return result
  67.  
  68. def main():
  69. filldata()
  70. client.close()
  71. res = apriori(data, 30, 8)
  72.  
  73. if __name__ == '__main__':
  74. main()

  

  

Apriori算法在购物篮分析中的运用的更多相关文章

  1. 数据挖掘算法之-关联规则挖掘(Association Rule)(购物篮分析)

    在各种数据挖掘算法中,关联规则挖掘算是比較重要的一种,尤其是受购物篮分析的影响,关联规则被应用到非常多实际业务中,本文对关联规则挖掘做一个小的总结. 首先,和聚类算法一样,关联规则挖掘属于无监督学习方 ...

  2. 数据算法 --hadoop/spark数据处理技巧 --(5.移动平均 6. 数据挖掘之购物篮分析MBA)

    五.移动平均 多个连续周期的时间序列数据平均值(按相同时间间隔得到的观察值,如每小时一次或每天一次)称为移动平均.之所以称之为移动,是因为随着新的时间序列数据的到来,要不断重新计算这个平均值,由于会删 ...

  3. R语言和数据分析十大:购物篮分析

    提到数据挖掘,我们的第一个反应是之前的啤酒和尿布的故事听说过,这个故事是一个典型的数据挖掘关联规则.篮分析的传统线性回归之间的主要差别的差别,对于离散数据的相关性分析: 常见的关联规则: 关联规则:牛 ...

  4. 108_Power Pivot购物篮分析分组GENERATE之笛卡尔积、排列、组合

    博客:www.jiaopengzi.com 焦棚子的文章目录 请点击下载附件 1.背景 昨天在看论坛帖子时候(帖子),看到一个关于SKU组合的问题,有很多M大佬都给出了处理方案,于是想用dax也写一个 ...

  5. 关联规则之Aprior算法(购物篮分析)

    0.支持度与置信度 <mahout实战>与<机器学习实战>一起该买的记录数占所有商品记录总数的比例——支持度(整体) 买了<mahout实战>与<机器学习实战 ...

  6. Apriori算法第二篇----详细分析和代码实现

    1 Apriori介绍 Apriori算法使用频繁项集的先验知识,使用一种称作逐层搜索的迭代方法,k项集用于探索(k+1)项集.首先,通过扫描事务(交易)记录,找出所有的频繁1项集,该集合记做L1,然 ...

  7. 016 Spark中关于购物篮的设计,以及优化(两个点)

    一:介绍 1.购物篮的定义 2.适用场景 3.相关概念 4.步骤 5.编程实现 6.步骤 二:程序 1.程序 package com.ibeifeng.senior.mba.association i ...

  8. Apriori算法第一篇

    摘要: Apriori算法是产生k项高频项目组的一般手段.算法概要:首先产生k项高频项目集合Lk,自身链接形成k+1项的项目结合C(k+1),然后剪枝(去掉以前去掉的不满足支持度的高频),生成K=1项 ...

  9. Apriori算法的C++实现

    Apriori是经典的购物篮分析算法.该算法用SQL实现难度较大,所以考虑用C++实现. 花了两天,代码例如以下.原创转载请注明出处 //Apriori.c #include<iostream& ...

随机推荐

  1. SQL SERVER 查询死锁

    USE mastergo CREATE PROCEDURE [dbo].[sp_who_lock]AS     BEGIN        DECLARE @spid INT ,             ...

  2. 修正android cocos2dx项目当点击属性时提示错误的问题

    近期在用cocos2dx 3.x版本号做android版本号的时候,出现点击project-属性-C/C++ builder的时候会提示 The currently displayed paye co ...

  3. PowerMock注解PowerMockIgnore的使用方法

    故事要从一个异常开始,某天我在开发一个加密.解密特性,算法使用的是3DES,样例代码如下. package org.jackie.study.powermock; import java.io.Uns ...

  4. android_handler(三)

    这篇记录 android 消息机制中,MainThread 向 WorkThread 发送消息.( MainThread → WorkThread ) 步骤: 1.准备looper对象 2.在子线程中 ...

  5. 程序猿的编程神器 - vim

    一.官方文档: 当你首次安装好 Vim 之后.能够用 :help tutor 或者 :help tutor@cn 命令.进入一个30分钟的 Vim 新手教程.你也能够下载一个 Vim Document ...

  6. 用apache的httpclient发请求和接受数据

    此处发请求的是用httpclient4,请自己下载所需要的jar包. 发post请求,并得到数据. String url = "http://localhost:8080/lee" ...

  7. linux下配置php Apache mysql

    一 Apache部分 http://www.cnblogs.com/bluewelkin/p/3805107.html里面是纠正了原文的一些小错误,即可正常安装 1.su 命令2.安装apr-1.3. ...

  8. IOS Remote Notification

    1. 本地证书合成 rm *.pem echo "export cert..." openssl pkcs12 -clcerts -nokeys -out push_cert.pe ...

  9. Sqlserver中实现oralce 数据库的rownumber

    引用自:http://cai555.javaeye.com/blog/466033 方法1: with temp as ( select row_number() over(order by city ...

  10. WPF学习之资源-Resources

    WPF学习之资源-Resources WPF通过资源来保存一些可以被重复利用的样式,对象定义以及一些传统的资源如二进制数据,图片等等,而在其支持上也更能体现出这些资源定义的优越性.比如通过Resour ...