2017-02-13 2 views
1

나는 Convolution2D 층의 가중치를 설정하고 싶습니다 :Convolution2D에 대한 가중치를 설정하는 방법은 무엇입니까?

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

하지만 난 여기에 예상 있는지 모르겠습니다. 몇 가지 시도했지만 대부분의 시간 내가

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

정확히 무슨 뜻인지 잘 모르겠습니다.

답변

7

set_weights 메소드를 통해 컨볼 루션 레이어에 numpy 배열을 전달해야합니다.

길쌈 레이어의 가중치는 각각의 개별 필터의 가중치 일뿐만 아니라 바이어스입니다. 따라서 가중치를 설정하려면 추가 측정 기준을 추가해야합니다.

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

을 그리고 그것을 설정 : 모든 무게 중심 요소를 제외하고 제로와 1x3x3 필터를 설정하려면

예를 들어, 당신은 그것을해야한다.

코드를 들어 당신은 실행할 수 있습니다 :

#!/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) 길쌈 fillter에서 중앙 요소를 변경해보십시오.

코드 수행 내용 :

먼저 모델을 작성하십시오.

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) 

인쇄 원래 무게는

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.] 
    ]] 
    ]) 

당신의 가중치를 설정 input_mat

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

원하는 체중 w 텐서 및 일부 입력을 만들고 있습니다 (init = '보통', 정규 분포로 초기화) 인쇄하십시오.

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

마지막으로, (자동 모델 컴파일 예측) 예측과 출력을 생성하는 데 사용할

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.]]]] 
+0

아, 감사합니다! 그건 나에게 분명하지 않았다. 문서에서는 가중치의 모양에 대한 정확한 요구 사항을 지정하지 않았습니다. 당신의 예제를 가져 주셔서 감사합니다! – displayname

+0

참조 : https://github.com/fchollet/keras/issues/1671 – maz

관련 문제