在纯Python中我可以轻松做到:
from random import choice
def init_by_plus_or_menus() -> int:
return choice([-1, 1])
Keras 文档在示例 Keras.backend (tf) 函数中使用:
def my_init(shape, dtype=None):
return tf.random.normal(shape, dtype=dtype)
layer = Dense(64, kernel_initializer=my_init)
,但没有类似于标准 Python random.choice 或其逐元素类似物的函数。
我试过这个:
def init_plus_or_minus(shape, dtype=None):
return backend.constant(value=choice([-1, 1]), shape=shape, dtype=dtype)
# Testing
if __name__ == '__main__':
print(init_plus_or_minus(shape=(10,), dtype='int8'))
终端把我变成了这样:
tf.Tensor([1 1 1 1 1 1 1 1 1 1], shape=(10,), dtype=int8)
正如您所看到的,结果张量由生成的随机值填充一次,这不是我想要的。
我想我使用tensorflow.constant的“value”参数中的numpy.choice生成的数组解决了问题:
from keras.backend import constant
from numpy.random import choice
def init_plus_or_minus(shape, dtype=None, name=None):
return constant(value=choice([-1, 1], size=shape), dtype=dtype, name=name)
# Testing
if __name__ == '__main__':
print(init_plus_or_minus(shape=(10, 5,), dtype='int8'))
终端将其返回:
tf.Tensor(
[[ 1 -1 1 -1 1]
[ 1 1 -1 -1 1]
[ 1 1 -1 1 1]
[ 1 -1 1 1 1]
[-1 1 -1 -1 1]
[ 1 -1 -1 1 -1]
[ 1 -1 -1 1 -1]
[-1 -1 -1 -1 -1]
[-1 1 1 -1 1]
[-1 1 1 -1 1]], shape=(10, 5), dtype=int8)