/
aglaia.py
2666 lines (2095 loc) · 114 KB
/
aglaia.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
# MIT License
#
# Copyright (c) 2018 Silvia Amabilino, Lars Andersen Bratholm
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Module containing the general neural network class and the child classes for the molecular and atomic neural networks.
"""
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from sklearn.base import BaseEstimator
from .symm_funct import generate_acsf_tf
from ..utils.utils import InputError, ceil, is_positive_or_zero, is_positive_integer, is_positive, \
is_bool, is_positive_integer_or_zero, is_string, is_positive_integer_array, is_array_like, \
check_global_representation, check_y, check_sizes, check_dy, check_classes, is_numeric_array, is_non_zero_integer, \
is_positive_integer_or_zero_array, check_local_representation
from qml.aglaia.tf_utils import TensorBoardLogger
from qml.representations import generate_acsf
from qml.aglaia.graceful_killer import _GracefulKiller
from qml import Compound
from qml import representations as qml_rep
import tensorflow
class _NN(BaseEstimator):
"""
Parent class for training multi-layered neural networks on molecular or atomic properties via Tensorflow
"""
def __init__(self, hidden_layer_sizes, l1_reg, l2_reg, batch_size, learning_rate,
iterations, tensorboard, store_frequency, tf_dtype, scoring_function,
activation_function, optimiser, beta1, beta2, epsilon,
rho, initial_accumulator_value, initial_gradient_squared_accumulator_value,
l1_regularization_strength,l2_regularization_strength, tensorboard_subdir):
"""
:param hidden_layer_sizes: Number of hidden layers. The n'th element represents the number of neurons in the n'th
hidden layer.
:type hidden_layer_size: Tuple of integers
:param l1_reg: L1-regularisation parameter for the neural network weights
:type l1_reg: float
:param l2_reg: L2-regularisation parameter for the neural network weights
:type l2_reg: float
:param batch_size: Size of minibatches for the ADAM optimizer. If set to 'auto' ``batch_size = min(200,n_samples)``
:type batch_size: integer
:param learning_rate: The learning rate in the numerical minimisation.
:type learning_rate: float
:param iterations: Total number of iterations that will be carried out during the training process.
:type iterations: integer
:param tf_dtype: Accuracy to use for floating point operations in tensorflow. 64 and 'float64' is recognised as tf.float64
and similar for tf.float32 and tf.float16.
:type tf_dtype: Tensorflow datatype
:param scoring_function: Scoring function to use. Available choices are 'mae', 'rmse', 'r2'.
:type scoring_function: string
:param activation_function: Activation function to use in the neural network. Currently 'sigmoid', 'tanh', 'elu', 'softplus',
'softsign', 'relu', 'relu6', 'crelu' and 'relu_x' is supported.
:type activation_function: Tensorflow datatype
:param beta1: parameter for AdamOptimizer
:type beta1: float
:param beta2: parameter for AdamOptimizer
:type beta2: float
:param epsilon: parameter for AdadeltaOptimizer
:type epsilon: float
:param rho: parameter for AdadeltaOptimizer
:type rho: float
:param initial_accumulator_value: parameter for AdagradOptimizer
:type initial_accumulator_value: float
:param initial_gradient_squared_accumulator_value: parameter for AdagradDAOptimizer
:type initial_gradient_squared_accumulator_value: float
:param l1_regularization_strength: parameter for AdagradDAOptimizer
:type l1_regularization_strength: float
:param l2_regularization_strength: parameter for AdagradDAOptimizer
:type l2_regularization_strength: float
:param tensorboard: Store summaries to tensorboard or not
:type tensorboard: boolean
:param store_frequency: How often to store summaries to tensorboard.
:type store_frequency: integer
:param tensorboard_subdir: Directory to store tensorboard data
:type tensorboard_subdir: string
"""
super(_NN,self).__init__()
# Initialising the parameters
self._set_hidden_layers_sizes(hidden_layer_sizes)
self._set_l1_reg(l1_reg)
self._set_l2_reg(l2_reg)
self._set_batch_size(batch_size)
self._set_learning_rate(learning_rate)
self._set_iterations(iterations)
self._set_tf_dtype(tf_dtype)
self._set_scoring_function(scoring_function)
self._set_tensorboard(tensorboard, store_frequency, tensorboard_subdir)
self._set_activation_function(activation_function)
# Placeholder variables
self.n_features = None
self.n_samples = None
self.training_cost = []
self.session = None
# Setting the optimiser
self._set_optimiser_param(beta1, beta2, epsilon, rho, initial_accumulator_value,
initial_gradient_squared_accumulator_value, l1_regularization_strength,
l2_regularization_strength)
self.optimiser = self._set_optimiser_type(optimiser)
# Placholder variables for data
self.compounds = None
self.representation = None
self.properties = None
self.gradients = None
self.classes = None
# To enable restart model
self.loaded_model = False
def _set_activation_function(self, activation_function):
"""
This function sets which activation function will be used in the model.
:param activation_function: name of the activation function to use
:type activation_function: string or tf class
:return: None
"""
if activation_function in ['sigmoid', tf.nn.sigmoid]:
self.activation_function = tf.nn.sigmoid
elif activation_function in ['tanh', tf.nn.tanh]:
self.activation_function = tf.nn.tanh
elif activation_function in ['elu', tf.nn.elu]:
self.activation_function = tf.nn.elu
elif activation_function in ['softplus', tf.nn.softplus]:
self.activation_function = tf.nn.softplus
elif activation_function in ['softsign', tf.nn.softsign]:
self.activation_function = tf.nn.softsign
elif activation_function in ['relu', tf.nn.relu]:
self.activation_function = tf.nn.relu
elif activation_function in ['relu6', tf.nn.relu6]:
self.activation_function = tf.nn.relu6
elif activation_function in ['crelu', tf.nn.crelu]:
self.activation_function = tf.nn.crelu
elif activation_function in ['relu_x', tf.nn.relu_x]:
self.activation_function = tf.nn.relu_x
else:
raise InputError("Unknown activation function. Got %s" % str(activation_function))
def _set_l1_reg(self, l1_reg):
"""
This function sets the value of the l1 regularisation that will be used on the weights in the model.
:param l1_reg: l1 regularisation on the weights
:type l1_reg: float
:return: None
"""
if not is_positive_or_zero(l1_reg):
raise InputError("Expected positive float value for variable 'l1_reg'. Got %s" % str(l1_reg))
self.l1_reg = l1_reg
def _set_l2_reg(self, l2_reg):
"""
This function sets the value of the l2 regularisation that will be used on the weights in the model.
:param l2_reg: l2 regularisation on the weights
:type l2_reg: float
:return: None
"""
if not is_positive_or_zero(l2_reg):
raise InputError("Expected positive float value for variable 'l2_reg'. Got %s" % str(l2_reg))
self.l2_reg = l2_reg
def _set_batch_size(self, batch_size):
"""
This function sets the value of the batch size. The value of the batch size will be checked again once the data
set is available, to make sure that it is sensible. This will be done by the function _get_batch_size.
:param batch_size: size of the batch size.
:type batch_size: float
:return: None
"""
if batch_size != "auto":
if not is_positive_integer(batch_size):
raise InputError("Expected 'batch_size' to be a positive integer. Got %s" % str(batch_size))
elif batch_size == 1:
raise InputError("batch_size must be larger than 1. Got %s" % str(batch_size))
self.batch_size = int(batch_size)
else:
self.batch_size = batch_size
def _set_learning_rate(self, learning_rate):
"""
This function sets the value of the learning that will be used by the optimiser.
:param learning_rate: step size in the optimisation algorithms
:type l1_reg: float
:return: None
"""
if not is_positive(learning_rate):
raise InputError("Expected positive float value for variable learning_rate. Got %s" % str(learning_rate))
self.learning_rate = float(learning_rate)
def _set_iterations(self, iterations):
"""
This function sets the number of iterations that will be carried out by the optimiser.
:param iterations: number of iterations
:type l1_reg: int
:return: None
"""
if not is_positive_integer(iterations):
raise InputError("Expected positive integer value for variable iterations. Got %s" % str(iterations))
self.iterations = int(iterations)
# TODO check that the estimators actually use this
def _set_tf_dtype(self, tf_dtype):
"""
This sets what data type will be used in the model.
:param tf_dtype: data type
:type tf_dtype: string or tensorflow class or int
:return: None
"""
# 2 == tf.float64 and 1 == tf.float32 for some reason
# np.float64 recognised as tf.float64 as well
if tf_dtype in ['64', 64, 'float64', tf.float64]:
self.tf_dtype = tf.float64
elif tf_dtype in ['32', 32, 'float32', tf.float32]:
self.tf_dtype = tf.float32
elif tf_dtype in ['16', 16, 'float16', tf.float16]:
self.tf_dtype = tf.float16
else:
raise InputError("Unknown tensorflow data type. Got %s" % str(tf_dtype))
def _set_optimiser_param(self, beta1, beta2, epsilon, rho, initial_accumulator_value, initial_gradient_squared_accumulator_value,
l1_regularization_strength, l2_regularization_strength):
"""
This function sets all the parameters that are required by all the optimiser functions. In the end, only the parameters
for the optimiser chosen will be used.
:param beta1: parameter for AdamOptimizer
:type beta1: float
:param beta2: parameter for AdamOptimizer
:type beta2: float
:param epsilon: parameter for AdadeltaOptimizer
:type epsilon: float
:param rho: parameter for AdadeltaOptimizer
:type rho: float
:param initial_accumulator_value: parameter for AdagradOptimizer
:type initial_accumulator_value: float
:param initial_gradient_squared_accumulator_value: parameter for AdagradDAOptimizer
:type initial_gradient_squared_accumulator_value: float
:param l1_regularization_strength: parameter for AdagradDAOptimizer
:type l1_regularization_strength: float
:param l2_regularization_strength: parameter for AdagradDAOptimizer
:type l2_regularization_strength: float
:return: None
"""
if not is_positive(beta1) and not is_positive(beta2):
raise InputError("Expected positive float values for variable beta1 and beta2. Got %s and %s." % (str(beta1),str(beta2)))
self.beta1 = float(beta1)
self.beta2 = float(beta2)
if not is_positive(epsilon):
raise InputError("Expected positive float value for variable epsilon. Got %s" % str(epsilon))
self.epsilon = float(epsilon)
if not is_positive(rho):
raise InputError("Expected positive float value for variable rho. Got %s" % str(rho))
self.rho = float(rho)
if not is_positive(initial_accumulator_value) and not is_positive(initial_gradient_squared_accumulator_value):
raise InputError("Expected positive float value for accumulator values. Got %s and %s" %
(str(initial_accumulator_value), str(initial_gradient_squared_accumulator_value)))
self.initial_accumulator_value = float(initial_accumulator_value)
self.initial_gradient_squared_accumulator_value = float(initial_gradient_squared_accumulator_value)
if not is_positive_or_zero(l1_regularization_strength) and not is_positive_or_zero(l2_regularization_strength):
raise InputError("Expected positive or zero float value for regularisation variables. Got %s and %s" %
(str(l1_regularization_strength), str(l2_regularization_strength)))
self.l1_regularization_strength = float(l1_regularization_strength)
self.l2_regularization_strength = float(l2_regularization_strength)
def _set_optimiser_type(self, optimiser):
"""
This function sets which numerical optimisation algorithm will be used for training.
:param optimiser: Optimiser
:type optimiser: string or tf class
:return: tf optimiser to use
:rtype: tf class
"""
self.AdagradDA = False
if optimiser in ['AdamOptimizer', tf.train.AdamOptimizer]:
optimiser_type = tf.train.AdamOptimizer
elif optimiser in ['AdadeltaOptimizer', tf.train.AdadeltaOptimizer]:
optimiser_type = tf.train.AdadeltaOptimizer
elif optimiser in ['AdagradOptimizer', tf.train.AdagradOptimizer]:
optimiser_type = tf.train.AdagradOptimizer
elif optimiser in ['AdagradDAOptimizer', tf.train.AdagradDAOptimizer]:
optimiser_type = tf.train.AdagradDAOptimizer
self.AdagradDA = True
elif optimiser in ['GradientDescentOptimizer', tf.train.GradientDescentOptimizer]:
optimiser_type = tf.train.GradientDescentOptimizer
else:
raise InputError("Unknown optimiser. Got %s" % str(optimiser))
return optimiser_type
def _set_optimiser(self):
"""
This function instantiates an object from the optimiser class that has been selected by the user. It also sets
the parameters for the optimiser.
:return: Optimiser with set parameters
:rtype: object of tf optimiser class
"""
self.AdagradDA = False
if self.optimiser in ['AdamOptimizer', tf.train.AdamOptimizer]:
optimiser_obj = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1, beta2=self.beta2,
epsilon=self.epsilon)
elif self.optimiser in ['AdadeltaOptimizer', tf.train.AdadeltaOptimizer]:
optimiser_obj = tf.train.AdadeltaOptimizer(learning_rate=self.learning_rate, rho=self.rho, epsilon=self.epsilon)
elif self.optimiser in ['AdagradOptimizer', tf.train.AdagradOptimizer]:
optimiser_obj = tf.train.AdagradOptimizer(learning_rate=self.learning_rate,
initial_accumulator_value=self.initial_accumulator_value)
elif self.optimiser in ['AdagradDAOptimizer', tf.train.AdagradDAOptimizer]:
self.global_step = tf.placeholder(dtype=tf.int64)
optimiser_obj = tf.train.AdagradDAOptimizer(learning_rate=self.learning_rate, global_step=self.global_step,
initial_gradient_squared_accumulator_value=self.initial_gradient_squared_accumulator_value,
l1_regularization_strength=self.l1_regularization_strength,
l2_regularization_strength=self.l2_regularization_strength)
self.AdagradDA = True
elif self.optimiser in ['GradientDescentOptimizer', tf.train.GradientDescentOptimizer]:
optimiser_obj = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)
else:
raise InputError("Unknown optimiser class. Got %s" % str(self.optimiser))
return optimiser_obj
def _set_scoring_function(self, scoring_function):
"""
This function sets which scoring metrics to use when scoring the results.
:param scoring_function: name of the scoring function to use
:type scoring_function: string
:return: None
"""
if not is_string(scoring_function):
raise InputError("Expected a string for variable 'scoring_function'. Got %s" % str(scoring_function))
if scoring_function.lower() not in ['mae', 'rmse', 'r2']:
raise InputError("Available scoring functions are 'mae', 'rmse', 'r2'. Got %s" % str(scoring_function))
self.scoring_function = scoring_function
def _set_hidden_layers_sizes(self, hidden_layer_sizes):
"""
This function sets the number of hidden layers and the number of neurons in each hidden layer. The length of the
tuple tells the number of hidden layers (n_hidden_layers) while each element of the tuple specifies the number
of hidden neurons in that layer.
:param hidden_layer_sizes: number of hidden layers and hidden neurons.
:type hidden_layer_sizes: tuple of length n_hidden_layer
:return: None
"""
try:
iterator = iter(hidden_layer_sizes)
except TypeError:
raise InputError("'hidden_layer_sizes' must be a tuple of positive integers. Got a non-iterable object.")
if None in hidden_layer_sizes:
raise InputError("'hidden_layer_sizes' must be a tuple of positive integers. Got None elements")
if not is_positive_integer_array(hidden_layer_sizes):
raise InputError("'hidden_layer_sizes' must be a tuple of positive integers")
self.hidden_layer_sizes = np.asarray(hidden_layer_sizes, dtype = int)
def _set_tensorboard(self, tensorboard, store_frequency, tensorboard_subdir):
"""
This function prepares all the things needed to use tensorboard when training the estimator.
:param tensorboard: whether to use tensorboard or not
:type tensorboard: boolean
:param store_frequency: Every how many steps to save data to tensorboard
:type store_frequency: int
:param tensorboard_subdir: directory where to save the tensorboard data
:type tensorboard_subdir: string
:return: None
"""
if not is_bool(tensorboard):
raise InputError("Expected boolean value for variable tensorboard. Got %s" % str(tensorboard))
self.tensorboard = bool(tensorboard)
if not self.tensorboard:
return
if not is_string(tensorboard_subdir):
raise InputError('Expected string value for variable tensorboard_subdir. Got %s' % str(tensorboard_subdir))
# TensorBoardLogger will handle all tensorboard related things
self.tensorboard_logger_training = TensorBoardLogger(tensorboard_subdir + '/training')
self.tensorboard_subdir_training = tensorboard_subdir + '/training'
self.tensorboard_logger_representation = TensorBoardLogger(tensorboard_subdir + '/representation')
self.tensorboard_subdir_representation = tensorboard_subdir + '/representation'
if not is_positive_integer(store_frequency):
raise InputError("Expected positive integer value for variable store_frequency. Got %s" % str(store_frequency))
if store_frequency > self.iterations:
print("Only storing final iteration for tensorboard")
self.tensorboard_logger_training.set_store_frequency(self.iterations)
else:
self.tensorboard_logger_training.set_store_frequency(store_frequency)
def _init_weight(self, n1, n2, name):
"""
This function generates a the matrix of weights to go from layer l to the next layer l+1. It initialises the
weights from a truncated normal distribution where the standard deviation is 1/sqrt(n2) and the mean is zero.
:param n1: size of the layer l+1
:type n1: int
:param n2: size of the layer l
:type n2: int
:param name: name to give to the tensor of weights to make tensorboard clear
:type name: string
:return: weights to go from layer l to layer l+1
:rtype: tf tensor of shape (n1, n2)
"""
w = tf.Variable(tf.truncated_normal([n1,n2], stddev = 1.0 / np.sqrt(n2), dtype = self.tf_dtype),
dtype = self.tf_dtype, name = name)
return w
def _init_bias(self, n, name):
"""
This function initialises the biases to go from layer l to layer l+1.
:param n: size of the layer l+1
:type n: int
:param name: name to give to the tensor of biases to make tensorboard clear
:type name: string
:return: biases
:rtype: tf tensor of shape (n, 1)
"""
b = tf.Variable(tf.zeros([n], dtype = self.tf_dtype), name=name, dtype = self.tf_dtype)
return b
def _generate_weights(self, n_out):
"""
Generates the weights and the biases, by looking at the size of the hidden layers,
the number of features in the representation and the number of outputs. The weights are initialised from
a zero centered normal distribution with precision :math:`\\tau = a_{m}`, where :math:`a_{m}` is the number
of incoming connections to a neuron. Weights larger than two standard deviations from the mean is
redrawn.
:param n_out: Number of outputs
:type n_out: integer
:return: tuple of weights and biases, each being of length (n_hidden_layers + 1)
:rtype: tuple
"""
weights = []
biases = []
# Weights from input layer to first hidden layer
weights.append(self._init_weight(self.hidden_layer_sizes[0], self.n_features, 'weight_in'))
biases.append(self._init_bias(self.hidden_layer_sizes[0], 'bias_in'))
# Weights from one hidden layer to the next
for i in range(1, self.hidden_layer_sizes.size):
weights.append(self._init_weight(self.hidden_layer_sizes[i], self.hidden_layer_sizes[i-1], 'weight_hidden_%d' %i))
biases.append(self._init_bias(self.hidden_layer_sizes[i], 'bias_hidden_%d' % i))
# Weights from last hidden layer to output layer
weights.append(self._init_weight(n_out, self.hidden_layer_sizes[-1], 'weight_out'))
biases.append(self._init_bias(n_out, 'bias_out'))
return weights, biases
def _l2_loss(self, weights):
"""
Creates the expression for L2-regularisation on the weights
:param weights: tensorflow tensors representing the weights
:type weights: list of tf tensors
:return: tensorflow scalar representing the regularisation contribution to the cost function
:rtype: tf.float32
"""
reg_term = tf.zeros([], name="l2_loss")
for i in range(self.hidden_layer_sizes.size):
reg_term += tf.reduce_sum(tf.square(weights[i]))
return self.l2_reg * reg_term
def _l1_loss(self, weights):
"""
Creates the expression for L1-regularisation on the weights
:param weights: tensorflow tensors representing the weights
:type weights: list of tf tensors
:return: tensorflow scalar representing the regularisation contribution to the cost function
:rtype: tf.float32
"""
reg_term = tf.zeros([], name="l1_loss")
for i in range(self.hidden_layer_sizes.size):
reg_term += tf.reduce_sum(tf.abs(weights[i]))
return self.l1_reg * reg_term
def _get_batch_size(self):
"""
Determines the actual batch size. If set to auto, the batch size will be set to 100.
If the batch size is larger than the number of samples, it is truncated and a warning
is printed.
Furthermore the returned batch size will be slightly modified from the user input if
the last batch would be tiny compared to the rest.
:return: Batch size
:rtype: int
"""
if self.batch_size == 'auto':
batch_size = min(100, self.n_samples)
else:
if self.batch_size > self.n_samples:
print("Warning: batch_size larger than sample size. It is going to be clipped")
return min(self.n_samples, self.batch_size)
else:
batch_size = self.batch_size
# see if the batch size can be modified slightly to make sure the last batch is similar in size
# to the rest of the batches
# This is always less that the requested batch size, so no memory issues should arise
better_batch_size = ceil(self.n_samples, ceil(self.n_samples, batch_size))
return better_batch_size
def _set_slatm_parameters(self, params):
"""
This function sets the parameters for the slatm representation.
:param params: dictionary
:return: None
"""
self.slatm_parameters = {'slatm_sigma1': 0.05, 'slatm_sigma2': 0.05, 'slatm_dgrid1': 0.03, 'slatm_dgrid2': 0.03,
'slatm_rcut': 4.8, 'slatm_rpower': 6, 'slatm_alchemy': False}
if params is not None:
for key, value in params.items():
if key in self.slatm_parameters:
self.slatm_parameters[key] = value
self._check_slatm_values()
def _set_acsf_parameters(self, params):
"""
This function sets the parameters for the acsf representation.
:param params: dictionary
:return: None
"""
self.acsf_parameters = {'rcut': 5.0, 'acut': 5.0, 'nRs2': 5, 'nRs3': 5, 'nTs': 5,
'zeta': 220.127, 'eta': 30.8065, 'bin_min': 0.8}
if params is not None:
for key, value in params.items():
if key in self.acsf_parameters:
self.acsf_parameters[key] = value
self._check_acsf_values()
def score(self, x, y=None, dy=None, classes=None):
"""
This function calls the appropriate function to score the model. One needs to pass a representation and some
properties to it or alternatively if the compounds/representations and the properties are stored in the class one
can pass indices.
:param x: either the representations or the indices to the representations
:type x: either a numpy array of shape (n_samples, n_features) or (n_samples, n_atoms, n_features) or a numpy array of ints
:param y: either the properties or None
:type y: either a numpy array of shape (n_samples,) or None
:param dy: either the gradients of the properties or none
:type dy: either a numpy array of shape (n_samples, n_atoms, 3) or None
:param classes: either the classes to do the NN decomposition or None
:type classes: either a numpy array of shape (n_samples, n_atoms) or None
:return: score
:rtype: float
"""
return self._score(x, y, dy, classes)
def _score(self, x, y=None, dy=None, classes=None):
"""
This function calls the appropriate function to score the model. One needs to pass a representation and some
properties to it or alternatively if the compounds/representations and the properties are stored in the class one
can pass indices.
:param x: either the representations or the indices to the representations
:type x: either a numpy array of shape (n_samples, n_features) or (n_samples, n_atoms, n_features) or a numpy array of ints
:param y: either the properties or None
:type y: either a numpy array of shape (n_samples,) or None
:param dy: either the gradients of the properties or none
:type dy: either a numpy array of shape (n_samples, n_atoms, 3) or None
:param classes: either the classes to do the NN decomposition or None
:type classes: either a numpy array of shape (n_samples, n_atoms) or None
:return: score
:rtype: float
"""
if self.scoring_function == 'mae':
return self._score_mae(x, y, dy, classes)
if self.scoring_function == 'rmse':
return self._score_rmse(x, y, dy, classes)
if self.scoring_function == 'r2':
return self._score_r2(x, y, dy, classes)
def generate_compounds(self, filenames):
"""
Creates QML compounds. Needs to be called before fitting.
:param filenames: path of xyz-files
:type filenames: list
"""
# Check that the number of properties match the number of compounds if the properties have already been set
if self.properties is None:
pass
else:
if self.properties.size == len(filenames):
pass
else:
raise InputError("Number of properties (%d) does not match number of compounds (%d)"
% (self.properties.size, len(filenames)))
self.compounds = np.empty(len(filenames), dtype=object)
for i, filename in enumerate(filenames):
self.compounds[i] = Compound(filename)
def generate_representation(self, xyz=None, classes=None, method='fortran'):
"""
This function can generate representations either from the data contained in the compounds or from xyz data passed
through the argument. If the Compounds have already being set and xyz data is given, it complains.
:param xyz: cartesian coordinates
:type xyz: numpy array of shape (n_samples, n_atoms, 3)
:param classes: The classes to do the atomic decomposition of the networks (most commonly nuclear charges)
:type classes: numpy array of shape (n_samples, n_atoms)
:return: None
"""
if self.compounds is None and xyz is None and classes is None:
raise InputError("QML compounds need to be created in advance or Cartesian coordinates need to be passed in "
"order to generate the representation.")
if self.representation is not None:
raise InputError("The representations have already been set!")
if self.compounds is None:
self.representation, self.classes = self._generate_representations_from_data(xyz, classes, method)
elif xyz is None:
# Make representations from compounds
self.representation, self.classes = self._generate_representations_from_compounds(method)
else:
raise InputError("Compounds have already been set but new xyz data is being passed.")
def set_properties(self, properties):
"""
Set properties. Needed to be called before fitting.
:param y: array of properties of size (nsamples,)
:type y: array
"""
if properties is None:
raise InputError("Properties cannot be set to none.")
else:
if is_numeric_array(properties) and np.asarray(properties).ndim == 1:
self.properties = np.asarray(properties)
else:
raise InputError(
'Variable "properties" expected to be array like of dimension 1. Got %s' % str(properties))
def set_representations(self, representations):
"""
This function takes representations as input and stores them inside the class.
:param representations: global or local representations
:type representations: numpy array of shape (n_samples, n_features) or (n_samples, n_atoms, n_features)
"""
if self.representation is not None:
raise InputError("The representations have already been set!")
if representations is None:
raise InputError("Descriptor cannot be set to none.")
else:
if is_numeric_array(representations):
self._set_representation(representations)
else:
raise InputError('Variable "representation" expected to be array like.')
def set_gradients(self, gradients):
"""
This function enables to set the gradient information.
:param gradients: The gradients of the properties with respect to the input. For example, forces.
:type gradients: numpy array (for example, numpy array of shape (n_samples, n_atoms, 3))
:return: None
"""
if gradients is None:
raise InputError("Gradients cannot be set to none.")
else:
if is_numeric_array(gradients):
self.gradients = np.asarray(gradients)
else:
raise InputError('Variable "gradients" expected to be array like.')
# TODO move to ARMP? MRMP does not neet this function
def set_classes(self, classes):
"""
This function stores the classes to be used during training for local networks.
:param classes: what class does each atom belong to.
:type classes: numpy array of shape (n_samples, n_atoms) of ints
:return: None
"""
if classes is None:
raise InputError("Classes cannot be set to none.")
else:
if is_positive_integer_or_zero_array(classes):
self.classes = np.asarray(classes)
else:
raise InputError('Variable "classes" expected to be array like of positive integers.')
def fit(self, x, y=None, dy=None, classes=None):
"""
This function calls the specific fit method of the child classes.
:param x: either the representations or the indices to the representations
:type x: either a numpy array of shape (n_samples, n_features) or (n_samples, n_atoms, n_features) or a numpy array of ints
:param y: either the properties or None
:type y: either a numpy array of shape (n_samples,) or None
:param dy: either the gradients of the properties or none
:type dy: either a numpy array of shape (n_samples, n_atoms, 3) or None
:param classes: either the classes to do the NN decomposition or None
:type classes: either a numpy array of shape (n_samples, n_atoms) or None
:return: None
"""
return self._fit(x, y, dy, classes)
def _check_slatm_values(self):
"""
This function checks that the parameters passed to slatm make sense.
:return: None
"""
if not is_positive(self.slatm_parameters['slatm_sigma1']):
raise InputError("Expected positive float for variable 'slatm_sigma1'. Got %s." % str(self.slatm_parameters['slatm_sigma1']))
if not is_positive(self.slatm_parameters['slatm_sigma2']):
raise InputError("Expected positive float for variable 'slatm_sigma2'. Got %s." % str(self.slatm_parameters['slatm_sigma2']))
if not is_positive(self.slatm_parameters['slatm_dgrid1']):
raise InputError("Expected positive float for variable 'slatm_dgrid1'. Got %s." % str(self.slatm_parameters['slatm_dgrid1']))
if not is_positive(self.slatm_parameters['slatm_dgrid2']):
raise InputError("Expected positive float for variable 'slatm_dgrid2'. Got %s." % str(self.slatm_parameters['slatm_dgrid2']))
if not is_positive(self.slatm_parameters['slatm_rcut']):
raise InputError("Expected positive float for variable 'slatm_rcut'. Got %s." % str(self.slatm_parameters['slatm_rcut']))
if not is_non_zero_integer(self.slatm_parameters['slatm_rpower']):
raise InputError("Expected non-zero integer for variable 'slatm_rpower'. Got %s." % str(self.slatm_parameters['slatm_rpower']))
if not is_bool(self.slatm_parameters['slatm_alchemy']):
raise InputError("Expected boolean value for variable 'slatm_alchemy'. Got %s." % str(self.slatm_parameters['slatm_alchemy']))
def _check_acsf_values(self):
"""
This function checks that the user input parameters to acsf make sense.
:return: None
"""
if not is_positive(self.acsf_parameters['rcut']):
raise InputError(
"Expected positive float for variable 'rcut'. Got %s." % str(self.acsf_parameters['rcut']))
if not is_positive(self.acsf_parameters['acut']):
raise InputError(
"Expected positive float for variable 'acut'. Got %s." % str(self.acsf_parameters['acut']))
if not is_positive_integer(self.acsf_parameters['nRs2']):
raise InputError("Expected positinve integer for 'nRs2. Got %s." % (self.acsf_parameters['nRs2']))
if not is_positive_integer(self.acsf_parameters['nRs3']):
raise InputError("Expected positinve integer for 'nRs3. Got %s." % (self.acsf_parameters['nRs3']))
if not is_positive_integer(self.acsf_parameters['nTs']):
raise InputError("Expected positinve integer for 'nTs. Got %s." % (self.acsf_parameters['nTs']))
if is_numeric_array(self.acsf_parameters['eta']) or is_numeric_array(self.acsf_parameters['eta']):
raise InputError("Expecting a scalar value for eta parameters.")
if is_numeric_array(self.acsf_parameters['zeta']):
raise InputError("Expecting a scalar value for zeta. Got %s." % (self.acsf_parameters['zeta']))
if not is_positive_or_zero(self.acsf_parameters['bin_min']):
raise InputError(
"Expected positive or zero float for variable 'bin_min'. Got %s." % str(self.acsf_parameters['bin_min']))
def _get_msize(self, pad = 0):
"""
Gets the maximum number of atoms in a single molecule. To support larger molecules
an optional padding can be added by the ``pad`` variable.
:param pad: Add an integer padding to the returned dictionary
:type pad: integer
:return: largest molecule with respect to number of atoms.
:rtype: integer
"""
if self.compounds.size == 0:
raise RuntimeError("QML compounds have not been generated")
if not is_positive_integer_or_zero(pad):
raise InputError("Expected variable 'pad' to be a positive integer or zero. Got %s" % str(pad))
nmax = max(mol.natoms for mol in self.compounds)
return nmax + pad
def _get_asize(self, pad = 0):
"""
Gets the maximum occurrences of each element in a single molecule. To support larger molecules
an optional padding can be added by the ``pad`` variable.
:param pad: Add an integer padding to the returned dictionary
:type pad: integer
:return: dictionary of the maximum number of occurences of each element in a single molecule.
:rtype: dictionary
"""
if self.compounds.size == 0:
raise RuntimeError("QML compounds have not been generated")
if not is_positive_integer_or_zero(pad):
raise InputError("Expected variable 'pad' to be a positive integer or zero. Got %s" % str(pad))
asize = {}
for mol in self.compounds:
for key, value in mol.natypes.items():
if key not in asize:
asize[key] = value + pad
continue
asize[key] = max(asize[key], value + pad)
return asize
def _get_slatm_mbtypes(self, arr):
"""
This function takes an array containing all the classes that are present in a data set and returns a list of all
the unique classes present, all the possible pairs and triplets of classes.
:param arr: classes for each atom in a data set
:type arr: numpy array of shape (n_samples, n_atoms)
:return: unique single, pair and triplets of classes
:rtype: list of lists
"""
return qml_rep.get_slatm_mbtypes(arr)
def _get_xyz_from_compounds(self, indices):
"""
This function takes some indices and returns the xyz of the compounds corresponding to those indices.
:param indices: indices of the compounds to use for training
:type indices: numpy array of ints of shape (n_samples, )
:return: the xyz of the specified compounds
:rtype: numpy array of shape (n_samples, n_atoms, 3)
"""
xyzs = []
zs = []
max_n_atoms = 0
for compound in self.compounds[indices]:
xyzs.append(compound.coordinates)
zs.append(compound.nuclear_charges)
if len(compound.nuclear_charges) > max_n_atoms:
max_n_atoms = len(compound.nuclear_charges)
# Padding so that all the samples have the same shape
n_samples = len(zs)
for i in range(n_samples):
current_n_atoms = len(zs[i])
missing_n_atoms = max_n_atoms - current_n_atoms
xyz_padding = np.zeros((missing_n_atoms, 3))
xyzs[i] = np.concatenate((xyzs[i], xyz_padding))
xyzs = np.asarray(xyzs, dtype=np.float32)
return xyzs
def _get_properties(self, indices):
"""
This returns the properties that have been set through QML.
:param indices: The indices of the properties to return
:type indices: numpy array of ints of shape (n_samples, )
:return: the properties of the compounds specified
:rtype: numpy array of shape (n_samples, 1)
"""
return np.atleast_2d(self.properties[indices]).T
def _get_classes(self, indices):
"""
This returns the classes that have been set through QML.
:param indices: The indices of the properties to return
:type indices: numpy array of ints of shape (n_samples, )
:return: classes of the compounds specified
:rtype: numpy array of shape (n_samples, n_atoms)
"""
zs = []
max_n_atoms = 0
for compound in self.compounds[indices]:
zs.append(compound.nuclear_charges)
if len(compound.nuclear_charges) > max_n_atoms:
max_n_atoms = len(compound.nuclear_charges)
# Padding so that all the samples have the same shape
n_samples = len(zs)
for i in range(n_samples):
current_n_atoms = len(zs[i])
missing_n_atoms = max_n_atoms - current_n_atoms
zs_padding = np.zeros(missing_n_atoms)
zs[i] = np.concatenate((zs[i], zs_padding))
return np.asarray(zs, dtype=np.float32)
def _generate_compounds_from_data(self, xyz, classes):
"""
This function generates the compounds from xyz data and nuclear charges.
:param xyz: cartesian coordinates
:type xyz: numpy array of shape (n_samples, n_atoms, 3)
:param classes: classes for atomic decomposition
:type classes: None
:return: array of compound objects
"""
compounds = np.empty(xyz.shape[0], dtype=object)
for i in range(xyz.shape[0]):
compounds[i] = Compound()
compounds[i].set_compounds(xyz=xyz[i], zs=classes[i])
return compounds