ontowalk2vecDBpedia.py 9.63 KB
Newer Older
ina's avatar
ina committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import random
import os
import numpy as np

os.environ['PYTHONHASHSEED'] = '42'
random.seed(42)
np.random.seed(42)

import argparse
import rdflib
import node2vec
import pandas as pd
import matplotlib.pyplot as plt
from gensim.models import Word2Vec
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import networkx as nx
from graph import *
from rdf2vec import RDF2VecTransformer
from graphs import SPARQLLoader
import numpy as np
from collections import defaultdict

import warnings
warnings.filterwarnings('ignore')

def parse_args():
	'''
	Parses the node2vec arguments.
	'''
	parser = argparse.ArgumentParser(description="Run ontowalk2vec.")

	parser.add_argument('--input', nargs='?', default='',
	                    help='Input graph path')

	parser.add_argument('--output', nargs='?', default='emb/data.emb',
	                    help='Embeddings path')

	parser.add_argument('--dimensions', type=int, default=128,
	                    help='Number of dimensions. Default is 128.')

	parser.add_argument('--walk-length', type=int, default=80,
	                    help='Length of walk per source. Default is 80.')

	parser.add_argument('--num-walks', type=int, default=10,
	                    help='Number of walks per source. Default is 10.')

	parser.add_argument('--window-size', type=int, default=10,
                    	help='Context size for optimization. Default is 10.')

	parser.add_argument('--iter', default=1, type=int,
                      help='Number of epochs in SGD')

	parser.add_argument('--workers', type=int, default=8,
	                    help='Number of parallel workers. Default is 8.')

	parser.add_argument('--p', type=float, default=1,
	                    help='Return hyperparameter. Default is 1.')

	parser.add_argument('--q', type=float, default=1,
	                    help='Inout hyperparameter. Default is 1.')

	parser.add_argument('--weighted', dest='weighted', action='store_true',
	                    help='Boolean specifying (un)weighted. Default is unweighted.')
	parser.add_argument('--unweighted', dest='unweighted', action='store_false')
	parser.set_defaults(weighted=False)

	parser.add_argument('--directed', dest='directed', action='store_true',
	                    help='Graph is (un)directed. Default is undirected.')
	parser.add_argument('--undirected', dest='undirected', action='store_false')
	parser.set_defaults(directed=True)

	return parser.parse_args()



