Created
August 16, 2015 03:17
-
-
Save taise/9d3e6cb817b4ccf7aa7e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| import numpy as np | |
| data_set = { | |
| 'transaction_1': [0,1,0,0,1], | |
| 'transaction_2': [1,0,1,1,0], | |
| 'transaction_3': [1,0,1,0,0], | |
| 'transaction_4': [0,1,0,1,0], | |
| 'transaction_5': [0,0,0,1,0] | |
| } | |
| print("## data_set") | |
| print("transaction: [item1, item2, item3, item4, item5]") | |
| for k, v in data_set.items(): | |
| print(k, v) | |
| # cast to numpy.ndarray | |
| items = np.array(list(data_set.values())) | |
| def support(items, index_a, index_b): | |
| ''' | |
| Support(A -> B) = o(A U B) / N | |
| o: num of B transactions that contain A | |
| n: num of all transactions | |
| items: [[item1, ..., itemM], | |
| ... | |
| [item1, ..., itemM]] | |
| index_[a, b]: index of the item | |
| ''' | |
| item_a = items[:, index_a] | |
| item_b = items[:, index_b] | |
| o = (item_a * item_b > 0).sum() | |
| n = items.shape[0] | |
| return o / n | |
| def confidence(items, index_a, index_b): | |
| ''' | |
| Confidence(A -> B) = o(A U B) / n(A) | |
| o: num of B transactions that contain A | |
| n: num of transactions that contain A | |
| items: [[item1, ..., itemM], | |
| ... | |
| [item1, ..., itemM]] | |
| index_[a, b]: index of the item | |
| ''' | |
| item_a = items[:, index_a] | |
| item_b = items[:, index_b] | |
| o = (item_a * item_b > 0).sum() | |
| n = (item_a > 0).sum() | |
| return o / n | |
| def lift(items, index_a, index_b): | |
| ''' | |
| Lift(A -> B) = c(Confidence(A -> B)) / n(B) | |
| c: value of Confidence(A -> B) | |
| n: num of transactions that contain B | |
| items: [[item1, ..., itemM], | |
| ... | |
| [item1, ..., itemM]] | |
| index_[a, b]: index of the item | |
| ''' | |
| c = confidence(items, index_a, index_b) | |
| n = (items[:, index_b] > 0).sum() | |
| return c / n | |
| support_0_3 = support(items, 0, 3) | |
| confidence_0_3 = confidence(items, 0, 3) | |
| lift_0_3 = lift(items, 0, 3) | |
| print("\n=== Association rules ===") | |
| print("support: ", support_0_3) | |
| print("confidence: ", confidence_0_3) | |
| print("lift: ", lift_0_3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment