glm_param.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright 2019 The FATE Authors. All Rights Reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. import copy
  19. from pipeline.param.base_param import BaseParam
  20. from pipeline.param.callback_param import CallbackParam
  21. from pipeline.param.encrypt_param import EncryptParam
  22. from pipeline.param.cross_validation_param import CrossValidationParam
  23. from pipeline.param.init_model_param import InitParam
  24. from pipeline.param.stepwise_param import StepwiseParam
  25. from pipeline.param import consts
  26. class LinearModelParam(BaseParam):
  27. """
  28. Parameters used for GLM.
  29. Parameters
  30. ----------
  31. penalty : {'L2' or 'L1'}
  32. Penalty method used in LinR. Please note that, when using encrypted version in HeteroLinR,
  33. 'L1' is not supported.
  34. tol : float, default: 1e-4
  35. The tolerance of convergence
  36. alpha : float, default: 1.0
  37. Regularization strength coefficient.
  38. optimizer : {'sgd', 'rmsprop', 'adam', 'sqn', 'adagrad', 'nesterov_momentum_sgd'}
  39. Optimize method
  40. batch_size : int, default: -1
  41. Batch size when updating model. -1 means use all data in a batch. i.e. Not to use mini-batch strategy.
  42. learning_rate : float, default: 0.01
  43. Learning rate
  44. max_iter : int, default: 20
  45. The maximum iteration for training.
  46. init_param: InitParam object, default: default InitParam object
  47. Init param method object.
  48. early_stop : {'diff', 'abs', 'weight_dff'}
  49. Method used to judge convergence.
  50. a) diff: Use difference of loss between two iterations to judge whether converge.
  51. b) abs: Use the absolute value of loss to judge whether converge. i.e. if loss < tol, it is converged.
  52. c) weight_diff: Use difference between weights of two consecutive iterations
  53. encrypt_param: EncryptParam object, default: default EncryptParam object
  54. encrypt param
  55. cv_param: CrossValidationParam object, default: default CrossValidationParam object
  56. cv param
  57. decay: int or float, default: 1
  58. Decay rate for learning rate. learning rate will follow the following decay schedule.
  59. lr = lr0/(1+decay*t) if decay_sqrt is False. If decay_sqrt is True, lr = lr0 / sqrt(1+decay*t)
  60. where t is the iter number.
  61. decay_sqrt: Bool, default: True
  62. lr = lr0/(1+decay*t) if decay_sqrt is False, otherwise, lr = lr0 / sqrt(1+decay*t)
  63. validation_freqs: int, list, tuple, set, or None
  64. validation frequency during training, required when using early stopping.
  65. The default value is None, 1 is suggested. You can set it to a number larger than 1 in order to speed up training by skipping validation rounds.
  66. When it is larger than 1, a number which is divisible by "max_iter" is recommended, otherwise, you will miss the validation scores of the last training iteration.
  67. early_stopping_rounds: int, default: None
  68. If positive number specified, at every specified training rounds, program checks for early stopping criteria.
  69. Validation_freqs must also be set when using early stopping.
  70. metrics: list or None, default: None
  71. Specify which metrics to be used when performing evaluation during training process. If metrics have not improved at early_stopping rounds, trianing stops before convergence.
  72. If set as empty, default metrics will be used. For regression tasks, default metrics are ['root_mean_squared_error', 'mean_absolute_error']
  73. use_first_metric_only: bool, default: False
  74. Indicate whether to use the first metric in `metrics` as the only criterion for early stopping judgement.
  75. floating_point_precision: None or integer
  76. if not None, use floating_point_precision-bit to speed up calculation,
  77. e.g.: convert an x to round(x * 2**floating_point_precision) during Paillier operation, divide
  78. the result by 2**floating_point_precision in the end.
  79. callback_param: CallbackParam object
  80. callback param
  81. """
  82. def __init__(self, penalty='L2',
  83. tol=1e-4, alpha=1.0, optimizer='sgd',
  84. batch_size=-1, learning_rate=0.01, init_param=InitParam(),
  85. max_iter=100, early_stop='diff',
  86. encrypt_param=EncryptParam(),
  87. cv_param=CrossValidationParam(), decay=1, decay_sqrt=True, validation_freqs=None,
  88. early_stopping_rounds=None, stepwise_param=StepwiseParam(), metrics=None, use_first_metric_only=False,
  89. floating_point_precision=23, callback_param=CallbackParam()):
  90. super(LinearModelParam, self).__init__()
  91. self.penalty = penalty
  92. self.tol = tol
  93. self.alpha = alpha
  94. self.optimizer = optimizer
  95. self.batch_size = batch_size
  96. self.learning_rate = learning_rate
  97. self.init_param = copy.deepcopy(init_param)
  98. self.max_iter = max_iter
  99. self.early_stop = early_stop
  100. self.encrypt_param = encrypt_param
  101. self.cv_param = copy.deepcopy(cv_param)
  102. self.decay = decay
  103. self.decay_sqrt = decay_sqrt
  104. self.validation_freqs = validation_freqs
  105. self.early_stopping_rounds = early_stopping_rounds
  106. self.stepwise_param = copy.deepcopy(stepwise_param)
  107. self.metrics = metrics or []
  108. self.use_first_metric_only = use_first_metric_only
  109. self.floating_point_precision = floating_point_precision
  110. self.callback_param = copy.deepcopy(callback_param)
  111. def check(self):
  112. descr = "linear model param's "
  113. if self.penalty is None:
  114. self.penalty = 'NONE'
  115. elif type(self.penalty).__name__ != "str":
  116. raise ValueError(
  117. descr + "penalty {} not supported, should be str type".format(self.penalty))
  118. self.penalty = self.penalty.upper()
  119. if self.penalty not in ['L1', 'L2', 'NONE']:
  120. raise ValueError(
  121. "penalty {} not supported, penalty should be 'L1', 'L2' or 'none'".format(self.penalty))
  122. if type(self.tol).__name__ not in ["int", "float"]:
  123. raise ValueError(
  124. descr + "tol {} not supported, should be float type".format(self.tol))
  125. if type(self.alpha).__name__ not in ["int", "float"]:
  126. raise ValueError(
  127. descr + "alpha {} not supported, should be float type".format(self.alpha))
  128. if type(self.optimizer).__name__ != "str":
  129. raise ValueError(
  130. descr + "optimizer {} not supported, should be str type".format(self.optimizer))
  131. else:
  132. self.optimizer = self.optimizer.lower()
  133. if self.optimizer not in ['sgd', 'rmsprop', 'adam', 'adagrad', 'sqn', 'nesterov_momentum_sgd']:
  134. raise ValueError(
  135. descr + "optimizer not supported, optimizer should be"
  136. " 'sgd', 'rmsprop', 'adam', 'sqn', 'adagrad', or 'nesterov_momentum_sgd'")
  137. if type(self.batch_size).__name__ not in ["int", "long"]:
  138. raise ValueError(
  139. descr + "batch_size {} not supported, should be int type".format(self.batch_size))
  140. if self.batch_size != -1:
  141. if type(self.batch_size).__name__ not in ["int", "long"] \
  142. or self.batch_size < consts.MIN_BATCH_SIZE:
  143. raise ValueError(descr + " {} not supported, should be larger than {} or "
  144. "-1 represent for all data".format(self.batch_size, consts.MIN_BATCH_SIZE))
  145. if type(self.learning_rate).__name__ not in ["int", "float"]:
  146. raise ValueError(
  147. descr + "learning_rate {} not supported, should be float type".format(
  148. self.learning_rate))
  149. self.init_param.check()
  150. if type(self.max_iter).__name__ != "int":
  151. raise ValueError(
  152. descr + "max_iter {} not supported, should be int type".format(self.max_iter))
  153. elif self.max_iter <= 0:
  154. raise ValueError(
  155. descr + "max_iter must be greater or equal to 1")
  156. if type(self.early_stop).__name__ != "str":
  157. raise ValueError(
  158. descr + "early_stop {} not supported, should be str type".format(
  159. self.early_stop))
  160. else:
  161. self.early_stop = self.early_stop.lower()
  162. if self.early_stop not in ['diff', 'abs', 'weight_diff']:
  163. raise ValueError(
  164. descr + "early_stop not supported, early_stop should be 'weight_diff', 'diff' or 'abs'")
  165. self.encrypt_param.check()
  166. if type(self.decay).__name__ not in ["int", "float"]:
  167. raise ValueError(
  168. descr + "decay {} not supported, should be 'int' or 'float'".format(self.decay)
  169. )
  170. if type(self.decay_sqrt).__name__ not in ["bool"]:
  171. raise ValueError(
  172. descr + "decay_sqrt {} not supported, should be 'bool'".format(self.decay)
  173. )
  174. self.stepwise_param.check()
  175. self.callback_param.check()
  176. return True