简体   繁体   中英

Multiply a layer by a boolean mask in Keras, getting error 'NoneType' object has no attribute '_inbound_nodes'

Plenty of threads on this error, but I can't seem to apply them to my case. Here's a simplified version of what I'm trying to do:

import numpy as np
from keras.models import Model
from keras.layers import Input, multiply, Dense, Lambda, Multiply
import keras.backend as K

Some dummy data:

xx = np.array([1,2,3]).reshape(3,1)
maskvec = np.array([1,2,3]).reshape(3,1)

This is a function to compare a mask to a value in the mask:

def compfun(x):
    comp = K.equal(x[0], x[1])
    return K.cast(comp, dtype = "float32")


inp = Input(shape = (1,))
lay = Dense(1)(inp)
mask = Input(shape = (1,))
m2 = Lambda(compfun)([mask, K.variable(2)]) #2 is a magic number.  In my use-case it'll be in a for-loop
masked = multiply([lay, m2])
model = Model(inputs = [inp, mask], outputs = [masked])

And the dreaded

AttributeError: 'NoneType' object has no attribute '_inbound_nodes'

Would really appreciate some insight into what's going on here! Really banging my head against the wall.

I've tried making the second argument to compfun into an array rather than a constant, but I get the same error (I have no idea if K.equal can take scalars or not when another argument is a vector)

You can change it like this:

def compfun(x):
    comp = K.equal(x, K.variable(2))
    return K.cast(comp, dtype = "float32")


m2 = Lambda(compfun)(mask)

It turns out that the problem was that `Lambdas choke when you give them an argument that is a list, because they don't know what to do with the non-layer part of the function. I handled the problem like this:

for i in np.unique(loc_idx): 
    mask = Lambda(lambda x: K.cast(K.equal(x, i), dtype = "float32"))(loc_inp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM