def I_M(g, method_1, method_2, genero=False):
    colores_posibles = [
        'r', 'b', 'g', 'k', 'c', 'y', 'violet', 'orange', 'indianred',
        'darkgray'
    ]

    if genero:
        nodes_1 = particionar_por_genero(g)
        colors_1 = comunidad_a_color(g, nodes_1)
    else:
        nodes_1 = calcular_particion(g, method=method_1)
        colors_1 = comunidad_a_color(g, nodes_1)

    nodes_2 = calcular_particion(g, method=method_2)
    colors_2 = comunidad_a_color(g, nodes_2)

    matrix = np.zeros([len(colores_posibles), len(colores_posibles)])
    for i in range(len(g.nodes())):
        index_1 = colores_posibles.index(colors_1[0][i])
        index_2 = colores_posibles.index(colors_2[0][i])
        matrix[index_1, index_2] += 1
    matrix = matrix / len(g.nodes())

    colors_1 = [
        colores_posibles.index(colors_1[0][i]) for i in range(len(colors_1[0]))
    ]
    colors_2 = [
        colores_posibles.index(colors_2[0][i]) for i in range(len(colors_2[0]))
    ]
    m_1, bins = np.histogram(colors_1,
                             bins=np.arange(len(colores_posibles) + 1))
    m_2, bins = np.histogram(colors_2,
                             bins=np.arange(len(colores_posibles) + 1))
    m_1 = m_1 / len(g.nodes())
    m_2 = m_2 / len(g.nodes())

    I = 0
    for i in range(len(colores_posibles)):
        for j in range(len(colores_posibles)):
            if matrix[i, j] != 0 and m_1[i] != 0 and m_2[j] != 0:
                I += matrix[i, j] * np.log2(matrix[i, j] / (m_1[i] * m_2[j]))

    H_1 = -np.sum([i * np.log2(i) for i in m_1 if i != 0])
    H_2 = -np.sum([i * np.log2(i) for i in m_2 if i != 0])

    I_M = I / (0.5 * (H_1 + H_2))

    return I_M
예제 #2
0
def matriz_de_presiciones (graph, lista_de_metodos):    
    diccionario = {} #Claves-->nombres de los metodos. Values-->indice del metodo
    for k, metodo in enumerate(lista_de_metodos):
        diccionario[metodo] = k
    pares_de_metodos = pares(lista_de_metodos)
    matriz_presicion = np.ones((len(lista_de_metodos), len(lista_de_metodos)))
    for i in range(len(pares_de_metodos)):
        part_1 = calcular_particion(dolph, method=pares_de_metodos[i][0],
                                    only_labels = True)
        part_2 = calcular_particion(dolph, method=pares_de_metodos[i][1],
                                    only_labels = True)
        _, presicion = matriz_de_confusion(part_1,part_2)
        ind_1 = diccionario[pares_de_metodos[i][0]]
        ind_2 = diccionario[pares_de_metodos[i][1]]   
        matriz_presicion[ind_1,ind_2] = presicion
        matriz_presicion[ind_2,ind_1] = presicion    
    return matriz_presicion
예제 #3
0
def matriz_de_presiciones (graph, lista_de_metodos):    
    '''A partir de un grafo y una lista de metodos a analizar,
    devuelve una matriz en donde el elemento i-j es una comparacion
    entre el metodo i con el j.'''
    diccionario = {} #Claves-->nombres de los metodos. Values-->indice del metodo
    for k, metodo in enumerate(lista_de_metodos):
        diccionario[metodo] = k
    pares_de_metodos = pares(lista_de_metodos)
    matriz_presicion = np.ones((len(lista_de_metodos), len(lista_de_metodos)))
    for i in range(len(pares_de_metodos)):
        part_1 = calcular_particion(graph, method=pares_de_metodos[i][0],
                                    only_labels = True)
        part_2 = calcular_particion(graph, method=pares_de_metodos[i][1],
                                    only_labels = True)
        _, presicion = matriz_de_confusion(part_1,part_2)
        ind_1 = diccionario[pares_de_metodos[i][0]]
        ind_2 = diccionario[pares_de_metodos[i][1]]   
        matriz_presicion[ind_1,ind_2] = presicion
        matriz_presicion[ind_2,ind_1] = presicion    
    return matriz_presicion
