是否可以设置keras层输出?

时间:2017-10-27 13:11:29

标签: python deep-learning keras keras-layer

我需要修改第二个卷积层的最后一个特征映射的输出 或者如果可能的话,将数组添加到我的转换层输出中 下面是我创建的python脚本和输出中所需更改的示例 谢谢您的帮助!

import numpy as np
from keras import backend as K

num=18  
m=11  
n=50  
k=3  
np.random.seed(100)  
features = np.random.rand(num,m,n,k)

模型

input_shape=features.shape[1:]  
model = Sequential()  
model.add(Conv2D(2, kernel_size=(1, 3), strides=(1,1),activation='relu',input_shape=input_shape))  
model.add(Conv2D(21, kernel_size=(1, 48), strides=(1,1),padding="valid",activation='relu'))  
model.add(Conv2D(1, kernel_size=(1, 1), strides=(1, 1),activation='relu',padding="valid"))  
model.add(Dense(1, activation='softmax'))  
Adam = optimizers.Adam(lr=0.00003, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)  
model.compile(loss='mse',optimizer=Adam)  

get_1st_layer_output = K.function([model.layers[0].input],
[model.layers[1].output])  
layer_output = get_1st_layer_output([features])

设置所需的layer_output值
我需要在每个传播步骤中都这样做。

for i in range(0,11):
    layer_output[0][0][i][0][20]=0.1
    print(layer_output[0][0][i][0][20])  

1 个答案:

答案 0 :(得分:0)

我认为在这种情况下我会使用具有常数张量的连接。不幸的是,我无法让它工作,但无论如何我都会分享我的工作,希望能帮助你。

import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Conv2D, Dense, Concatenate
from keras import optimizers

num=18
m=11
n=50
k=3
np.random.seed(100)
features = np.random.rand(num, m, n, k)

custom_tensor = K.constant(0.1, shape=(11, 48, 1))

input_shape = features.shape[1:]
input = keras.Input(shape=input_shape)
print(K.ndim(input))
layer0 = Conv2D(2, kernel_size=(1, 3), strides=(1,1),activation='relu')(input)
layer0_added = Concatenate(axis=-1)([layer0, custom_tensor])
layer1 = Conv2D(20, kernel_size=(1, 48), strides=(1,1),padding="valid",activation='relu')(layer0_added)
layer2 = Conv2D(1, kernel_size=(1, 1), strides=(1, 1),activation='relu',padding="valid")(layer1)
layer3 = Dense(1, activation='softmax')(layer2)

model = keras.models.model(layer0)
Adam = optimizers.Adam(lr=0.00003, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
model.compile(loss='mse', optimizer=Adam)

它产生了错误

ValueError: `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 11, 48, 2), (11, 48, 1)]

但希望无论如何这对你有帮助。