def main(args):

    # Load the data with rdflib
    print(end='Loading data... ', flush=True)
    g = rdflib.Graph()
    g.parse('../ontowalk2vec/data/dbpedia_2016-10.owl')

    # Load our train & test instances and labels
    test_data = pd.read_csv('../ontowalk2vec/data/cities_test.csv', sep=',')
    train_data = pd.read_csv('../ontowalk2vec/data/cities_train.csv', sep=',')

    train_points = [rdflib.URIRef(x) for x in train_data['city']]
    train_labels = train_data['label']

    test_points = [rdflib.URIRef(x) for x in test_data['city']]
    test_labels = test_data['label']

    all_labels = list(train_labels) + list(test_labels)

    # Define the label predicates, all triples with these predicates
    # will be excluded from the graph
    label_predicates = [
        #rdflib.term.URIRef('http://dl-learner.org/carcinogenesis#isMutagenic')
    ]

    # Convert the rdflib to our KnowledgeGraph object
  
    kg = SPARQLLoader("https://dbpedia.org/sparql") 
    

    kgraph = KnowledgeGraph()
    
    for root in (train_points+test_points):
        walks = {(root,)}
        for i in range(2):
            walks_copy = walks.copy()
            for walk in walks_copy:
                hops = kg.get_hops(walk[-1])
                for (p,o) in hops:
                    rls = rdflib.URIRef(root)
                    rlp = rdflib.URIRef(p)
                    rlo = rdflib.URIRef(o)
                    g.add((rls, rlp, rlo))
                    s_v, o_v = Vertex(str(root)), Vertex(str(o))
                    p_v = Vertex(str(p), predicate=True, _from=s_v, _to=o_v)
                    kgraph.add_vertex(s_v)
                    kgraph.add_vertex(p_v)
                    kgraph.add_vertex(o_v)
                    kgraph.add_edge(s_v, p_v)
                    kgraph.add_edge(p_v, o_v)
                
                
                hops2 = kg.get_sub_pred(walk[-1])
                for (s,p) in hops2:
                    rls = rdflib.URIRef(root)
                    rlp = rdflib.URIRef(p)
                    rlo = rdflib.URIRef(o)
                    g.add((rls, rlp, rlo))
                    s_v, o_v = Vertex(str(s)), Vertex(str(root))
                    p_v = Vertex(str(p), predicate=True, _from=s_v, _to=o_v)
                    kgraph.add_vertex(s_v)
                    kgraph.add_vertex(p_v)
                    kgraph.add_vertex(o_v)
                    kgraph.add_edge(s_v, p_v)
                    kgraph.add_edge(p_v, o_v)
                

    ontology = rdflib_to_kg(g, label_predicates=label_predicates)
    nx_graph = nx.DiGraph()

    for v in ontology._vertices:
        if not v.predicate:
            name = v.name
            nx_graph.add_node(name, name=name, pred=v.predicate)
            
    for v in ontology._vertices:
        if not v.predicate:
            v_name = v.name
            for pred in ontology.get_neighbors(v):
                pred_name = pred.name
                for obj in ontology.get_neighbors(pred):
                    obj_name = obj.name
                    nx_graph.add_edge(v_name, obj_name, name=pred_name)

    for edge in nx_graph.edges():
        nx_graph[edge[0]][edge[1]]['weight'] = 1
    
    
    G = node2vec.Graph(nx_graph, args.directed, args.p, args.q)
    G.preprocess_transition_probs()
    node2vec_walks = G.simulate_walks(args.num_walks, args.walk_length)

    print('creating embeddings')
    #bfs embeddings
    transformer = RDF2VecTransformer(wl=False, max_path_depth=1, walks_per_graph=250, sg=1)
    walk_embeddings = transformer.fit_transform(kgraph, train_points + test_points, node2vec_walks)
    
    #wl embeddings
    transformer = RDF2VecTransformer(wl=True, max_path_depth=1, walks_per_graph=250, sg=1)
    wl_embeddings = transformer.fit_transform(kgraph, train_points + test_points, node2vec_walks)
    
    # Fit model on the walk embeddings
    train_embeddings = walk_embeddings[:len(train_points)]
    test_embeddings = walk_embeddings[len(train_points):]

    rf =  RandomForestClassifier(random_state=42, n_estimators=100)
    rf.fit(train_embeddings, train_labels)

    accuracies = ''
    conf_matr = ''
    
    print('Random Forest:')
    acc1= accuracy_score(test_labels, rf.predict(test_embeddings))
    accuracies += str(acc1)+','
    print(acc1)
    cm1 = confusion_matrix(test_labels, rf.predict(test_embeddings))
    for i in range(3):
    	for j in range(3):
    		conf_matr += str(cm1[i][j]) + ','
    conf_matr += '\n'
    print(cm1)
    

    clf =  GridSearchCV(SVC(random_state=42), {'kernel': ['linear', 'poly', 'rbf'], 'C': [10**i for i in range(-3, 4)]})
    clf.fit(train_embeddings, train_labels)

    print('Support Vector Machine:')    
    acc2 = accuracy_score(test_labels, clf.predict(test_embeddings))
    accuracies += str(acc2)+','
    print(acc2)
    cm2 = confusion_matrix(test_labels, clf.predict(test_embeddings))
    for i in range(3):
    	for j in range(3):
    		conf_matr += str(cm2[i][j]) + ','
    conf_matr += '\n'
    print(cm2)

    # Fit model on the WL embeddings
    train_embeddings = wl_embeddings[:len(train_points)]
    test_embeddings = wl_embeddings[len(train_points):]

    rf =  RandomForestClassifier(random_state=42, n_estimators=100)
    rf.fit(train_embeddings, train_labels)
    

    print('Random Forest:')
    acc3 = accuracy_score(test_labels, rf.predict(test_embeddings))
    accuracies += str(acc3)+','
    print(acc3)
    cm3 = confusion_matrix(test_labels, rf.predict(test_embeddings))
    for i in range(3):
    	for j in range(3):
    		conf_matr += str(cm3[i][j]) + ','
    conf_matr += '\n'
    print(cm3)

    clf =  GridSearchCV(SVC(random_state=42), {'kernel': ['linear', 'poly', 'rbf'], 'C': [10**i for i in range(-3, 4)]})
    clf.fit(train_embeddings, train_labels)

    print('Support Vector Machine:')
    acc4 = accuracy_score(test_labels, clf.predict(test_embeddings))
    print(acc4)
    accuracies += str(acc4)+','
    cm4 = confusion_matrix(test_labels, clf.predict(test_embeddings))
    for i in range(3):
    	for j in range(3):
    		conf_matr += str(cm4[i][j]) + ','
    conf_matr += '\n'
    print(cm4)

    with open('resultsAccuracies.tsv', "a") as myfile:
                myfile.write(accuracies)
                myfile.write('\n\n')
                
    with open('resultsMatrix_rdf2vec.tsv', "a") as myfile:
                myfile.write(conf_matr)
                myfile.write('\n\n')

 
    # Create TSNE plots of our embeddings
    colors = ['r', 'g', 'b', 'y']
    color_map = {}
    for i, label in enumerate(set(all_labels)):
        color_map[label] = colors[i]

    f, ax = plt.subplots(1, 2, figsize=(10, 5))
    walk_tsne = TSNE(random_state=42, perplexity = 50 )
    X_walk_tsne = walk_tsne.fit_transform(walk_embeddings)
    wl_tsne = TSNE(random_state=42, perplexity = 50 )
    X_wl_tsne = wl_tsne.fit_transform(wl_embeddings)

    ax[0].scatter(X_walk_tsne[:, 0], X_walk_tsne[:, 1], c=[color_map[i] for i in all_labels])
    ax[1].scatter(X_wl_tsne[:, 0], X_wl_tsne[:, 1], c=[color_map[i] for i in all_labels])
    ax[0].set_title('Walk Embeddings')
    ax[1].set_title('Weisfeiler-Lehman Embeddings')
    plt.show()


if __name__ == "__main__":
	args = parse_args()
	for i in range(10):
		main(args)