def test_nodes_all_labeled(self): G = nx.karate_club_graph() label_name = 'club' predicted = node_classification.local_and_global_consistency( G, alpha=0, label_name=label_name) for i in range(len(G)): assert_equal(predicted[i], G.node[i][label_name])
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.local_and_global_consistency( G, alpha=0, label_name=label_name) for i in range(len(G)): assert predicted[i] == G.nodes[i][label_name]
def l_g_consistency(G, label_name): predicted = list( node_classification.local_and_global_consistency( 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.nodes[0][label_name] = 'A' predicted = node_classification.local_and_global_consistency( 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.local_and_global_consistency( 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_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.local_and_global_consistency( G, label_name=label_name) assert predicted[0] == "A" assert predicted[1] == "A" assert predicted[2] == "B" assert predicted[3] == "B"
def test_path_graph(self): G = nx.path_graph(4) label_name = 'label' G.node[0][label_name] = 'A' G.node[3][label_name] = 'B' predicted = node_classification.local_and_global_consistency( G, label_name=label_name) assert_equal(predicted[0], 'A') assert_equal(predicted[1], 'A') assert_equal(predicted[2], 'B') assert_equal(predicted[3], 'B')
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
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
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])))
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
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_edges(self): with pytest.raises(nx.NetworkXError): G = nx.Graph() G.add_node(1) G.add_node(2) node_classification.local_and_global_consistency(G)
def test_no_labels(self): with pytest.raises(nx.NetworkXError): G = nx.path_graph(4) node_classification.local_and_global_consistency(G)
def test_no_nodes(self): G = nx.Graph() node_classification.local_and_global_consistency(G)
def test_no_edges(self): G = nx.Graph() G.add_node(1) G.add_node(2) node_classification.local_and_global_consistency(G)
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.local_and_global_consistency(G) print(predicted) # Se quiser os valores de pertinência em cada classe deve-se usar a # função deste arquivo F = local_and_global_consistency(G) print(F)
def test_no_labels(self): G = nx.path_graph(4) node_classification.local_and_global_consistency(G)