In [ ]:
import numpy as np
from itertools import combinations
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
In [ ]:
# define two transactions for two customers
customer_a= ['shampoo', 'conditioner', 'foundation','cream']
customer_b= ['shampoo', 'conditioner', 'lipstick']
In [ ]:
# total transactions
total_trans= [customer_a, customer_b]
total_trans
Out[ ]:
[['shampoo', 'conditioner', 'foundation', 'cream'], ['shampoo', 'conditioner', 'lipstick']]
In [ ]:
#for every transaction, we find the pair-wise item purchased together
edge_weights= defaultdict(int)
#how we update the weight, and make connections between two items
for transaction in total_trans:
for item1, item2, in combinations(sorted(set(transaction)),2):
edge_weights[(item1, item2)] +=1
In [ ]:
edge_weights
Out[ ]:
defaultdict(int,
{('conditioner', 'cream'): 1,
('conditioner', 'foundation'): 1,
('conditioner', 'shampoo'): 2,
('cream', 'foundation'): 1,
('cream', 'shampoo'): 1,
('foundation', 'shampoo'): 1,
('conditioner', 'lipstick'): 1,
('lipstick', 'shampoo'): 1})
In [ ]:
# create graph and put information above into this graph
G= nx.Graph()
for (item1, item2), weight in edge_weights.items():
G.add_edge(item1, item2, weight=weight)
In [ ]:
#extract weights
weights= list(nx.get_edge_attributes(G, 'weight').values())
weights = [i*2 for i in weights]
weights
Out[ ]:
[2, 2, 4, 2, 2, 2, 2, 2]
In [ ]:
#visualize the graph
pos= nx.spring_layout(G) #spring layout is a style to visualize
nx.draw(G, pos, node_color= 'lightblue', node_size=1500,
edge_color='pink', with_labels=True, width=weights)
plt.show()
In [ ]:
In [ ]:
In [ ]:
#easier way to think of connections #1
a= [1,2,3]
combinations(a,2)
for i, j in combinations(a,2):
print(i,j)
1 2 1 3 2 3
In [ ]:
#easier way to think of connections #2
a= [1,2,3,4]
combinations(a,2)
for i, j, k in combinations(a,3):
print(i,j, k)
1 2 3 1 2 4 1 3 4 2 3 4
In [ ]:
#easier way to think of connections #3
b= ['lambo', 'iphone17', 'porsche']
for i, j in combinations(b,2):
print(i,j)
lambo iphone17 lambo porsche iphone17 porsche
In [ ]: