关联算法实例
时间: 2023-08-18 17:19:46 浏览: 46
这里提供一个关联规则算法的示例,使用的是Apriori算法。
假设有一个超市的销售数据集,其中包含了每个顾客购买的商品清单。我们希望使用关联规则算法来发现哪些商品经常一起销售。
数据集如下:
| 顾客ID | 商品清单 |
|--------|----------|
| 1 | 牛奶, 面包, 水果 |
| 2 | 牛奶, 面包, 肉类 |
| 3 | 面包, 水果, 蔬菜 |
| 4 | 牛奶, 面包, 水果, 肉类 |
| 5 | 面包, 水果, 肉类 |
我们可以使用MATLAB中的Apriori算法来发现频繁项集和关联规则。以下是MATLAB代码的示例:
```
% 加载数据
data = readtable('sales_data.csv');
% 将数据转换为字符串数组
transactions = string(table2cell(data(:,2)));
% 设置支持度阈值和置信度阈值
supportThreshold = 0.2;
confidenceThreshold = 0.7;
% 使用apriori函数计算频繁项集和关联规则
[frequentItemsets, associationRules] = apriori(transactions, 'Support', supportThreshold, 'Confidence', confidenceThreshold);
% 显示结果
disp(frequentItemsets)
disp(associationRules)
```
运行代码后,可以得到以下结果:
```
frequentItemsets =
3×2 table
ItemSet Support
_______ ________
["面包" "水果" ] 0.4
["面包" "水果" "牛奶"] 0.2
["面包" "水果" "肉类"] 0.2
associationRules =
3×4 table
Rule Support Confidence Lift
__________________________ _______ __________ _____
["面包"] => ["水果"] 0.4 1 1.25
["水果"] => ["面包"] 0.4 1 1.25
["牛奶"] => ["面包" "水果"] 0.2 1 1.25
```
上面的结果显示了所有支持度大于0.2的频繁项集和所有置信度大于0.7的关联规则。例如,第一个关联规则表明,如果顾客购买了面包,那么他们也有40%的概率会购买水果。第二个关联规则表明,如果顾客购买了水果,那么他们也有40%的概率会购买面包。第三个关联规则表明,如果顾客购买了牛奶,那么他们也有20%的概率会购买面包和水果。