我想在学习过程中向cnn中间层的输出层添加一个常数矩阵,然后将其发送到下一层。我将代码放在这里并使用添加功能,但会产生错误。我该怎么办?使用添加是否是真正的解决方案?
from keras.layers import Input, Concatenate, GaussianNoise
from keras.layers import Conv2D
from keras.models import Model
from keras.datasets import mnist
from keras.callbacks import TensorBoard
from keras import backend as K
from keras import layers
import matplotlib.pyplot as plt
import tensorflow as tf
import keras as Kr
import numpy as np
w_main = np.random.randint(2,size=(1,4,4,1))
w_main=w_main.astype(np.float32)
w_expand=np.zeros((1,28,28,1),dtype='float32')
w_expand[:,0:4,0:4]=w_main
w_expand.reshape(1,28,28,1)
#-----------------------encoder------------------------------------------------
#------------------------------------------------------------------------------
image = Input((28, 28, 1))
conv1 = Conv2D(8, (5, 5), activation='relu', padding='same')(image)
conv2 = Conv2D(4, (3, 3), activation='relu', padding='same')(conv1)
conv3 = Conv2D(2, (3, 3), activation='relu', padding='same')(conv2)
encoded = Conv2D(1, (3, 3), activation='relu', padding='same')(conv3)
encoder=Model(inputs=image, outputs=encoded)
encoder.summary()
#-----------------------adding w---------------------------------------
encoded_merged=Kr.layers.Add(encoded,w_expand)
#-----------------------decoder------------------------------------------------
#------------------------------------------------------------------------------
#encoded_merged = Input((28, 28, 2))
x = Conv2D(2, (5, 5), activation='relu', padding='same')(encoded_merged)
x = Conv2D(4, (3, 3), activation='relu', padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu',padding='same')(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same', name='decoder_output')(x)
decoder=Model(inputs=encoded_merged, outputs=decoded)
decoder.summary()
产生的错误是:
TypeError: init ()接受1个位置参数,但给出了3个 我很急。请帮助我。
答案 0 :(得分:1)
您使用错误的图层方式,这是正确的方法:
encoded_merged=Kr.layers.Add()([encoded,w_expand])
答案 1 :(得分:0)
您需要将常量包装到将返回张量的Layer中,当前您有numpy
数组,无法将其添加到张量:
add_const = Kr.layers.Lambda(lambda x: x + Kr.backend.constant(w_expand))
并与要添加到的图层一起使用:
encoded_merged = add_const(encoded)