앞의 포스팅에서 배운 association rule mining 알고리즘을 mlxtend 패키지를 이용하여 활용해보자.
pip install mlxtend
TransactionEncoder()
sklearn의 OneHotEncoder, LabelEncoder 등과 거의 유사한 Encoder 클래스이다.
transaction data를 numpy array로 인코딩해준다.
import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
dataset = [['Milk', 'Onion', 'Nutmeg', 'Kidney Beans', 'Eggs', 'Yogurt'],
['Dill', 'Onion', 'Nutmeg', 'Kidney Beans', 'Eggs', 'Yogurt'],
['Milk', 'Apple', 'Kidney Beans', 'Eggs'],
['Milk', 'Unicorn', 'Corn', 'Kidney Beans', 'Yogurt'],
['Corn', 'Onion', 'Onion', 'Kidney Beans', 'Ice cream', 'Eggs']]
te = TransactionEncoder()
# te_ary = te.fit_transform(dataset) <- Same result
te_ary = te.fit(dataset).transform(dataset)
모든 데이터를 읽은 후, 각 row에 해당 데이터가 있으면 True, 없으면 False로 인코딩하여 2D-array인 te_ary를 반환한다.
te_ary는 아래와 같이 저장된다.
print(te_ary)
[[False False False True False True True True True False True]
[False False True True False True False True True False True]
[ True False False True False True True False False False False]
[False True False False False True True False False True True]
[False True False True True True False False True False False]]
fit_transform()을 적용한 후, TransactionEncoder의 멤버변수 columns_ 를 통해 각 컬럼이 어떤 데이터로 매핑되었는지 확인할 수 있다.
print(te.columns_)
['Apple', 'Corn', 'Dill', 'Eggs', 'Ice cream', 'Kidney Beans', 'Milk', 'Nutmeg', 'Onion', 'Unicorn', 'Yogurt']
2D-array와 행렬의 컬럼이름도 알았으니, pandas의 dataframe으로 변환할 수 있다,
df = pd.DataFrame(te_ary, columns=te.columns_)
Frequent Itemset Generation using apriori()
Apriori 알고리즘을 통해 Frequent Itemset을 생성해보자.
이때, apriori()의 첫번째 파라미터의 모든 컬럼을 item으로 인식하고 알고리즘을 수행하므로, 필요하다면 목적에 맞게 컬럼을 지정할 필요가 있다.
from mlxtend.frequent_patterns import apriori
frequent_itemsets = apriori(df, min_support=0.6, use_colnames=True)
frequent_itemsets
그 복잡한 $C_k, L_k$를 만드는 과정이 하나의 API를 통해 frequent itemset을 생성할 수 있다.
(1) Selecting and Filtering
이렇게 만들어진 frequent_itemset 역시 pandas의 dataframe이다. 따라서 pandas의 동일한 메소드를 이용하여 원하는 정보를 고를 수 있다.
type(frequent_itemsets)
pandas.core.frame.DataFrame
(1.1) 컬럼 추가하기
apply 등의 메소드를 이용하여 DataFrame에 컬럼을 추가할 수 있다.
frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x))
frequent_itemsets
(1.2) 특정 조건을 만족하는 row 찾기
DataFrame에 bool 연산을 이용하여 특정 조건을 만족하는 row를 필터링할 수 있다.
frequent_itemsets[ (frequent_itemsets['length'] == 2) &
(frequent_itemsets['support'] >= 0.8) ]
집합 연산도 가능하다.
참고로, itemset의 type은 frozenset으로, Python의 set과 유사하지만, immutable하다.
frequent_itemsets[ frequent_itemsets['itemsets'] == {'Onion', 'Eggs'} ]
Associate Rule Generation using association_rules()
이제 생성된 frequent itemsets을 이용하여 rule을 생성해보자.
직접 지정한 min_threshold을 만족하는 metric만 결과를 저장하고, 나머지는 버린다.
from mlxtend.frequent_patterns import association_rules
rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.7)
rules
이렇게 생성된 rules 역시 DataFrame이므로 위의 frequent_itemsets와 같이 DataFrame의 메소드를 이용할 수 있다.
rules["antecedent_len"] = rules["antecedents"].apply(lambda x: len(x))
rules
rules[ (rules['antecedent_len'] >= 2) &
(rules['confidence'] > 0.75) &
(rules['lift'] > 1.2) ]
rules[rules['antecedents'] == {'Eggs', 'Kidney Beans'}]
참고
TransactionEncoder - mlxtend
From here you can search these documents. Enter your search terms below.
rasbt.github.io
Apriori - mlxtend
From here you can search these documents. Enter your search terms below.
rasbt.github.io
'스터디 > 데이터사이언스' 카테고리의 다른 글
[Pandas] Basic Statistics 살펴보기 (0) | 2023.04.10 |
---|---|
[Data Science] Grubb's test를 이용한 Outlier detection (0) | 2023.04.08 |
[Data Science] Association Rule Mining (6) Interesting Measures (0) | 2023.04.03 |
[Data Science] Association Rule Mining (5) Rule Generation (0) | 2023.04.03 |
[Data Science] Association Rule Mining (4) FP-Growth (0) | 2023.04.02 |