如何为 Convolution2D 设置权重? [英] How to set weights for Convolution2D?

查看:21
本文介绍了如何为 Convolution2D 设置权重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置 Convolution2D 层的权重:

I would like to set the weights of a Convolution2D layer:

conv = Convolution2D(conv_out_size, window_size, embedding_size,
                     border_mode='same',
                     activation='relu',
                     weights=weights,
                     name='conv_{:d}'.format(i))(in_x)

但我不确定这里会发生什么.我尝试了几件事,但大部分时间我都得到

but I am not sure what's expected here. I've tried several thing but most of the time I get

ValueError: You called `set_weights(weights)` on layer "conv_0" with a  weight list of length 1, but the layer was expecting 2 weights. 

不确定这到底是什么意思.

Not sure what this exactly means.

推荐答案

你应该通过 set_weights 方法将一个 numpy 数组传递给你的卷积层.

You should pass a numpy array to your convolutional layer through the set_weights method.

请记住,卷积层的权重不仅是每个单独过滤器的权重,还包括偏差.所以如果你想设置你的权重,你需要添加一个额外的维度.

Remember that the weights of a convolutional layer are not only the weights of each individual filter, but also the bias. So if you want to set your weights you need to add an extra dimension.

例如,如果你想设置一个 1x3x3 的过滤器,除了中心元素之外,所有的权重都为零,你应该这样做:

For example, if you want to set a 1x3x3 filter with all weights zero except for the central element, you should make it:

w = np.asarray([ 
    [[[
    [0,0,0],
    [0,2,0],
    [0,0,0]
    ]]]
    ])

然后设置它.

对于您可以运行的代码:

For a code you could run:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
np.random.seed(1234)
from keras.layers import Input
from keras.layers.convolutional import Convolution2D
from keras.models import Model
print("Building Model...")
inp = Input(shape=(1,None,None))
output   = Convolution2D(1, 3, 3, border_mode='same', init='normal',bias=False)(inp)
model_network = Model(input=inp, output=output)
print("Weights before change:")
print (model_network.layers[1].get_weights())
w = np.asarray([ 
    [[[
    [0,0,0],
    [0,2,0],
    [0,0,0]
    ]]]
    ])
input_mat = np.asarray([ 
    [[
    [1.,2.,3.],
    [4.,5.,6.],
    [7.,8.,9.]
    ]]
    ])
model_network.layers[1].set_weights(w)
print("Weights after change:")
print(model_network.layers[1].get_weights())
print("Input:")
print(input_mat)
print("Output:")
print(model_network.predict(input_mat))

尝试更改卷积填充器中的中心元素(示例中为 2).

Try changing the central element in the convolutional fillter (2 in the example).

代码的作用:

首先建立一个模型.

inp = Input(shape=(1,None,None))
output   = Convolution2D(1, 3, 3, border_mode='same', init='normal',bias=False)(inp)
model_network = Model(input=inp, output=output)

打印你的原始权重(用正态分布初始化,init='normal')

Print your original weights (initialized with normal distribution, init='normal' )

print (model_network.layers[1].get_weights())

创建你想要的权重张量 w 和一些输入 input_mat

Create your desired weight tensor w and some input input_mat

w = np.asarray([ 
    [[[
    [0,0,0],
    [0,2,0],
    [0,0,0]
    ]]]
    ])
input_mat = np.asarray([ 
    [[
    [1.,2.,3.],
    [4.,5.,6.],
    [7.,8.,9.]
    ]]
    ])

设置权重并打印

model_network.layers[1].set_weights(w)
print("Weights after change:")
print(model_network.layers[1].get_weights())

最后,使用它生成带有预测的输出(预测会自动编译您的模型)

Finally, use it to generate output with predict (predict automatically compiles your model)

print(model_network.predict(input_mat))

示例输出:

Using Theano backend.
Building Model...
Weights before change:
[array([[[[ 0.02357176, -0.05954878,  0.07163535],
         [-0.01563259, -0.03602944,  0.04435815],
         [ 0.04297942, -0.03182618,  0.00078482]]]], dtype=float32)]
Weights after change:
[array([[[[ 0.,  0.,  0.],
         [ 0.,  2.,  0.],
         [ 0.,  0.,  0.]]]], dtype=float32)]
Input:
[[[[ 1.  2.  3.]
   [ 4.  5.  6.]
   [ 7.  8.  9.]]]]
Output:
[[[[  2.   4.   6.]
   [  8.  10.  12.]
   [ 14.  16.  18.]]]]

这篇关于如何为 Convolution2D 设置权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