改变卷积层上的滤波器CNN Python/TensorF

2024-09-28 19:08:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码块:

^{1}$

以及:

^{pr2}$

所以我们可以观察到滤波器的尺寸是3x3,滤波器的数目是8。滤波器用随机值定义。在

我需要做的是用固定值定义我所有的8个过滤器,即预定值,例如:

weigths = [
    [[0,  1, 0,],[0, -1, 0,],[0,  0, 0,],],
    [[0,  0, 1,],[0, -1, 0,],[0,  0, 0,],],
    [[0,  0, 0,],[0, -1, 1,],[0,  0, 0,],],
    [[0,  0, 0,],[0, -1, 0,],[0,  0, 1,],],
    [[0,  0, 0,],[0, -1, 0,],[0,  1, 0,],],
    [[0,  0, 0,],[0, -1, 0,],[1,  0, 0,],], 
    [[0,  0, 0,],[1, -1, 0,],[0,  0, 0,],],
    [[1,  0, 0,],[0, -1, 0,],[0,  0, 0,],]
]

我无法想象,我怎么能在我的代码里做这个修改,有人知道我怎么做吗?在

提前非常感谢!在


Tags: 代码过滤器定义尺寸想象数目pr2weigths
2条回答

您只需将权重定义为不可训练,并将新权重定义为:

new_weights = tf.Variable( tf.reshape(weights, (3,3,1,8)),trainable=False)
# then apply on the inputs 
layer = tf.nn.conv2d(inputs, filter=new_weights, strides=[1, 1, 1, 1], padding='SAME')

如果您想通过某个预定义的值初始化权重,可以使用tf.constant_initializer。如果您不想训练这个权重,可以将它们定义为tf.constant而不是tf.Variable

def new_weights(init_vaue, is_const):
    if (is_const) :
        return tf.constant(init_vaue, name='weights')
    else:
        initializer = tf.constant_initializer(init_vaue)
        return tf.get_variable('weights', shape = init_vaue.shape, initializer=initializer)

weights = np.ones([3,3,1,8], dtype=np.float)
print(weights.shape)

value = new_weights(weights, True)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    value_ = sess.run(value) 
    print(value_)

相关问题 更多 >