forked from stellargraph/stellargraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_node_splitter.py
977 lines (854 loc) · 31.2 KB
/
test_node_splitter.py
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
# -*- coding: utf-8 -*-
#
# Copyright 2017-2018 Data61, CSIRO
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import uuid
import os
import numpy as np
import itertools as it
import networkx as nx
import pandas as pd
import pytest
from stellargraph.core.graph import StellarGraph
from stellargraph.data.node_splitter import NodeSplitter, train_val_test_split
from stellargraph.data.epgm import EPGM
from stellargraph import globalvar
from datetime import datetime, timedelta
import random
def create_heterogeneous_graph():
g = nx.Graph()
random.seed(152) # produces the same graph every time
start_date_dt = datetime.strptime("01/01/2015", "%d/%m/%Y")
end_date_dt = datetime.strptime("01/01/2017", "%d/%m/%Y")
start_end_days = (
end_date_dt - start_date_dt
).days # the number of days between start and end dates
# 50 nodes of type person
person_node_ids = list(range(0, 50))
for person in person_node_ids:
g.add_node(person, label="person", elite=random.choice(["0", "1", "-1"]))
# 200 nodes of type paper
paper_node_ids = list(range(50, 250))
g.add_nodes_from(paper_node_ids, label="paper")
# 10 nodes of type venue
venue_node_ids = list(range(250, 260))
g.add_nodes_from(venue_node_ids, label="venue")
# add the person - friend -> person edges
# each person can be friends with 0 to 5 others; edges include a date
for person_id in person_node_ids:
k = random.randrange(5)
friend_ids = set(random.sample(person_node_ids, k=k)) - {
person_id
} # no self loops
for friend in friend_ids:
g.add_edge(
person_id,
friend,
label="friend",
date=(
start_date_dt + timedelta(days=random.randrange(start_end_days))
).strftime("%d/%m/%Y"),
)
# add the person - writes -> paper edges
for person_id in person_node_ids:
k = random.randrange(5)
paper_ids = random.sample(paper_node_ids, k=k)
for paper in paper_ids:
g.add_edge(person_id, paper, label="writes")
# add the paper - published-at -> venue edges
for paper_id in paper_node_ids:
venue_id = random.sample(venue_node_ids, k=1)[
0
] # paper is published at 1 venue only
g.add_edge(paper_id, venue_id, label="published-at")
return g
def delete_files_in_dir(path):
for filename in os.listdir(path):
filename_path = os.path.join(path, filename)
if os.path.isfile(filename_path):
os.unlink(filename_path)
def filter_nodes(nodes, node_type, target_attribute):
"""
Returns a list of node IDs for the subset of graph_nodes that have the given node type.
Args:
nodes: <list> The node data as a list of tuples where for each node the first value is the node ID and the
second value is a dictionary holding the node attribute data.
node_type: <str> The node type to filter by
target_attribute: <str> The target attribute key to filter by
Returns:
<list> List of 2-tuples where the first value is the node ID and the second value is the target attribute
value.
"""
# This code will fail if a node of node_type is missing the target_attribute.
# We can fix this by using node['data'].get(target_attribute, None) so that at least all nodes of the
# given type are returned. However, we must check for None in target_attribute later to exclude these nodes
# from being added to train, test, and validation datasets.
y = [
(node[0], node[1].get(target_attribute, globalvar.UNKNOWN_TARGET_ATTRIBUTE))
for node in nodes
if node[1][globalvar.TYPE_ATTR_NAME] == node_type
]
return y
def get_nodes(graph_nodes, node_type, target_attribute):
"""
Returns a list of node IDs for the subset of graph_nodes that have the given node type.
Args:
graph_nodes: <list> List of OrderedDict with vertex data for graph in EPGM format
node_type: <str> The node type of interest
target_attribute: <str> The target attribute key
Returns:
List of 2-tuples where the first value is the node ID and the second value is the target attribute
value.
"""
# This code will fail if a node of node_type is missing the target_attribute.
# We can fix this by using node['data'].get(target_attribute, None) so that at least all nodes of the
# given type are returned. However, we must check for None in target_attribute later to exclude these nodes
# from being added to train, test, and validation datasets.
y = [
(
node["id"],
node["data"].get(target_attribute, globalvar.UNKNOWN_TARGET_ATTRIBUTE),
)
for node in graph_nodes
if node["meta"][globalvar.TYPE_ATTR_NAME] == node_type
]
return y
def load_data(path, dataset_name=None, node_type=None, target_attribute=None):
"""
Loads the node data
:param path: Input filename or directory where graph in EPGM format is stored
:param node_type: For HINs, the node type to consider
:param target_attribute: For EPGM format, the target node attribute
:return: N x 2 numpy arrays where the first column is the node id and the second column is the node label.
"""
if os.path.isdir(path):
g_epgm = EPGM(path)
graphs = g_epgm.G["graphs"]
for g in graphs:
if g["meta"]["label"] == dataset_name:
g_id = g["id"]
g_vertices = g_epgm.G["vertices"] # retrieve all graph vertices
if node_type is None:
node_type = g_epgm.node_types(g_id)
if len(node_type) == 1:
node_type = node_type[0]
else:
raise Exception(
"Multiple node types detected in graph {}: {}.".format(
g_id, node_type
)
)
if target_attribute is None:
target_attribute = g_epgm.node_attributes(g_id, node_type)
if len(target_attribute) == 1:
target_attribute = target_attribute[0]
else:
raise Exception(
"Multiple node attributes detected for nodes of type {} in graph {}: {}.".format(
node_type, g_id, target_attribute
)
)
y = np.array(
get_nodes(
g_vertices, node_type=node_type, target_attribute=target_attribute
)
)
else:
y_df = pd.read_csv(path, delimiter=" ", header=None, dtype=str)
y_df.sort_values(by=[0], inplace=True)
y = y_df.values
return y
class TestEPGMIOHeterogeneous(unittest.TestCase):
def setUp(self):
self.node_type = "person"
self.target_attribute = "elite"
self.ds_obj = NodeSplitter()
def test_train_test_split_invalid_parameters(self):
nc = 10
test_size = 100
method = "count"
g = create_heterogeneous_graph()
y = np.array(
filter_nodes(
list(g.nodes(data=True)),
node_type=self.node_type,
target_attribute=self.target_attribute,
)
)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=None, # this will raise a ValueError exception
p=nc,
method=method,
test_size=test_size,
)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y,
p=-1,
method=method,
test_size=test_size, # this will raise a ValueError exception
)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y,
p=1.2, # this will raise a ValueError exception
method=method,
test_size=test_size,
)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y,
p=0,
method=method,
test_size=test_size, # this will raise a ValueError exception
)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, p=nc, method=method, test_size=0
) # this will raise a ValueError exception
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, p=nc, method=method, test_size=-100
) # this will raise a ValueError exception
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, p=nc, method=method, test_size=99.10101
) # this will raise a ValueError exception
# check parameter values for 'percent' method
method = "percent"
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, p=1.1, method=method # must be less than 1.
)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, p=-0.5, method=method # must be greater than or equalt 0.
)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, p=10, method=method # must be float in range (0, 1)
)
# check parameter values for 'absolute' method
method = "absolute"
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, method=method, p=0.25
) # must specify train_size and test_size parameters, p is not used
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, method=method, test_size=0, train_size=1000
)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(y=y, method=method, test_size=99, train_size=0)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y, method=method, test_size=0.25, train_size=0.75
) # test_size and train_size should be integers not percentages
# test invalid method
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(
y=y,
method="other", # valid values are 'percent', 'count', and 'absolute'
p=nc,
test_size=test_size,
)
# testing seed value
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(y=y, p=nc, test_size=100, seed=-1003)
with self.assertRaises(ValueError):
self.ds_obj.train_test_split(y=y, p=nc, test_size=100, seed=101.13)
def test_split_data_epgm(self):
nc = 5
test_size = 20
g = create_heterogeneous_graph()
y = np.array(
filter_nodes(
list(g.nodes(data=True)),
node_type=self.node_type,
target_attribute=self.target_attribute,
)
)
num_unlabeled = sum(l == "-1" for l in y[:, 1])
number_of_unique_labels = (
len(np.unique(y[:, 1])) - 1
) # subtract one for missing value (-1) label
validation_size = (
y.shape[0] - test_size - nc * number_of_unique_labels - num_unlabeled
)
self.y_train, self.y_val, self.y_test, self.y_unlabeled = self.ds_obj.train_test_split(
y=y, p=nc, test_size=test_size
)
print(self.y_val, self.y_unlabeled)
self.assertEqual(
self.y_test.shape[0],
test_size,
"Test dataset has wrong size {:d} vs expected {:d}".format(
self.y_test.shape[0], test_size
),
)
self.assertEqual(
self.y_train.shape[0],
nc * number_of_unique_labels,
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_train.shape[0], nc * number_of_unique_labels
),
)
self.assertEqual(
self.y_val.shape[0],
validation_size,
"Val dataset has wrong size {:d} vs expected {:d}".format(
self.y_val.shape[0], validation_size
),
)
class TestEPGMIOHomogenous(unittest.TestCase):
def setUp(self):
if os.getcwd().split("/")[-1] == "tests":
self.input_dir = os.path.expanduser("resources/data/cora/cora.epgm")
self.input_lab = os.path.expanduser("resources/data/cora/cora.lab/cora.lab")
else:
self.input_dir = os.path.expanduser("tests/resources/data/cora/cora.epgm")
self.input_lab = os.path.expanduser(
"tests/resources/data/cora/cora.lab/cora.lab"
)
self.dataset_name = "cora"
self.node_type = "paper"
self.target_attribute = "subject"
self.ds_obj = NodeSplitter()
def create_toy_dataset(self):
# 100 node ids with 40 class 0, 40 class 1, and 20 unknown '-1'
node_ids = [uuid.uuid4() for i in np.arange(100)]
labels = ["-1"] * 100
labels[0:40] = [0] * 40
labels[40:80] = [1] * 40
y = np.transpose(np.vstack((node_ids, labels)))
return y
def test_split_with_percent(self):
method = "percent"
p = 0.5
y = self.create_toy_dataset()
y_train, y_val, y_test, y_unlabeled = self.ds_obj.train_test_split(
y=y, p=p, method=method
)
self.assertEqual(
y_train.shape,
(40, 2),
"Train set size is incorrect, expected (40, 2) but received {}".format(
y_train.shape
),
)
self.assertEqual(
y_test.shape,
(40, 2),
"Test set size is incorrect, expected (40, 2) but received {}".format(
y_test.shape
),
)
self.assertEqual(
y_unlabeled.shape,
(20, 2),
"Unlabeled set size is incorrect, expected (20, 2) but received {}".format(
y_unlabeled.shape
),
)
self.assertEqual(
y_val.shape,
(0, 2),
"Validation set size is incorrect, expected (0, 2) but received {}".format(
y_val.shape
),
)
p = 0.33
y_train, y_val, y_test, y_unlabeled = self.ds_obj.train_test_split(
y=y, p=p, method=method
)
self.assertEqual(
y_train.shape,
(26, 2),
"Train set size is incorrect, expected (26, 2) but received {}".format(
y_train.shape
),
)
self.assertEqual(
y_test.shape,
(54, 2),
"Test set size is incorrect, expected (54, 2) but received {}".format(
y_test.shape
),
)
self.assertEqual(
y_unlabeled.shape,
(20, 2),
"Unlabeled set size is incorrect, expected (20, 2) but received {}".format(
y_unlabeled.shape
),
)
self.assertEqual(
y_val.shape,
(0, 2),
"Validation set size is incorrect, expected (0, 2) but received {}".format(
y_val.shape
),
)
p = 0.75
y_train, y_val, y_test, y_unlabeled = self.ds_obj.train_test_split(
y=y, p=p, method=method
)
self.assertEqual(
y_train.shape,
(60, 2),
"Train set size is incorrect, expected (60, 2) but received {}".format(
y_train.shape
),
)
self.assertEqual(
y_test.shape,
(20, 2),
"Test set size is incorrect, expected (20, 2) but received {}".format(
y_test.shape
),
)
self.assertEqual(
y_unlabeled.shape,
(20, 2),
"Unlabeled set size is incorrect, expected (20, 2) but received {}".format(
y_unlabeled.shape
),
)
self.assertEqual(
y_val.shape,
(0, 2),
"Validation set size is incorrect, expected (0, 2) but received {}".format(
y_val.shape
),
)
# remove points with UNKNOWN_TARGET_ATTRIBUTE
y[80:, 1] = "2"
y_train, y_val, y_test, y_unlabeled = self.ds_obj.train_test_split(
y=y, p=p, method=method
)
self.assertEqual(
y_train.shape,
(75, 2),
"Train set size is incorrect, expected (75, 2) but received {}".format(
y_train.shape
),
)
self.assertEqual(
y_test.shape,
(25, 2),
"Test set size is incorrect, expected (25, 2) but received {}".format(
y_test.shape
),
)
self.assertEqual(
y_unlabeled.shape,
(0, 2),
"Unlabeled set size is incorrect, expected (0, 2) but received {}".format(
y_unlabeled.shape
),
)
self.assertEqual(
y_val.shape,
(0, 2),
"Validation set size is incorrect, expected (0, 2) but received {}".format(
y_val.shape
),
)
p = 0.33
y_train, y_val, y_test, y_unlabeled = self.ds_obj.train_test_split(
y=y, p=p, method=method
)
self.assertEqual(
y_train.shape,
(33, 2),
"Train set size is incorrect, expected (33, 2) but received {}".format(
y_train.shape
),
)
self.assertEqual(
y_test.shape,
(67, 2),
"Test set siz e is incorrect, expected (67, 2) but received {}".format(
y_test.shape
),
)
self.assertEqual(
y_unlabeled.shape,
(0, 2),
"Unlabeled set size is incorrect, expected (0, 2) but received {}".format(
y_unlabeled.shape
),
)
self.assertEqual(
y_val.shape,
(0, 2),
"Validation set size is incorrect, expected (0, 2) but received {}".format(
y_val.shape
),
)
def test_split_data_lab(self):
nc = 20
test_size = 100
method = "count"
# this operation is also performed in test_load_epgm() but the call to setUp sets self.y to None so
# I have to load the data again.
y = load_data(
self.input_lab,
dataset_name=self.dataset_name,
node_type=self.node_type,
target_attribute=self.target_attribute,
)
number_of_unique_labels = len(np.unique(y[:, 1]))
validation_size = y.shape[0] - test_size - nc * number_of_unique_labels
#
# Test using method 'count'
#
self.y_train, self.y_val, self.y_test, self.y_unlabeled = self.ds_obj.train_test_split(
y=y, p=nc, test_size=test_size
)
self.assertEqual(
self.y_test.shape[0],
test_size,
"Test dataset has wrong size {:d} vs expected {:d}".format(
self.y_test.shape[0], test_size
),
)
self.assertEqual(
self.y_train.shape[0],
nc * number_of_unique_labels,
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_train.shape[0], nc * number_of_unique_labels
),
)
self.assertEqual(
self.y_val.shape[0],
validation_size,
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_val.shape[0], validation_size
),
)
#
# Test using method 'percent'
#
p = 0.75
method = "percent"
# y_val should be empty
self.y_train, self.y_val, self.y_test, self.y_unlabeled = self.ds_obj.train_test_split(
y=y, p=p, method=method
)
self.assertEqual(len(self.y_val), 0, "Validation set should be empty.")
self.assertEqual(
y.shape[0],
self.y_train.shape[0] + self.y_test.shape[0] + self.y_unlabeled.shape[0],
"The total number of points sampled is not equal to the size of y. Sampled {:d} vs expected {:d}".format(
self.y_train.shape[0]
+ self.y_test.shape[0]
+ self.y_unlabeled.shape[0],
y.shape[0],
),
)
self.assertEqual(
self.y_train.shape[0],
int(y.shape[0] * p),
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_train.shape[0], int(y.shape[0] * p)
),
)
self.assertEqual(
self.y_test.shape[0],
int(y.shape[0] * (1.0 - p)),
"Test dataset has wrong size {:d} vs expected {:d}".format(
self.y_test.shape[0], int(y.shape[0] * (1.0 - p))
),
)
#
# Test using method 'absolute'
#
method = "absolute"
train_size = 1000
test_size = 98
# y_val should be empty
self.y_train, self.y_val, self.y_test, self.y_unlabeled = self.ds_obj.train_test_split(
y=y, method=method, test_size=test_size, train_size=train_size
)
validation_size = y.shape[0] - (
train_size + test_size + self.y_unlabeled.shape[0]
)
self.assertEqual(
self.y_val.shape[0], validation_size, "Validation set has incorrect size."
)
self.assertEqual(
y.shape[0],
self.y_train.shape[0]
+ self.y_test.shape[0]
+ self.y_unlabeled.shape[0]
+ self.y_val.shape[0],
"The total number of points sampled is not equal to the size of y. Sampled {:d} vs expected {:d}".format(
self.y_train.shape[0]
+ self.y_test.shape[0]
+ self.y_unlabeled.shape[0]
+ self.y_val.shape[0],
y.shape[0],
),
)
self.assertEqual(
self.y_train.shape[0],
train_size,
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_train.shape[0], train_size
),
)
self.assertEqual(
self.y_test.shape[0],
test_size,
"Test dataset has wrong size {:d} vs expected {:d}".format(
self.y_test.shape[0], test_size
),
)
def test_split_data_epgm(self):
nc = 20
test_size = 100
y = load_data(
self.input_dir,
dataset_name=self.dataset_name,
node_type=self.node_type,
target_attribute=self.target_attribute,
)
number_of_unique_labels = len(np.unique(y[:, 1]))
validation_size = y.shape[0] - test_size - nc * number_of_unique_labels
self.y_train, self.y_val, self.y_test, self.y_unlabeled = self.ds_obj.train_test_split(
y=y, p=nc, test_size=test_size
)
self.assertEqual(
self.y_test.shape[0],
test_size,
"Test dataset has wrong size {:d} vs expected {:d}".format(
self.y_test.shape[0], test_size
),
)
self.assertEqual(
self.y_train.shape[0],
nc * number_of_unique_labels,
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_train.shape[0], nc * number_of_unique_labels
),
)
self.assertEqual(
self.y_val.shape[0],
validation_size,
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_val.shape[0], validation_size
),
)
#
# Test using method 'percent'
#
p = 0.5
method = "percent"
# y_val should be empty
self.y_train, self.y_val, self.y_test, self.y_unlabeled = self.ds_obj.train_test_split(
y=y, p=p, method=method
)
self.assertEqual(len(self.y_val), 0, "Validation set should be empty.")
self.assertEqual(
y.shape[0],
self.y_train.shape[0] + self.y_test.shape[0] + self.y_unlabeled.shape[0],
"The total number of points sampled is not equal to the size of y. Sampled {:d} vs expected {:d}".format(
self.y_train.shape[0]
+ self.y_test.shape[0]
+ self.y_unlabeled.shape[0],
y.shape[0],
),
)
self.assertEqual(
self.y_train.shape[0],
int(y.shape[0] * p),
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_train.shape[0], int(y.shape[0] * p)
),
)
self.assertEqual(
self.y_test.shape[0],
int(y.shape[0] * (1.0 - p)),
"Test dataset has wrong size {:d} vs expected {:d}".format(
self.y_test.shape[0], int(y.shape[0] * (1.0 - p))
),
)
#
# Test using method 'absolute'
#
method = "absolute"
train_size = 299
test_size = 101
# y_val should be empty
self.y_train, self.y_val, self.y_test, self.y_unlabeled = self.ds_obj.train_test_split(
y=y, method=method, test_size=test_size, train_size=train_size
)
validation_size = y.shape[0] - (
train_size + test_size + self.y_unlabeled.shape[0]
)
self.assertEqual(
self.y_val.shape[0], validation_size, "Validation set has incorrect size."
)
self.assertEqual(
y.shape[0],
self.y_train.shape[0]
+ self.y_test.shape[0]
+ self.y_unlabeled.shape[0]
+ self.y_val.shape[0],
"The total number of points sampled is not equal to the size of y. Sampled {:d} vs expected {:d}".format(
self.y_train.shape[0]
+ self.y_test.shape[0]
+ self.y_unlabeled.shape[0]
+ self.y_val.shape[0],
y.shape[0],
),
)
self.assertEqual(
self.y_train.shape[0],
train_size,
"Train dataset has wrong size {:d} vs expected {:d}".format(
self.y_train.shape[0], train_size
),
)
self.assertEqual(
self.y_test.shape[0],
test_size,
"Test dataset has wrong size {:d} vs expected {:d}".format(
self.y_test.shape[0], test_size
),
)
##################
# Test the simple node_splitter interface:
def create_example_graph_1():
g = nx.Graph()
g.add_nodes_from([0, 1, 2, 3], label="movie")
g.add_nodes_from([4, 5, 6], label="person")
g.add_edges_from([(4, 0), (4, 1), (5, 1), (4, 2), (5, 3)], label="rating")
g.add_edges_from([(0, 4), (1, 4), (1, 5), (2, 4), (3, 5)], label="another")
g.add_edges_from([(4, 5)], label="friend")
return g
def create_example_graph_2():
g = nx.Graph()
g.add_nodes_from([0, 1, 2, "3", 4, 5, 6], label="default")
g.add_edges_from([(4, 0), (4, 1), (5, 1), (4, 2), (5, "3")], label="default")
return g
def test_split_function():
# Example graph:
for g in [create_example_graph_1(), create_example_graph_2()]:
splits = train_val_test_split(
g,
node_type=None,
test_size=2,
train_size=3,
targets=None,
split_equally=False,
seed=None,
)
assert len(splits[0]) == 3
assert len(splits[1]) == 2
assert len(splits[2]) == 2
assert len(splits[3]) == 0
print(splits)
# Make sure the nodeIDs can be found in the graph
assert all(s in g for s in it.chain(*splits))
def test_split_function_percent():
# Example graph:
for g in [create_example_graph_1(), create_example_graph_2()]:
# Test splits by proportion - note floor of the
# number of samples
splits = train_val_test_split(
g,
node_type=None,
test_size=2.8 / 7,
train_size=3.2 / 7,
targets=None,
seed=None,
)
# Note the length of val is still 2 even though we requested 1
assert len(splits[0]) == 3
assert len(splits[1]) == 2
assert len(splits[2]) == 2
assert len(splits[3]) == 0
print(splits)
# Make sure the nodeIDs can be found in the graph
assert all(s in g for s in it.chain(*splits))
def test_split_function_split_equally():
# Example graph:
g = create_example_graph_2()
# We have to have a target value for the nodes
targets = {n: int(2 * ii / g.number_of_nodes()) for ii, n in enumerate(g)}
splits = train_val_test_split(
g,
node_type=None,
test_size=2,
train_size=4,
targets=targets,
split_equally=True,
seed=None,
)
# For this number of nodes we should have 50% of the nodes as label 1
assert sum(targets[s] for s in splits[0]) == len(splits[0]) // 2
# Make sure the nodeIDs can be found in the graph
assert all(s in g for s in it.chain(*splits))
def test_split_function_node_type():
# Example graph:
g = create_example_graph_1()
# This doesn't work if g is not a StellarGraph
with pytest.raises(TypeError):
splits = train_val_test_split(
g,
node_type="movie",
test_size=1,
train_size=2,
targets=None,
split_equally=False,
seed=None,
)
gs = StellarGraph(g)
splits = train_val_test_split(
gs,
node_type="movie",
test_size=1,
train_size=2,
targets=None,
split_equally=False,
seed=None,
)
assert all(g.node[s]["label"] == "movie" for split in splits for s in split)
def test_split_function_unlabelled():
# Example graph:
sg = create_example_graph_1()
# Leave some of the nodes unlabelled:
targets = {}
for ii, n in enumerate(sg):
if ii > 2:
targets[n] = 1
splits = train_val_test_split(
sg,
node_type=None,
test_size=2,
train_size=2,
targets=targets,
split_equally=False,
seed=None,
)
# For this number of nodes we should have 50% of the nodes as label 1
# Note the length of val is still 2 even though we requested 1
assert len(splits[0]) == 2
assert len(splits[1]) == 0
assert len(splits[2]) == 2
assert len(splits[3]) == 3