def test_digraph(self):
     G = nx.DiGraph()
     G.add_edge(0, 1)
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     label_name = 'label'
     G.node[0][label_name] = 'A'
     G.node[3][label_name] = 'B'
     node_classification.harmonic_function(G)
 def test_digraph(self):
     G = nx.DiGraph()
     G.add_edge(0, 1)
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     label_name = 'label'
     G.node[0][label_name] = 'A'
     G.node[3][label_name] = 'B'
     node_classification.harmonic_function(G)
Beispiel #3
0
 def test_digraph(self):
     with pytest.raises(nx.NetworkXNotImplemented):
         G = nx.DiGraph()
         G.add_edge(0, 1)
         G.add_edge(1, 2)
         G.add_edge(2, 3)
         label_name = "label"
         G.nodes[0][label_name] = "A"
         G.nodes[3][label_name] = "B"
         node_classification.harmonic_function(G)
Beispiel #4
0
def drop_label(graph, labels, percentage):

    nodes = graph.nodes
    indices = np.random.permutation(len(nodes))
    bound = int(len(nodes) * percentage)
    training_idx, test_idx = indices[:bound], indices[bound:]
    train_mask = np.zeros(len(nodes))
    train_mask[training_idx] = 1

    for node, label, mask in zip(nodes, labels, train_mask):
        if mask == 1:
            graph.nodes[node]['label'] = label
        else:
            try:
                nodes[node].pop("label")
            except:
                pass

    harmonic_prediction = np.array(
        node_classification.harmonic_function(graph))
    local_global_prediction = np.array(
        node_classification.local_and_global_consistency(graph))

    return accuracy_score(labels[test_idx], harmonic_prediction[test_idx]), \
           accuracy_score(labels[test_idx], local_global_prediction[test_idx])
 def test_nodes_all_labeled(self):
     G = nx.karate_club_graph()
     label_name = 'club'
     predicted = node_classification.harmonic_function(
         G, label_name=label_name)
     for i in range(len(G)):
         assert_equal(predicted[i], G.node[i][label_name])
 def test_nodes_all_labeled(self):
     G = nx.karate_club_graph()
     label_name = 'club'
     predicted = node_classification.harmonic_function(
         G, label_name=label_name)
     for i in range(len(G)):
         assert_equal(predicted[i], G.node[i][label_name])
Beispiel #7
0
def harmonic_func(G, label_name):
    predicted = list(
        node_classification.harmonic_function(G, label_name=label_name))
    idx = 0
    for n in G.nodes():
        G.nodes[n][label_name] = predicted[idx]
        idx = idx + 1
    return G
 def test_one_labeled_node(self):
     G = nx.path_graph(4)
     label_name = 'label'
     G.node[0][label_name] = 'A'
     predicted = node_classification.harmonic_function(
         G, label_name=label_name)
     assert_equal(predicted[0], 'A')
     assert_equal(predicted[1], 'A')
     assert_equal(predicted[2], 'A')
     assert_equal(predicted[3], 'A')
 def test_one_labeled_node(self):
     G = nx.path_graph(4)
     label_name = "label"
     G.nodes[0][label_name] = "A"
     predicted = node_classification.harmonic_function(
         G, label_name=label_name)
     assert predicted[0] == "A"
     assert predicted[1] == "A"
     assert predicted[2] == "A"
     assert predicted[3] == "A"
 def test_one_labeled_node(self):
     G = nx.path_graph(4)
     label_name = 'label'
     G.node[0][label_name] = 'A'
     predicted = node_classification.harmonic_function(
         G, label_name=label_name)
     assert_equal(predicted[0], 'A')
     assert_equal(predicted[1], 'A')
     assert_equal(predicted[2], 'A')
     assert_equal(predicted[3], 'A')
 def test_labeled_nodes_are_not_changed(self):
     G = nx.karate_club_graph()
     label_name = 'club'
     label_removed = set([0, 1, 2, 3, 4, 5, 6, 7])
     for i in label_removed:
         del G.node[i][label_name]
     predicted = node_classification.harmonic_function(
         G, label_name=label_name)
     label_not_removed = set(list(range(len(G)))) - label_removed
     for i in label_not_removed:
         assert_equal(predicted[i], G.node[i][label_name])
 def test_labeled_nodes_are_not_changed(self):
     G = nx.karate_club_graph()
     label_name = 'club'
     label_removed = set([0, 1, 2, 3, 4, 5, 6, 7])
     for i in label_removed:
         del G.node[i][label_name]
     predicted = node_classification.harmonic_function(
         G, label_name=label_name)
     label_not_removed = set(list(range(len(G)))) - label_removed
     for i in label_not_removed:
         assert_equal(predicted[i], G.node[i][label_name])
