欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

tf.cond报错Initializer for variable is from inside control-flow construct such as a loop or condition

程序员文章站 2022-04-01 16:11:17
...

完整报错信息:ValueError: Initializer for variable lambda_5/cond/mrcnn_mask_conv1/kernel/ is from inside a control-flow construct, such as a loop or conditional. When creating a variable inside a loop or conditional, use a lambda as the initializer.

解决思路:这个报错的原因是在tf.cond中有变量的初始化,所以只要把初始化的部分单独提出来先用变量来接收,然后把变量放入tf.cond的选择部分即可。

参考网站:

https://*.com/questions/48515034/keras-tensorflow-initializer-for-variable-is-from-inside-a-control-flow-con

举例子:

def ff_true():
    mrcnn_mask = build_fpn_mask_graph(rois, mrcnn_feature_maps,
       config.IMAGE_SHAPE,
       config.MASK_POOL_SIZE,
       config.NUM_CLASSES)

def ff_false():
    return tf.zeros_like(target_mask)

mrcnn_mask = KL.Lambda(lambda x: tf.cond(tf.equal(tf.reduce_mean(x), 0), 
    ff_true, ff_true)) (rois)

上面会有报错,修改成如下形式无报错:

a = build_fpn_mask_graph(rois, mrcnn_feature_maps,
    config.IMAGE_SHAPE,
    config.MASK_POOL_SIZE,
    config.NUM_CLASSES)   
def ff_true():
    return a
def ff_false():
    return tf.zeros_like(target_mask)

mrcnn_mask = KL.Lambda(lambda x: tf.cond(tf.equal(tf.reduce_mean(x), 0), 
    ff_true, ff_true)) (rois)

可以看到先用a来赋值,完成计算后,再将其放入tf.cond中作为选择项。