如何制作自定义内核(或偏差)权重初始值设定项,为 Keras Dense 随机生成 -1 或 1 值?

问题描述 投票:0回答:1

在纯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)

正如您所看到的,结果张量由生成的随机值填充一次,这不是我想要的。

keras random initializer
1个回答
0
投票

我想我使用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)
© www.soinside.com 2019 - 2024. All rights reserved.