-
Notifications
You must be signed in to change notification settings - Fork 109
/
config.py
1652 lines (1389 loc) · 75.8 KB
/
config.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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
config.py
==========
This module consists of definition of the necessary configuration parameters for all the
core algorithms. The parameters are seprated into global parameters which are common
across all the algorithms, and local parameters which are specific to the algorithms.
"""
from argparse import ArgumentParser
import importlib
from pykg2vec.utils.kgcontroller import KnowledgeGraph, KGMetaData
from pykg2vec.utils.logger import Logger
from pykg2vec.config.hyperparams import HyperparamterLoader
class Importer:
"""The class defines methods for importing pykg2vec modules.
Importer is used to defines the maps for the algorithm names and
provides methods for loading configuration and models.
Attributes:
model_path (str): Path where the models are defined.
config_path (str): Path where the configuration for each models are defineds.
modelMap (dict): This map transforms the names of model to the actual class names.
configMap (dict): This map transforms the input config names to the actuall config class names.
Examples:
>>> from pykg2vec.config.config import Importer
>>> config_def, model_def = Importer().import_model_config('transe')
>>> config = config_def()
>>> model = model_def(config)
"""
_logger = Logger().get_logger(__name__)
def __init__(self):
self.model_path = "pykg2vec.core"
self.config_path = "pykg2vec.config.config"
self.modelMap = {"analogy": "ANALOGY.ANALOGY",
"complex": "Complex.Complex",
"complexn3": "Complex.ComplexN3",
"conve": "ConvE.ConvE",
"convkb": "ConvKB.ConvKB",
"cp": "CP.CP",
"hole": "HoLE.HoLE",
"distmult": "DistMult.DistMult",
"kg2e": "KG2E.KG2E",
"kg2e_el": "KG2E.KG2E_EL",
"ntn": "NTN.NTN",
"proje_pointwise": "ProjE_pointwise.ProjE_pointwise",
"rescal": "Rescal.Rescal",
"rotate": "RotatE.RotatE",
"simple": "SimplE.SimplE",
"simple_ignr": "SimplE.SimplE_ignr",
"slm": "SLM.SLM",
"sme": "SME.SME",
"sme_bl": "SME.SME_BL",
"transd": "TransD.TransD",
"transe": "TransE.TransE",
"transh": "TransH.TransH",
"transg": "TransG.TransG",
"transm": "TransM.TransM",
"transr": "TransR.TransR",
"tucker": "TuckER.TuckER"}
self.configMap = {"analogy": "ANALOGYConfig",
"complex": "ComplexConfig",
"complexn3": "ComplexConfig",
"conve": "ConvEConfig",
"convkb": "ConvKBConfig",
"cp": "CPConfig",
"hole": "HoLEConfig",
"distmult": "DistMultConfig",
"kg2e": "KG2EConfig",
"kg2e_el": "KG2EConfig",
"ntn": "NTNConfig",
"proje_pointwise": "ProjE_pointwiseConfig",
"rescal": "RescalConfig",
"rotate": "RotatEConfig",
"simple": "SimplEConfig",
"simple_ignr": "SimplEConfig",
"slm": "SLMConfig",
"sme": "SMEConfig",
"sme_bl": "SMEConfig",
"transd": "TransDConfig",
"transe": "TransEConfig",
"transg": "TransGConfig",
"transh": "TransHConfig",
"transm": "TransMConfig",
"transr": "TransRConfig",
"tucker": "TuckERConfig"}
def import_model_config(self, name):
"""This function imports models and configuration.
This function is used to dynamically import the modules within
pykg2vec.
Args:
name (str): The input to the module is either name of the model or the configuration file. The strings are converted to lowercase to makesure the user inputs can easily be matched to the names of the models and the configuration class.
Returns:
object: Configuration and model object after it is successfully loaded.
`config_obj` (object): Returns the configuration class object of the corresponding algorithm.
`model_obj` (object): Returns the model class object of the corresponding algorithm.
Raises:
ModuleNotFoundError: It raises a module not found error if the configuration or the model cannot be found.
"""
config_obj = None
model_obj = None
try:
config_obj = getattr(importlib.import_module(self.config_path), self.configMap[name])
splited_path = self.modelMap[name].split('.')
model_obj = getattr(importlib.import_module(self.model_path + ".%s" % splited_path[0]), splited_path[1])
except ModuleNotFoundError:
self._logger.error("%s model has not been implemented. please select from: %s" % (
name, ' '.join(map(str, self.modelMap.values()))))
return config_obj, model_obj
class KGEArgParser:
"""The class implements the argument parser for the pykg2vec.
KGEArgParser defines all the necessary arguements for the global and local
configuration of all the modules.
Attributes:
general_group (object): It parses the general arguements used by most of the modules.
general_hyper_group (object): It parses the arguments for the hyper-parameter tuning.
SME_group (object): It parses the arguments for SME and KG2E algorithms.
conv_group (object): It parses the arguments for convE algorithms.
misc_group (object): It prases other necessary arguments.
Examples:
>>> from pykg2vec.config.config import KGEArgParser
>>> args = KGEArgParser().get_args()
"""
def __init__(self):
self.parser = ArgumentParser(description='Knowledge Graph Embedding tunable configs.')
''' arguments regarding TransG '''
self.TransG_group = self.parser.add_argument_group('TransG function selection')
self.TransG_group.add_argument('-th', dest='training_threshold', default=3.5, type=float, help="Training Threshold for updateing the clusters.")
self.TransG_group.add_argument('-nc', dest='ncluster', default=4, type=int, help="Number of clusters")
self.TransG_group.add_argument('-crp', dest='crp_factor', default=0.01, type=float, help="Chinese Restaurant Process Factor.")
self.TransG_group.add_argument('-stb', dest='step_before', default=10, type=int, help="Steps before")
self.TransG_group.add_argument('-wn', dest='weight_norm', default=False, type=lambda x: (str(x).lower() == 'true'), help="normalize the weights!")
''' arguments regarding SME and KG2E '''
self.SME_group = self.parser.add_argument_group('SME KG2E function selection')
self.SME_group.add_argument('-func', dest='function', default='bilinear', type=str, help="The name of function used in SME model.")
self.SME_group.add_argument('-cmax', dest='cmax', default=0.05, type=float, help="The parameter for clipping values for KG2E.")
self.SME_group.add_argument('-cmin', dest='cmin', default=5.00, type=float, help="The parameter for clipping values for KG2E.")
''' for conve '''
self.conv_group = self.parser.add_argument_group('ConvE specific Hyperparameters')
self.conv_group.add_argument('-fmd', dest='feature_map_dropout', default=0.2, type=float, help="feature map dropout value used in ConvE.")
self.conv_group.add_argument('-idt', dest="input_dropout", default=0.3, type=float, help="input dropout value used in ConvE.")
self.conv_group.add_argument('-hdt', dest="hidden_dropout", default=0.3, type=float, help="hidden dropout value used in ConvE.")
self.conv_group.add_argument('-lbs', dest='label_smoothing', default=0.1, type=float, help="The parameter used in label smoothing.")
'''for convKB'''
self.convkb_group = self.parser.add_argument_group('ConvKB specific Hyperparameters')
self.convkb_group.add_argument('-fsize', dest='filter_sizes', default=[1,2,3],nargs='+', type=int, help='Filter sizes to be used in convKB which acts as the widths of the kernals')
self.convkb_group.add_argument('-fnum', dest='num_filters', default=50, type=int, help='Filter numbers to be used in convKB')
'''for RotatE'''
self.rotate_group = self.parser.add_argument_group('RotatE specific Hyperparameters')
self.rotate_group.add_argument('-al', dest='alpha', default=0.1, type=float, help='The alpha used in self-adversarial negative sampling.')
''' arguments regarding hyperparameters '''
self.general_hyper_group = self.parser.add_argument_group('Generic Hyperparameters')
self.general_hyper_group.add_argument('-lmda', dest='lmbda', default=0.1, type=float, help='The lmbda for regularization.')
self.general_hyper_group.add_argument('-b', dest='batch_training', default=128, type=int, help='training batch size')
self.general_hyper_group.add_argument('-mg', dest='margin', default=0.8, type=float, help='Margin to take')
self.general_hyper_group.add_argument('-opt', dest='optimizer', default='adam', type=str, help='optimizer to be used in training.')
self.general_hyper_group.add_argument('-s', dest='sampling', default='uniform', type=str, help='strategy to do negative sampling.')
self.general_hyper_group.add_argument('-ngr', dest='negrate', default=1, type=int, help='The number of negative samples generated per positve one.')
self.general_hyper_group.add_argument('-l', dest='epochs', default=100, type=int, help='The total number of Epochs')
self.general_hyper_group.add_argument('-lr', dest='learning_rate', default=0.01, type=float,help='learning rate')
self.general_hyper_group.add_argument('-k', dest='hidden_size', default=50, type=int,help='Hidden embedding size.')
self.general_hyper_group.add_argument('-km', dest='ent_hidden_size', default=50, type=int, help="Hidden embedding size for entities.")
self.general_hyper_group.add_argument('-kr', dest='rel_hidden_size', default=50, type=int, help="Hidden embedding size for relations.")
self.general_hyper_group.add_argument('-k2', dest='hidden_size_1', default=10, type=int, help="Hidden embedding size for relations.")
self.general_hyper_group.add_argument('-l1', dest='l1_flag', default=True, type=lambda x: (str(x).lower() == 'true'),help='The flag of using L1 or L2 norm.')
''' working environments '''
self.environment_group = self.parser.add_argument_group('Working Environments')
self.environment_group.add_argument('-gp', dest='gpu_frac', default=0.8, type=float, help='GPU fraction to use')
self.environment_group.add_argument('-npg', dest='num_process_gen', default=2, type=int, help='number of processes used in the Generator.')
''' basic configs '''
self.general_group = self.parser.add_argument_group('Generic')
self.general_group.add_argument('-mn', dest='model_name', default='TransE', type=str, help='Name of model')
self.general_group.add_argument('-db', dest='debug', default=False, type=lambda x: (str(x).lower() == 'true'), help='To use debug mode or not.')
self.general_group.add_argument('-exp', dest='exp', default=False, type=lambda x: (str(x).lower() == 'true'), help='Use Experimental setting extracted from original paper. (use with -ds or FB15k in default)')
self.general_group.add_argument('-ds', dest='dataset_name', default='Freebase15k', type=str, help='The dataset name (choice: fb15k/wn18/wn18_rr/yago/fb15k_237/ks/nations/umls)')
self.general_group.add_argument('-dsp', dest='dataset_path', default=None, type=str, help='The path to custom dataset.')
self.general_group.add_argument('-ld', dest='load_from_data', default=False, type=lambda x: (str(x).lower() == 'true'), help='load from tensroflow saved data!')
self.general_group.add_argument('-sv', dest='save_model', default=True, type=lambda x: (str(x).lower() == 'true'), help='Save the model!')
self.general_group.add_argument('-tn', dest='test_num', default=1000, type=int, help='The total number of test triples')
self.general_group.add_argument('-ts', dest='test_step', default=10, type=int, help='Test every _ epochs')
self.general_group.add_argument('-t', dest='tmp', default='../intermediate', type=str,help='The folder name to store trained parameters.')
self.general_group.add_argument('-r', dest='result', default='../results', type=str,help="The folder name to save the results.")
self.general_group.add_argument('-fig', dest='figures', default='../figures', type=str,help="The folder name to save the figures.")
self.general_group.add_argument('-plote', dest='plot_embedding', default=False,type=lambda x: (str(x).lower() == 'true'), help='Plot the entity only!')
self.general_group.add_argument('-plot', dest='plot_entity_only', default=False,type=lambda x: (str(x).lower() == 'true'), help='Plot the entity only!')
def get_args(self, args):
"""This function parses the necessary arguments.
This function is called to parse all the necessary arguments.
Returns:
object: ArgumentParser object.
"""
return self.parser.parse_args(args)
class BasicConfig:
"""The class defines the basic configuration for the pykg2vec.
BasicConfig consists of the necessary parameter description used by all the
modules including the algorithms and utility functions.
Args:
test_step (int): Testing is carried out every test_step.
test_num (int): Number of triples that will be tested during evaluation.
triple_num (int): Number of triples that will be used for plotting the embedding.
tmp (Path Object): Path where temporary model information is stored.
result (Path Object): Gives the path where the result will be saved.
figures (Path Object): Gives the path where the figures will be saved.
gpu_fraction (float): Amount of GPU fraction that will be made available for training and inference.
gpu_allow_growth (bool): If True, allocates only necessary GPU memory and grows as required later.
loadFromData (bool): If True, loads the model parameters if available from memory.
save_model (True): If True, store the trained model parameters.
disp_summary (bool): If True, display the summary before and after training the algorithm.
disp_result (bool): If True, displays result while training.
plot_embedding (bool): If True, will plot the embedding after performing t-SNE based dimensionality reduction.
log_training_placement (bool): If True, allows us to find out which devices the operations and tensors are assigned to.
plot_training_result (bool): If True, plots the loss values stored during training.
plot_testing_result (bool): If True, it will plot all the testing result such as mean rank, hit ratio, etc.
plot_entity_only (bool): If True, plots the t-SNE reduced embdding of the entities in a figure.
full_test_flag (bool): It True, performs a full test after completing the training for full epochs.
hits (List): Gives the list of integer for calculating hits.
knowledge_graph (Object): It prepares and holds the instance of the knowledge graph dataset.
kg_meta (object): Stores the statistics metadata of the knowledge graph.
"""
_logger = Logger().get_logger(__name__)
def __init__(self, args):
# Training and evaluating related variables
self.test_step = args.test_step
self.full_test_flag = (self.test_step == 0)
self.test_num = args.test_num
self.hits = [1, 3, 5, 10]
self.loadFromData = args.load_from_data
self.save_model = args.save_model
self.disp_summary = True
self.disp_result = False
self.patience = 3 # should make this configurable as well.
# Visualization related,
# p.s. the visualizer is disable for most of the KGE methods for now.
self.disp_triple_num = 20
self.plot_embedding = args.plot_embedding
self.plot_training_result = True
self.plot_testing_result = True
self.plot_entity_only = args.plot_entity_only
# Working environment variables.
self.num_process_gen = args.num_process_gen
self.log_device_placement = False
self.gpu_fraction = args.gpu_frac
self.gpu_allow_growth = True
# self.gpu_config = tf.ConfigProto(log_device_placement=self.log_device_placement)
# self.gpu_config.gpu_options.per_process_gpu_memory_fraction = self.gpu_fraction
# self.gpu_config.gpu_options.allow_growth = self.gpu_allow_growth
# Knowledge Graph Information
self.custom_dataset_path = args.dataset_path
self.knowledge_graph = KnowledgeGraph(dataset=self.data, custom_dataset_path=self.custom_dataset_path)
self.kg_meta = self.knowledge_graph.kg_meta
# The results of training will be stored in the following folders
# which are relative to the parent folder (the path of the dataset).
dataset_path = self.knowledge_graph.dataset.dataset_path
self.path_tmp = dataset_path / 'intermediate'
self.path_tmp.mkdir(parents=True, exist_ok=True)
self.path_result = dataset_path / 'results'
self.path_result.mkdir(parents=True, exist_ok=True)
self.path_figures = dataset_path / 'figures'
self.path_figures.mkdir(parents=True, exist_ok=True)
self.path_embeddings = dataset_path / 'embeddings'
self.path_embeddings.mkdir(parents=True, exist_ok=True)
# debugging information
self.debug = args.debug
def summary(self):
"""Function to print the summary."""
summary = []
summary.append("")
summary.append("------------------Global Setting--------------------")
# Acquire the max length and add four more spaces
maxspace = len(max([k for k in self.__dict__.keys()])) +20
for key, val in self.__dict__.items():
if key in self.__dict__['hyperparameters']:
continue
if isinstance(val, (KGMetaData, KnowledgeGraph)) or key.startswith('gpu') or key.startswith('hyperparameters'):
continue
if len(key) < maxspace:
for i in range(maxspace - len(key)):
key = ' ' + key
summary.append("%s : %s"%(key, val))
summary.append("---------------------------------------------------")
summary.append("")
self._logger.info("\n".join(summary))
def summary_hyperparameter(self, model_name):
"""Function to print the hyperparameter summary."""
summary_hyperparameter = []
summary_hyperparameter.append("")
summary_hyperparameter.append("-----------%s Hyperparameter Setting-------------"%(model_name))
maxspace = len(max([k for k in self.hyperparameters.keys()])) + 15
for key,val in self.hyperparameters.items():
if len(key) < maxspace:
for i in range(maxspace - len(key)):
key = ' ' + key
summary_hyperparameter.append("%s : %s" % (key, val))
summary_hyperparameter.append("---------------------------------------------------")
self._logger.info("\n".join(summary_hyperparameter))
class TransEConfig(BasicConfig):
"""This class defines the configuration for the TransE Algorithm.
TransEConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
hidden_size (int): Defines the size of the latent dimension for both entities and relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.hidden_size = args.hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'transe')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'hidden_size': self.hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class HoLEConfig(BasicConfig):
"""This class defines the configuration for the HoLE Algorithm.
HoLEConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
hidden_size (int): Defines the size of the latent dimension for both entities and relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.hidden_size = args.hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'hole')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'hidden_size': self.hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class TransRConfig(BasicConfig):
"""This class defines the configuration for the TransR Algorithm.
TransRConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
ent_hidden_size (int): Defines the size of the latent dimension for entities.
rel_hidden_size (int): Defines the size of the latent dimension for relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.ent_hidden_size = args.ent_hidden_size
self.rel_hidden_size = args.rel_hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'transr')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'ent_hidden_size': self.ent_hidden_size,
'rel_hidden_size': self.rel_hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class TransDConfig(BasicConfig):
"""This class defines the configuration for the TransD Algorithm.
TransDConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
ent_hidden_size (int): Defines the size of the latent dimension for entities.
rel_hidden_size (int): Defines the size of the latent dimension for relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.ent_hidden_size = args.ent_hidden_size
self.rel_hidden_size = args.rel_hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'transd')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'ent_hidden_size': self.ent_hidden_size,
'rel_hidden_size': self.rel_hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class TransMConfig(BasicConfig):
"""This class defines the configuration for the TransM Algorithm.
TransMConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
hidden_size (int): Defines the size of the latent dimension for entities and relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.hidden_size = args.hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'transm')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'hidden_size': self.hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class TransHConfig(BasicConfig):
"""This class defines the configuration for the TransH Algorithm.
TransHConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
hidden_size (int): Defines the size of the latent dimension for entities and relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
C (float) : It is used to weigh the importance of soft-constraints.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.hidden_size = args.hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'transh')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'hidden_size': self.hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class RescalConfig(BasicConfig):
"""This class defines the configuration for the Rescal Algorithm.
RescalConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
hidden_size (int): Defines the size of the latent dimension for entities and relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.hidden_size = args.hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'rescal')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'hidden_size': self.hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class SMEConfig(BasicConfig):
"""This class defines the configuration for the SME Algorithm.
SMEConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
hidden_size (int): Defines the size of the latent dimension for entities and relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
bilinear (bool): If true uses bilnear transformation for loss else uses linear.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.hidden_size = args.hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = 1
self.margin = 1.0
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'sme')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'hidden_size': self.hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'optimizer': self.optimizer,
'sampling': self.sampling,
'margin': self.margin,
}
BasicConfig.__init__(self, args)
class NTNConfig(BasicConfig):
"""This class defines the configuration for the NTN Algorithm.
NTNConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
ent_hidden_size (int): Defines the size of the latent dimension for entities.
rel_hidden_size (int): Defines the size of the latent dimension for relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.lmbda = args.lmbda
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.ent_hidden_size = args.ent_hidden_size
self.rel_hidden_size = args.rel_hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
self.margin = 1.0
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'ntn')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'lmbda': self.lmbda,
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'ent_hidden_size': self.ent_hidden_size,
'rel_hidden_size': self.rel_hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class SLMConfig(BasicConfig):
"""This class defines the configuration for the SLM Algorithm.
SLMConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
ent_hidden_size (int): Defines the size of the latent dimension for entities.
rel_hidden_size (int): Defines the size of the latent dimension for relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.ent_hidden_size = args.ent_hidden_size
self.rel_hidden_size = args.rel_hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'slm')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'ent_hidden_size': self.ent_hidden_size,
'rel_hidden_size': self.rel_hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
}
BasicConfig.__init__(self, args)
class RotatEConfig(BasicConfig):
"""This class defines the configuration for the RotatE Algorithm.
RotatEDConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
hidden_size (int): Defines the size of the latent dimension for entities and relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.hidden_size = args.hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.neg_rate = args.negrate
self.alpha = args.alpha
if args.exp is True:
paper_params = HyperparamterLoader().load_hyperparameter(args.dataset_name, 'rotate')
for key, value in paper_params.items():
self.__dict__[key] = value # copy all the setting from the paper.
self.hyperparameters = {
'learning_rate': self.learning_rate,
'L1_flag': self.L1_flag,
'hidden_size': self.hidden_size,
'batch_size': self.batch_size,
'epochs': self.epochs,
'margin': self.margin,
'data': self.data,
'optimizer': self.optimizer,
'sampling': self.sampling,
'neg_rate': self.neg_rate,
'alpha': self.alpha
}
BasicConfig.__init__(self, args)
class KG2EConfig(BasicConfig):
"""This class defines the configuration for the KG2E Algorithm.
KG2EConfig inherits the BasicConfig and defines the local arguements used in the
algorithm.
Attributes:
hyperparameters (dict): Defines the dictionary of hyperparameters to be used by bayesian optimizer for tuning.
Args:
learning_rate (float): Defines the learning rate for the optimization.
L1_flag (bool): If True, perform L1 regularization on the model parameters.
hidden_size (int): Defines the size of the latent dimension for entities and relations.
batch_size (int): Defines the batch size for training the algorithm.
epochs (int): Defines the total number of epochs for training the algorithm.
margin (float): Defines the margin used between the positive and negative triple loss.
data (str): Defines the knowledge base dataset to be used for training the algorithm.
optimizer (str): Defines the optimization algorithm such as adam, sgd, adagrad, etc.
sampling (str): Defines the sampling (bern or uniform) for corrupting the triples.
bilinear (bool): If True, sets the transformaton to be bilinear.
distance_measure (str): Uses either kl_divergence or expected_likelihood as distance measure.
cmax (float): Sets the upper clipping range for the embedding.
cmin (float): Sets the lower clipping range for the embedding.
"""
def __init__(self, args=None):
self.learning_rate = args.learning_rate
self.L1_flag = args.l1_flag
self.hidden_size = args.hidden_size
self.batch_size = args.batch_training
self.epochs = args.epochs
self.margin = args.margin
self.data = args.dataset_name
self.optimizer = args.optimizer
self.sampling = args.sampling
self.cmax = args.cmax
self.cmin = args.cmin
self.neg_rate = args.negrate
if args.exp is True: