Один из способов - создать случайную форму в 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')