tf_watermark_regularizers.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from tensorflow.python.keras.losses import binary_crossentropy
  2. from tensorflow.python.keras.regularizers import Regularizer
  3. import numpy as np
  4. import tensorflow as tf
  5. class WatermarkRegularizer(Regularizer):
  6. def __init__(self, scale, b, randseed='none'):
  7. self.scale = tf.constant(scale, dtype=tf.float32)
  8. self.b = b # 密钥
  9. self.x = None # 投影矩阵
  10. self.v_x = None # 投影矩阵设为可训练参数
  11. self.randseed = randseed
  12. def __call__(self, weight):
  13. if self.x is None:
  14. x_rows = np.prod(weight.shape[0:3])
  15. x_cols = self.b.shape[1]
  16. if self.randseed != 'none':
  17. np.random.seed(int(self.randseed))
  18. self.x = np.random.randn(x_rows, x_cols)
  19. self.v_x = tf.Variable(self.x, trainable=False, dtype=tf.float32)
  20. weight_mean = tf.reduce_mean(weight, axis=3)
  21. w = tf.reshape(weight_mean, (1, tf.reduce_prod(weight_mean.shape)))
  22. regularized_loss = self.scale * tf.reduce_sum(
  23. binary_crossentropy(tf.sigmoid(tf.matmul(w, self.v_x)), tf.cast(self.b, tf.float32)))
  24. return regularized_loss
  25. # 获取投影矩阵
  26. def get_matrix(self):
  27. return self.x
  28. # 获取签名值
  29. def get_signature(self):
  30. return self.b