微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python中的关联规则可视化

如何解决Python中的关联规则可视化

我正在尝试可视化Apriori算法生成的关联规则。我有68条规则,并尝试使用下面的代码来可视化先行节点以及随后使用networkx库的节点。我想将“规则”节点显示为黄色,将其前因和结果节点显示为绿色:

def draw_graph(rules,rules_to_show):
import networkx as nx  
G1 = nx.DiGraph()

color_map = []
N = 50
colors = np.random.rand(N)
strs = ['R0','R1','R2','R3','R4','R5','R6','R7','R8','R9','R10']

for i in range(rules_to_show):
    G1.add_nodes_from(["R"+str(i)])
    
    for a in rules.iloc[i]['antecedents']:
        G1.add_nodes_from([a])
        G1.add_edge(a,"R"+str(i),color = colors[i],weight = 2)
        
    for c in rules.iloc[i]['consequents']:
        G1.add_nodes_from([c])
        G1.add_edge("R"+str(i),c,weight = 2)
        
for node in G1:
    found_a_string = False
    for item in strs:
        if node == item:
            found_a_string = True
        if found_a_string:
            color_map.append('yellow')
        else:
            color_map.append('green')
            
edges = G1.edges()
colors = [G1[u][v]['color'] for u,v in edges]
weights = [G1[u][v]['weight'] for u,v in edges]

pos = nx.spring_layout(G1,k = 16,scale = 1)
nx.draw_networkx(G1,pos,edgelist=edges,node_color = color_map,edge_color=colors,width=weights,font_size=16,with_labels=False)

for p in pos:
    pos[p][1] += 0.07
nx.draw_networkx_labels(G1,pos)
plt.show()

draw_graph(rules,10)

我从生成的规则中提取了10条规则,但是函数nx.draw_networkx中仍然存在一些错误,需要我修复该错误。由于参数node_color = color_map试图区分规则节点和其他节点而发生错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-97-78c7aecc83fc> in <module>
----> 1 draw_graph(rules,10)

<ipython-input-96-2b661601966f> in draw_graph(rules,rules_to_show)
     34 
     35     pos = nx.spring_layout(G1,scale = 1)
---> 36     nx.draw_networkx(G1,with_labels=False)
     37 
     38     for p in pos:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py in draw_networkx(G,arrows,with_labels,**kwds)
    333         pos = nx.drawing.spring_layout(G)  # default to spring layout
    334 
--> 335     draw_networkx_nodes(G,**node_kwds)
    336     draw_networkx_edges(G,arrows=arrows,**edge_kwds)
    337     if with_labels:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py in draw_networkx_nodes(G,nodelist,node_size,node_color,node_shape,alpha,cmap,vmin,vmax,ax,linewidths,edgecolors,label)
    476         linewidths=linewidths,477         edgecolors=edgecolors,--> 478         label=label,479     )
    480     ax.tick_params(

~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax,data,*args,**kwargs)
   1436     def inner(ax,data=None,**kwargs):
   1437         if data is None:
-> 1438             return func(ax,*map(sanitize_sequence,args),**kwargs)
   1439 
   1440         bound = new_sig.bind(ax,**kwargs)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py in wrapper(*inner_args,**inner_kwargs)
    409                          else deprecation_addendum,410                 **kwargs)
--> 411         return func(*inner_args,**inner_kwargs)
    412 
    413     return wrapper

~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in scatter(self,x,y,s,marker,norm,verts,plotnonfinite,**kwargs)
   4451             self._parse_scatter_color_args(
   4452                 c,kwargs,x.size,-> 4453                 get_next_color_func=self._get_patches_for_fill.get_next_color)
   4454 
   4455         if plotnonfinite and colors is None:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c,xsize,get_next_color_func)
   4305                     # NB: remember that a single color is also acceptable.
   4306                     # Besides *colors* will be an empty array if c == 'none'.
-> 4307                     raise invalid_shape_exception(len(colors),xsize)
   4308         else:
   4309             colors = None  # use cmap,norm after collection is created

ValueError: 'c' argument has 154 elements,which is inconsistent with 'x' and 'y' with size 14.

感谢您的帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。