text_plain_output_2.png text_plain_output_1.png
from mlxtend.frequent_patterns import apriori

from mlxtend.frequent_patterns import association_rules

import matplotlib.pyplot as plt

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import seaborn as sns

import seaborn as sns

df = pd.read_csv('../input/market_data_02.csv')
df.columns

# Print the most sold items by transaction
fig, ax=plt.subplots(figsize=(16,7))
df['descricao'].value_counts().sort_values(ascending=False).head(20).plot.bar(width=0.5,edgecolor='k',align='center',linewidth=1)
plt.xlabel('Product Item',fontsize=20)
plt.ylabel('Number of transactions',fontsize=17)
ax.tick_params(labelsize=20)
plt.title('20 Most Sold Items',fontsize=20)
plt.grid()
plt.ioff()

from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
hot_encoded_df = df.groupby(['nota_fiscal_id', 'descricao'])['descricao'].count().unstack().reset_index().fillna(0).set_index('nota_fiscal_id')

def encode_units(x):
    if x <= 0:
        return 0
    if x >= 1:
        return 1
hot_encoded_df = hot_encoded_df.applymap(encode_units)

frequent_itemsets = apriori(hot_encoded_df, min_support=0.01, use_colnames=True)
rules = association_rules(frequent_itemsets, metric='lift', min_threshold=1)

rules.to_csv('market_data_out_all_results.csv')

support = rules.as_matrix(columns=['support'])
confidence = rules.as_matrix(columns=['confidence'])
import seaborn as sns
for i in range(len(support)):
    support[i] = support[i]
    confidence[i] = confidence[i]
plt.title('Assonciation Rules')
plt.xlabel('support')
plt.ylabel('confidance')
sns.regplot(x=support, y=confidence, fit_reg=False)