Beispiel #13
0
 def test_path_graph(self):
     G = nx.path_graph(4)
     label_name = 'label'
     G.nodes[0][label_name] = 'A'
     G.nodes[3][label_name] = 'B'
     predicted = node_classification.harmonic_function(
         G, label_name=label_name)
     assert predicted[0] == 'A'
     assert predicted[1] == 'A'
     assert predicted[2] == 'B'
     assert predicted[3] == 'B'
Beispiel #14
0
def classify_gcn_data(graph, dataset):
    train_y = np.argmax(np.load(f'./ind.{dataset}.y'), axis=1)
    test_y = np.argmax(np.load(f'./ind.{dataset}.ty'), axis=1)

    test_idx = parse_index_file(f'./ind.{dataset}.test.index')

    train_labels = {train_node: train_y[train_node] for train_node in range(len(train_y))}
    test_labels = {test_node: test_y[test_node] for test_node in range(len(test_y))}

    nx.set_node_attributes(graph, train_labels, 'train_labels')

    harmonic_pred = node_classification.harmonic_function(graph, label_name='train_labels')
    lg_pred = node_classification.local_and_global_consistency(graph, label_name='train_labels')

    harmonic_acc = metrics.accuracy_score(test_y, np.array(harmonic_pred)[test_idx])
    lg_acc = metrics.accuracy_score(test_y, np.array(lg_pred)[test_idx])

    return harmonic_acc, lg_acc
Beispiel #15
0
def classifiy_lfr(graph, node_labels, train_portion=0.8):

    nodes_idx = np.arange(len(node_labels))
    np.random.shuffle(nodes_idx)

    train_nodes_idx = nodes_idx[:int(train_portion * len(node_labels))]
    test_nodes_idx = nodes_idx[int(train_portion * len(node_labels)):]

    train_labels = {train_node: node_labels[train_node] for train_node in train_nodes_idx}

    nx.set_node_attributes(graph, train_labels, 'train_labels')

    harmonic_pred = node_classification.harmonic_function(graph, label_name='train_labels')
    lg_pred = node_classification.local_and_global_consistency(graph, label_name='train_labels')

    harmonic_acc = metrics.accuracy_score(node_labels[test_nodes_idx], np.array(harmonic_pred)[test_nodes_idx])
    lg_acc = metrics.accuracy_score(node_labels[test_nodes_idx], np.array(lg_pred)[test_nodes_idx])

    return harmonic_acc, lg_acc
Beispiel #16
0
def classify_real_graph_nodes(graph, train_portion=0.8):
    all_labels = nx.get_node_attributes(graph, 'value')

    nodes = np.array(list(all_labels.keys()))
    nodes_idx = np.arange(len(nodes))
    np.random.shuffle(nodes_idx)

    train_nodes_idx = nodes_idx[:int(train_portion * len(nodes))]
    test_nodes_idx = nodes_idx[int(train_portion * len(nodes)):]

    train_labels = {train_node: all_labels[train_node] for train_node in nodes[train_nodes_idx]}
    test_labels = {test_node: all_labels[test_node] for test_node in nodes[test_nodes_idx]}

    nx.set_node_attributes(graph, train_labels, 'train_labels')

    harmonic_pred = node_classification.harmonic_function(graph, label_name='train_labels')
    lg_pred = node_classification.local_and_global_consistency(graph, label_name='train_labels')

    harmonic_acc = metrics.accuracy_score(np.array(list(test_labels.values())), np.array(harmonic_pred)[test_nodes_idx])
    lg_acc = metrics.accuracy_score(np.array(list(test_labels.values())), np.array(lg_pred)[test_nodes_idx])

    return harmonic_acc, lg_acc
Beispiel #17
0
def q2():
    graph, labels, y_train, y_val, y_test, train_mask, val_mask, test_mask = load_data_gcn(
        args.data)
    if args.data == 'citeseer':
        nonzeros = labels.nonzero()
        max_label = np.max(nonzeros[1])
        diff = len(labels) - len(nonzeros[1])
        res = np.full(labels.shape[0], -1)
        res[nonzeros[0]] = nonzeros[1]
        iso_mask = np.where(res == -1)
        res[iso_mask] = np.arange(max_label + 1, max_label + 1 + diff)
        labels = res
    else:
        labels = labels.nonzero()[1]

    for node, label, mask in zip(graph.nodes, labels, train_mask):
        if mask:
            graph.nodes[node]['label'] = label

    harmonic_prediction = np.array(
        node_classification.harmonic_function(graph))
    local_global_prediction = np.array(
        node_classification.local_and_global_consistency(graph))

    print("train accuracy of harmonic prediction: {}".format(
        accuracy_score(labels[train_mask], harmonic_prediction[train_mask])))
    print("train accuracy of loc-glob prediction: {}".format(
        accuracy_score(labels[train_mask],
                       local_global_prediction[train_mask])))

    print("val accuracy of harmonic prediction: {}".format(
        accuracy_score(labels[val_mask], harmonic_prediction[val_mask])))
    print("val accuracy of loc-glob prediction: {}".format(
        accuracy_score(labels[val_mask], local_global_prediction[val_mask])))

    print("test accuracy of harmonic prediction: {}".format(
        accuracy_score(labels[test_mask], harmonic_prediction[test_mask])))
    print("test accuracy of loc-glob prediction: {}".format(
        accuracy_score(labels[test_mask], local_global_prediction[test_mask])))
