Keras自定义函数“ AttributeError:“函数”对象没有属性“形状””

时间:2019-08-19 20:47:56

标签: python-3.x tf.keras

编译模型时出现“ AttributeError:'函数'对象没有属性'shape'”错误。尝试造成自定义损失

def pair_loss(lamb=0.01, gamma=1):
   #Custom loss
    def loss(y_true,y_pred):
        y1_pred, y2_pred = y_pred
        y1_true, y2_true = y_true
        result =  (tf.keras.backend.K.square(y1_pred - y1_true) + tf.keras.backend.K.square(y2_pred - y2_true))\
                + lamb(tf.keras.backend.max((0,(gamma - ( (y1_pred - y1_true)*(y2_pred - y2_true) ))),))
        return result
    return loss 
left_input = tf.keras.Input(shape=(1,), dtype=tf.string) 
right_input = tf.keras.Input(shape=(1,), dtype=tf.string) 


convnet = tf.keras.Sequential([
    tf.keras.layers.Lambda(embedding, output_shape=(512, )),
    tf.keras.layers.Dense(64, activation='relu',input_shape=(512,)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(1, activation='linear'),
                   ])

encoded_left = convnet(left_input)
encoded_right = convnet(right_input)

pair_net = tf.keras.Model(inputs=[left_input,right_input], outputs=[encoded_left,encoded_right])


optimizer = tf.keras.optimizers.Adam(0.001, decay=2.5e-4)
pair_net.compile(loss=pair_loss, optimizer=optimizer, metrics=['accuracy'])

0 个答案:

没有答案