Reputation: 105
I want to add a constant matrix to output layer of intermediate layer in cnn during learning and then send it to next layer. I put my code here and use Add functions but it produce error. what should I do? using Add is a true solution or not?
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()
the produced error is:
TypeError: init() takes 1 positional argument but 3 were given I am in a hurry. please help me with this.
Upvotes: 0
Views: 845
Reputation: 11225
You would need to wrap your constant into a Layer that will return a tensor, currently you have numpy
array which cannot be added to a tensor:
add_const = Kr.layers.Lambda(lambda x: x + Kr.backend.constant(w_expand))
And use it with the layer you want to add it to:
encoded_merged = add_const(encoded)
Upvotes: 0
Reputation: 56377
You are using the layer in the wrong way, this is the correct way:
encoded_merged=Kr.layers.Add()([encoded,w_expand])
Upvotes: 1