如何在自定义层中编写initializer(random.uniform)?

时间:2019-04-03 12:21:45

标签: python tensorflow keras initialization

我想用随机制服初始化我的自定义图层。在TensorFlow中,我可以找到以下使用initializer='uniform'的代码。但是我想在(-1.0,1.0)之间设置随机的统一输出范围。怎么做:

class MyDenseLayer(tf.keras.layers.Layer):
  def __init__(self, num_outputs):
    super(MyDenseLayer, self).__init__()
    self.num_outputs = num_outputs

  def build(self, input_shape):
    self.kernel = self.add_variable(initializer='uniform',shape=[int(input_shape[-1]),self.num_outputs])

  def call(self, input):
    return tf.matmul(input, self.kernel)

1 个答案:

答案 0 :(得分:1)

一种方法是在numpy中生成随机制服,然后像这样使用tf.constant_initializer()

import tensorflow as tf
import numpy as np

class MyDenseLayer(tf.keras.layers.Layer):
    def __init__(self, num_outputs):
        super(MyDenseLayer, self).__init__()
        self.num_outputs = num_outputs

    def build(self, input_shape):
        shape = [int(input_shape[-1]),self.num_outputs]
        init_val = np.random.uniform(low=-1.0, high=1.0, size=shape)
        initializer = tf.constant_initializer(init_val,
                                              dtype=tf.float32)
        self.kernel = self.add_weight(initializer=initializer,
                                      shape=shape,
                                      name='kernel')
        super(MyDenseLayer, self).build(input_shape)

    def call(self, input):
        return tf.matmul(input, self.kernel)

改为使用tf.initializers.random_uniform()

init = tf.initializers.random_uniform(minval=-1.0, maxval=1.0)
self.kernel = self.add_weight(initializer=init,
                              shape=shape,
                              name='kernel')