Beispiel #18
0
def calculate_node_classification_accuracy(G, label, ground_truths, method):

    nmi_list = []
    ars_list = []

    for i in range(10):
        
        if method == 'harmonic':
            predictions = node_classification.harmonic_function(G, label_name=label)
        else:
            predictions = node_classification.local_and_global_consistency(G, label_name=label)
        
        nmi, ars = calculate_nmi_ars(ground_truths, predictions)
        nmi_list.append(nmi)
        ars_list.append(ars)
    
    average_nmi = round(mean(nmi_list), 4)
    average_ars = round(mean(ars_list), 4)
    
    print('Average NMI:', average_nmi)
    print('Average ARS:', average_ars)

    return average_nmi, average_ars
 def test_no_labels(self):
     G = nx.path_graph(4)
     node_classification.harmonic_function(G)
 def test_no_edges(self):
     G = nx.Graph()
     G.add_node(1)
     G.add_node(2)
     node_classification.harmonic_function(G)
    fu_values = np.dot(np.dot(np.linalg.inv(Duu - Wuu), Wul), fl_values)
    for row in range(len(fu_values)):
        fu[fu_list[row]] = fu_values[row]
    labeled_list = []
    for i in range(len(fu) + len(fl)):
        try:
            labeled_list.append(fl[i])
        except KeyError:
            labeled_list.append(fu[i])

    return [uniq_labeles_inverse[int(round(value))] for value in labeled_list]


G = create_toroidal(16)
G.node[0]['label'] = 'blue'
G.node[255]['label'] = 'red'
gpos = nx.spring_layout(G, iterations=200)
node_color=['blue' if n == 0 else 'red' if n == 255 else 'gray' for n in G.nodes]
plt.figure(figsize=(10,10))
nx.draw(G, gpos, with_labels=False, node_size=200, node_color=node_color)
plt.show()

node_color=node_classification.harmonic_function(G)
removed = [n for n in G.nodes if n%3 == 0 ]
for n in G.nodes:
    if n not in removed:
        G.node[n]['label'] = node_color[n]
predicted = your_harmonic_function(G, label_name='label')

print(confusion_matrix(node_color, predicted))
print(precision_recall_fscore_support(node_color, predicted))
Beispiel #22
0
    #predicted = _predict(F, label_dict)

    return F



def setup_module(module):
    """Fixture for nose tests."""
    from nose import SkipTest
    try:
        import numpy
    except ImportError:
        raise SkipTest("NumPy not available")
    try:
        import scipy
    except ImportError:
        raise SkipTest("SciPy not available")

if __name__ == '__main__':
    G=nx.Graph()
    G.add_nodes_from(range(1,16))
    G.node[2]['label'] = 'A'
    G.node[11]['label'] = 'B'
    G.add_edges_from([(1,3),(3,2),(3,4),(4,6),(4,12),(4,14),(6,5),(12,10),(12,15),(10,7),(10,8),(10,9),(10,11),(10,13)])
	# Se quiser usar a função da networkx para rotular logo basta usar:
    predicted = node_classification.harmonic_function(G)
    print(predicted)
    # Se quiser os valores de pertinência em cada classe deve-se usar a
    # função deste arquivo
    F = harmonic_function(G)
    print(F)
 def test_no_edges(self):
     G = nx.Graph()
     G.add_node(1)
     G.add_node(2)
     node_classification.harmonic_function(G)
Beispiel #24
0
 def test_no_labels(self):
     with pytest.raises(nx.NetworkXError):
         G = nx.path_graph(4)
         node_classification.harmonic_function(G)
 def test_no_nodes(self):
     G = nx.Graph()
     node_classification.harmonic_function(G)
 def test_no_labels(self):
     G = nx.path_graph(4)
     node_classification.harmonic_function(G)
Beispiel #27
0
import networkx as nx
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import graphviz_layout
from networkx.algorithms import node_classification

G = nx.path_graph(4)
G.edges()

G.node[0]['label'] = 'A'
G.node[3]['label'] = 'B'
node_classification.harmonic_function(G)  # doctest: +SKIP

nx.draw(G,
        pos=graphviz_layout(G),
        node_size=1600,
        cmap=plt.cm.Reds,
        node_color=range(len(G)),
        prog='dot',
        with_labels=True)
plt.show()
Beispiel #28
0
 def test_no_edges(self):
     with pytest.raises(nx.NetworkXError):
         G = nx.Graph()
         G.add_node(1)
         G.add_node(2)
         node_classification.harmonic_function(G)
 def test_no_nodes(self):
     G = nx.Graph()
     node_classification.harmonic_function(G)