예제 #4
0
    return matriz_presicion

def plot_matrix(matriz, etiquetas=None, annot = False):
    df = pd.DataFrame(matriz, columns=etiquetas, index = etiquetas)
    ax = sns.heatmap(df, annot=annot, fmt=".2f", vmin = 0, vmax=1
                     , square=True)
    for label in ax.get_yticklabels():
            label.set_size(7)
    for label in ax.get_xticklabels():
            label.set_size(7)
#%%
if __name__ == '__main__':
    dolph = read_gml('Tp3/dolphins.gml')    
    lista_de_metodos = ["infomap","label_prop", "fastgreedy", "eigenvector",
                        "louvain", "edge_betweenness", "walktrap"] 
    part_1 = calcular_particion(dolph, method="fastgreedy", only_labels = True)
    part_2 = calcular_particion(dolph, method="walktrap", only_labels = True)
    matriz_confusion, presicion = matriz_de_confusion(part_1,part_2,norm=True)
    lista_de_metodos_chetos = ["Infomap","Label Propagation", "Fastgreedy",
                               "Eigenvector", "Louvain", "Edge Betweenness",
                               "Walktrap"] 
    mp = matriz_de_presiciones(dolph, lista_de_metodos)
    plt.figure()
    plot_matrix(matriz_confusion, annot=True)
    plt.figure()
    plot_matrix(mp, lista_de_metodos_chetos)
#%% Pruebita
    a=[1,1,1,2,2,2]
    b=[1,2,1,3,3,3]
    matriz, presicion = matriz_de_confusion(a,b,norm=True)
    plot_matrix(matriz)
예제 #5
0
    # The vertical line for average silhouette score of all the values
    ax.axvline(x=sil_medio, color="red", linestyle="--")

    if ax is None:
        fig.tight_layout()
    fig.show()


#%%
if __name__ == '__main__':
    plt.ion()

    prueba_infomap = True
    if prueba_infomap:
        g = nx.balanced_tree(h=3, r=2)
        particion = calcular_particion(g, method='infomap')
        sil = silhouettes(g, particion)

    prueba_dolph = False
    if prueba_dolph:
        g = read_gml('Tp3/dolphins.gml')
        npzfile = np.load('Tp3/tc03Data/Ej_b_particiones.npz')
        rewire = npzfile['salida']
        original = npzfile['salida_grafo_original']
        particion = original[0]
        ### Para probar el manejo de errores en silhouettes():
        # particion = [list(dolph.nodes())] # funciona
        sil = silhouettes(g, particion)

    prueba_disconexos = False
    if prueba_disconexos:
예제 #6
0
    """
    colores_posibles =  [b for (a,b) in matplotlib.colors.cnames.items()]
    colores_random = np.random.choice(np.arange(len(colores_posibles)), size=len(lista),
                                      replace=False)
    nodos = list(g.nodes())
    colores = list(np.zeros(len(nodos)))
    for i in range(len(lista)):
        for j in range(len(nodos)):
            index = colores_random[i]
            if nodos[j] in lista[i]:
                colores[j] = colores_posibles[index]
    return colores


#%% Punto 1    
wiki = ldata('Final/links.tsv')
g_wiki = nx.Graph()
g_wiki.add_edges_from(wiki)
#%%
wiki_infomap = calcular_particion(g_wiki)
wiki_infomap_color = comunidad_a_color(g_wiki, wiki_infomap)
wiki_fastgreedy = calcular_particion(g_wiki, method = 'fastgreedy')
wiki_fastgreedy_color = comunidad_a_color(g_wiki, wiki_fastgreedy)
#%%Ploteamos la red
fig, ax = plt.subplots()
plt.sca(ax)
ax.set_title('Wikipedia')
#nx.draw(g_wiki, node_color = wiki_infomap_color, node_size = 10)
nx.draw_spring(g_wiki, node_color = wiki_fastgreedy_color,
               node_size = 10, with_labels=True)