tauhid ullah
tauhid ullah

Reputation: 41

How to change the value of a keras tensor based on a specific condition

I'm trying to change the value of a Keras tensor using the lambda layer. However, it is giving me this error msg.

"AttributeError: 'int' object has no attribute 'get_shape."

Here is the code.

user_matrix = K.constant(getTrainMatrix(train))
item_matrix = K.constant(getTrainMatrix(train).T)

# Input variables
user_input = Input(shape=(1,), dtype='int32', name='user_input')
item_input = Input(shape=(1,), dtype='int32', name='item_input')

user_rating = Lambda(lambda x: tf.gather(user_matrix, tf.to_int32(x)))(user_input)
item_rating = Lambda(lambda x: tf.gather(item_matrix, tf.to_int32(x)))(item_input)
user_rating = Reshape((num_items, ))(user_rating)
item_rating = Reshape((num_users, ))(item_rating)

MLP_Embedding_User = Dense(layers[0]//2, activation="linear" , name='user_embedding')
MLP_Embedding_Item  = Dense(layers[0]//2, activation="linear" , name='item_embedding')
user_latent = MLP_Embedding_User(user_rating)
item_latent = MLP_Embedding_Item(item_rating)

before the MLP_Embedding_User, I just put this line of code,

user_rating=Lambda(lambda x:2 if x==0 else 0)(user_rating ) 

Now my question is how to perform this operation correctly.

Upvotes: 0

Views: 291

Answers (1)

zihaozhihao
zihaozhihao

Reputation: 4475

Try to use tf.where and tf.equal instead of use if else statement.

user_rating = K.constant(np.random.randint(0,2,size=10))
K.eval(user_rating)
# array([1., 1., 0., 0., 0., 0., 0., 1., 1., 0.], dtype=float32)

user_rating=Lambda(lambda x: tf.where(tf.equal(x, 0.), 2.*tf.ones_like(x), tf.zeros_like(x)))(user_rating)

K.eval(user_rating)
# array([0., 0., 2., 2., 2., 2., 2., 0., 0., 2.], dtype=float32)

Upvotes: 2

Related Questions