Mask_rcnn: Tensorflow 2.0 support

Created on 2 Oct 2019  ·  32Comments  ·  Source: matterport/Mask_RCNN

Tensorflow 2.0 has released yesterday . I try to change some API in Tensorflow 2.0 , but not well . When Mask_RCNN support Tensorflow 2.0 ?

The problem is

Screen Shot 2019-10-02 at 9 48 51 PM

Most helpful comment

For #1775,
I think the "layer.output" is not really under the tf2.0, so it can't be used as bool.
I use the code as below,

def compile(self, learning_rate, momentum):
    """Gets the model ready for training. Adds losses, regularization, and
    metrics. Then calls the Keras compile() function.
    """
    # Optimizer object
    optimizer = keras.optimizers.SGD(
        lr=learning_rate, momentum=momentum,
        clipnorm=self.config.GRADIENT_CLIP_NORM)
    # Add Losses
    # First, clear previously set losses to avoid duplication
    # self.keras_model._losses = []
    # self.keras_model._per_input_losses = {}
    loss_names = [
        "rpn_class_loss", "rpn_bbox_loss",
        "mrcnn_class_loss", "mrcnn_bbox_loss", "mrcnn_mask_loss"]
    added_loss_name = []
    for name in loss_names:
        layer = self.keras_model.get_layer(name)

        if layer.output.name in added_loss_name:
            # if layer.output in self.keras_model.losses:
            continue
        loss = (
                tf.math.reduce_mean(layer.output, keepdims=True)
                * self.config.LOSS_WEIGHTS.get(name, 1.))
        self.keras_model.add_loss(loss)

        added_loss_name.append(layer.output.name)

It is not really solve the problem. My code is here

All 32 comments

I've met the same problems too, And I'm trying to use the lower version of keras and tensorflow. Hope it will work.

@lokinfey did you resolve this?

Hi,
I am going to work on a university project about semantic segmentation and on of the requirements is that we use the new Tensorflow 2.0. Is there currently a way to use Mask RCNN with Tensorflow 2.0 or will it be possible in the near future?

@lokinfey did you resolve this?

hi i finished tf 2.0 without gpu ,but i need to more test gpu version

@lokinfey I noticed that Custom Layers output shapes are different in tf.keras and keras.
Mask RCNN use Custom Layers like: PyramidROIAlign, DetectionTargetLayer, etc.

More info: https://github.com/tensorflow/tensorflow/issues/33785

Any update on that?

Another issue is:

AttributeError                            Traceback (most recent call last)
<ipython-input-55-0da0f5bdf6f6> in <module>
----> 1 model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)
      2 
      3 model.load_weights(COCO_WEIGHTS_PATH, by_name=True, exclude=[
      4     'mrcnn_class_logits', 'mrcnn_bbox_fc', 'mrcnn_bbox', 'mrcnn_mask'])

~/VC/backend/Mask_RCNN/mrcnn/model.py in __init__(self, mode, config, model_dir)
   1835         self.model_dir = model_dir
   1836         self.set_log_dir()
-> 1837         self.keras_model = self.build(mode=mode, config=config)
   1838 
   1839     def build(self, mode, config):

~/VC/backend/Mask_RCNN/mrcnn/model.py in build(self, mode, config)
   1988             rois, target_class_ids, target_bbox, target_mask =\
   1989                 DetectionTargetLayer(config, name="proposal_targets")([
-> 1990                     target_rois, input_gt_class_ids, gt_boxes, input_gt_masks])
   1991 
   1992             # Network Heads

~/VC/backend/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in symbolic_fn_wrapper(*args, **kwargs)
     73         if _SYMBOLIC_SCOPE.value:
     74             with get_graph().as_default():
---> 75                 return func(*args, **kwargs)
     76         else:
     77             return func(*args, **kwargs)

~/VC/backend/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    487             # Actually call the layer,
    488             # collecting output(s), mask(s), and shape(s).
--> 489             output = self.call(inputs, **kwargs)
    490             output_mask = self.compute_mask(inputs, previous_mask)
    491 

~/VC/backend/Mask_RCNN/mrcnn/model.py in call(self, inputs)
    662             lambda w, x, y, z: detection_targets_graph(
    663                 w, x, y, z, self.config),
--> 664             self.config.IMAGES_PER_GPU, names=names)
    665         return outputs
    666 

~/VC/backend/Mask_RCNN/mrcnn/utils.py in batch_slice(inputs, graph_fn, batch_size, names)
    818     for i in range(batch_size):
    819         inputs_slice = [x[i] for x in inputs]
--> 820         output_slice = graph_fn(*inputs_slice)
    821         if not isinstance(output_slice, (tuple, list)):
    822             output_slice = [output_slice]

~/VC/backend/Mask_RCNN/mrcnn/model.py in <lambda>(w, x, y, z)
    661             [proposals, gt_class_ids, gt_boxes, gt_masks],
    662             lambda w, x, y, z: detection_targets_graph(
--> 663                 w, x, y, z, self.config),
    664             self.config.IMAGES_PER_GPU, names=names)
    665         return outputs

~/VC/backend/Mask_RCNN/mrcnn/model.py in detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config)
    551     positive_count = int(config.TRAIN_ROIS_PER_IMAGE *
    552                          config.ROI_POSITIVE_RATIO)
--> 553     positive_indices = tf.random_shuffle(positive_indices)[:positive_count]
    554     positive_count = tf.shape(positive_indices)[0]
    555     # Negative ROIs. Add enough to maintain positive:negative ratio.

AttributeError: module 'tensorflow' has no attribute 'random_shuffle'

@tomgross I had the same issue. Did you find the solution?

@neoyang0620 For this issue yes. See PR #1896

I am also facing the same problem as #1775 ! Do anyone solved it?

I am also facing the same problem as #1775 ! Do anyone solved it?

Tensorflow 2.0 has released yesterday . I try to change some API in Tensorflow 2.0 , but not well . When Mask_RCNN support Tensorflow 2.0 ?

The problem is

Screen Shot 2019-10-02 at 9 48 51 PM

Hi, lokinfey
how u solve this issue?

Another issue is:

AttributeError                            Traceback (most recent call last)
<ipython-input-55-0da0f5bdf6f6> in <module>
----> 1 model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)
      2 
      3 model.load_weights(COCO_WEIGHTS_PATH, by_name=True, exclude=[
      4     'mrcnn_class_logits', 'mrcnn_bbox_fc', 'mrcnn_bbox', 'mrcnn_mask'])

~/VC/backend/Mask_RCNN/mrcnn/model.py in __init__(self, mode, config, model_dir)
   1835         self.model_dir = model_dir
   1836         self.set_log_dir()
-> 1837         self.keras_model = self.build(mode=mode, config=config)
   1838 
   1839     def build(self, mode, config):

~/VC/backend/Mask_RCNN/mrcnn/model.py in build(self, mode, config)
   1988             rois, target_class_ids, target_bbox, target_mask =\
   1989                 DetectionTargetLayer(config, name="proposal_targets")([
-> 1990                     target_rois, input_gt_class_ids, gt_boxes, input_gt_masks])
   1991 
   1992             # Network Heads

~/VC/backend/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in symbolic_fn_wrapper(*args, **kwargs)
     73         if _SYMBOLIC_SCOPE.value:
     74             with get_graph().as_default():
---> 75                 return func(*args, **kwargs)
     76         else:
     77             return func(*args, **kwargs)

~/VC/backend/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    487             # Actually call the layer,
    488             # collecting output(s), mask(s), and shape(s).
--> 489             output = self.call(inputs, **kwargs)
    490             output_mask = self.compute_mask(inputs, previous_mask)
    491 

~/VC/backend/Mask_RCNN/mrcnn/model.py in call(self, inputs)
    662             lambda w, x, y, z: detection_targets_graph(
    663                 w, x, y, z, self.config),
--> 664             self.config.IMAGES_PER_GPU, names=names)
    665         return outputs
    666 

~/VC/backend/Mask_RCNN/mrcnn/utils.py in batch_slice(inputs, graph_fn, batch_size, names)
    818     for i in range(batch_size):
    819         inputs_slice = [x[i] for x in inputs]
--> 820         output_slice = graph_fn(*inputs_slice)
    821         if not isinstance(output_slice, (tuple, list)):
    822             output_slice = [output_slice]

~/VC/backend/Mask_RCNN/mrcnn/model.py in <lambda>(w, x, y, z)
    661             [proposals, gt_class_ids, gt_boxes, gt_masks],
    662             lambda w, x, y, z: detection_targets_graph(
--> 663                 w, x, y, z, self.config),
    664             self.config.IMAGES_PER_GPU, names=names)
    665         return outputs

~/VC/backend/Mask_RCNN/mrcnn/model.py in detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config)
    551     positive_count = int(config.TRAIN_ROIS_PER_IMAGE *
    552                          config.ROI_POSITIVE_RATIO)
--> 553     positive_indices = tf.random_shuffle(positive_indices)[:positive_count]
    554     positive_count = tf.shape(positive_indices)[0]
    555     # Negative ROIs. Add enough to maintain positive:negative ratio.

AttributeError: module 'tensorflow' has no attribute 'random_shuffle'

try random.shuffle instead of random_shuffle. Fixed my issue

Hi :

I tried to downgrade the tensorflow2.0  to 1.4 and keras to 2.2.4 , And it worked. You can have a try. Good Luck.

在 2019-12-14 09:17:08,"vincent0924" notifications@github.com 写道:

I am also facing the same problem as #1775 ! Do anyone solved it?

Tensorflow 2.0 has released yesterday . I try to change some API in Tensorflow 2.0 , but not well . When Mask_RCNN support Tensorflow 2.0 ?

The problem is

Hi, lokinfey
how u solve this issue?


You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or unsubscribe.

For #1775,
I think the "layer.output" is not really under the tf2.0, so it can't be used as bool.
I use the code as below,

def compile(self, learning_rate, momentum):
    """Gets the model ready for training. Adds losses, regularization, and
    metrics. Then calls the Keras compile() function.
    """
    # Optimizer object
    optimizer = keras.optimizers.SGD(
        lr=learning_rate, momentum=momentum,
        clipnorm=self.config.GRADIENT_CLIP_NORM)
    # Add Losses
    # First, clear previously set losses to avoid duplication
    # self.keras_model._losses = []
    # self.keras_model._per_input_losses = {}
    loss_names = [
        "rpn_class_loss", "rpn_bbox_loss",
        "mrcnn_class_loss", "mrcnn_bbox_loss", "mrcnn_mask_loss"]
    added_loss_name = []
    for name in loss_names:
        layer = self.keras_model.get_layer(name)

        if layer.output.name in added_loss_name:
            # if layer.output in self.keras_model.losses:
            continue
        loss = (
                tf.math.reduce_mean(layer.output, keepdims=True)
                * self.config.LOSS_WEIGHTS.get(name, 1.))
        self.keras_model.add_loss(loss)

        added_loss_name.append(layer.output.name)

It is not really solve the problem. My code is here

@Rorywh You meant Tensorflow 1.14.0

Yes, Tensorflow 1.14,

在 2019-12-19 00:43:49,"matthewmav" notifications@github.com 写道:

@Rorywh You meant Tensorflow 1.14


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or unsubscribe.

Does anyone know how to fix this issue without changing the tensorflow and/or keras version?? Only through code??

Hi all

I publish mask-rcnn for tensorflow 2.0 https://github.com/lokinfey/MaskRCNNTF2.0 , you can download it to use in your tensorflow 2.0

Hi @lokinfey Thanks for joining the attempt to bring tf 2.0 compatiblity to Mask_RCNN.

  • What's the reason behind starting a new repository? This way we loose all the history and tracking changes is harder. If this repository is unmaintained a fork would be the way to go IMO.
  • I don't think your version will work OOTB right now. Several issues I adressed in #1896 are still present 🤔 and keras is still standalone and not the included one in tensorflow. Did you run all included examples successfully?

I suggesst you help fixing #1896 and bring it to merge or put it at a new maintained location. What do you think?

Hi @lokinfey Thanks for joining the attempt to bring tf 2.0 compatiblity to Mask_RCNN.

  • What's the reason behind starting a new repository? This way we loose all the history and tracking changes is harder. If this repository is unmaintained a fork would be the way to go IMO.
  • I don't think your version will work OOTB right now. Several issues I adressed in #1896 are still present 🤔 and keras is still standalone and not the included one in tensorflow. Did you run all included examples successfully?

I suggesst you help fixing #1896 and bring it to merge or put it at a new maintained location. What do you think?

Okay , i will hide this repository and help fixing #1896

This is great news @tomgross @lokinfey . @Rorywh @advaitkumar3107 for now, I changed the TensorFlow and Keras lines in my Mask R-CNN requirements.txt file so I wouldn't use TF 2.0 by accident in new projects:
tensorflow>=1.3.0,<2.0
keras>=2.0.8,<2.3

Another issue is:

AttributeError                            Traceback (most recent call last)
<ipython-input-55-0da0f5bdf6f6> in <module>
----> 1 model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)
      2 
      3 model.load_weights(COCO_WEIGHTS_PATH, by_name=True, exclude=[
      4     'mrcnn_class_logits', 'mrcnn_bbox_fc', 'mrcnn_bbox', 'mrcnn_mask'])

~/VC/backend/Mask_RCNN/mrcnn/model.py in __init__(self, mode, config, model_dir)
   1835         self.model_dir = model_dir
   1836         self.set_log_dir()
-> 1837         self.keras_model = self.build(mode=mode, config=config)
   1838 
   1839     def build(self, mode, config):

~/VC/backend/Mask_RCNN/mrcnn/model.py in build(self, mode, config)
   1988             rois, target_class_ids, target_bbox, target_mask =\
   1989                 DetectionTargetLayer(config, name="proposal_targets")([
-> 1990                     target_rois, input_gt_class_ids, gt_boxes, input_gt_masks])
   1991 
   1992             # Network Heads

~/VC/backend/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in symbolic_fn_wrapper(*args, **kwargs)
     73         if _SYMBOLIC_SCOPE.value:
     74             with get_graph().as_default():
---> 75                 return func(*args, **kwargs)
     76         else:
     77             return func(*args, **kwargs)

~/VC/backend/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    487             # Actually call the layer,
    488             # collecting output(s), mask(s), and shape(s).
--> 489             output = self.call(inputs, **kwargs)
    490             output_mask = self.compute_mask(inputs, previous_mask)
    491 

~/VC/backend/Mask_RCNN/mrcnn/model.py in call(self, inputs)
    662             lambda w, x, y, z: detection_targets_graph(
    663                 w, x, y, z, self.config),
--> 664             self.config.IMAGES_PER_GPU, names=names)
    665         return outputs
    666 

~/VC/backend/Mask_RCNN/mrcnn/utils.py in batch_slice(inputs, graph_fn, batch_size, names)
    818     for i in range(batch_size):
    819         inputs_slice = [x[i] for x in inputs]
--> 820         output_slice = graph_fn(*inputs_slice)
    821         if not isinstance(output_slice, (tuple, list)):
    822             output_slice = [output_slice]

~/VC/backend/Mask_RCNN/mrcnn/model.py in <lambda>(w, x, y, z)
    661             [proposals, gt_class_ids, gt_boxes, gt_masks],
    662             lambda w, x, y, z: detection_targets_graph(
--> 663                 w, x, y, z, self.config),
    664             self.config.IMAGES_PER_GPU, names=names)
    665         return outputs

~/VC/backend/Mask_RCNN/mrcnn/model.py in detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config)
    551     positive_count = int(config.TRAIN_ROIS_PER_IMAGE *
    552                          config.ROI_POSITIVE_RATIO)
--> 553     positive_indices = tf.random_shuffle(positive_indices)[:positive_count]
    554     positive_count = tf.shape(positive_indices)[0]
    555     # Negative ROIs. Add enough to maintain positive:negative ratio.

AttributeError: module 'tensorflow' has no attribute 'random_shuffle'

try to use random.shuffle

I'm running in to the same issue described in the first comment in this issue:

`OperatorNotAllowedInGraphError            Traceback (most recent call last)
<ipython-input-18-16fc152be760> in <module>()
      3             learning_rate=config.LEARNING_RATE,
      4             epochs=3,
----> 5             layers='all')
      6 history = model.keras_model.history.history

4 frames
/content/drive/My Drive/Colab Notebooks/Mask_RCNN_2.0/mrcnn/model.py in train(self, train_dataset, val_dataset, learning_rate, epochs, layers, augmentation, custom_callbacks, no_augmentation_sources)
   2342         log("Checkpoint Path: {}".format(self.checkpoint_path))
   2343         self.set_trainable(layers)
-> 2344         self.compile(learning_rate, self.config.LEARNING_MOMENTUM)
   2345 
   2346         # Work-around for Windows: Keras fails on Windows when using

/content/drive/My Drive/Colab Notebooks/Mask_RCNN_2.0/mrcnn/model.py in compile(self, learning_rate, momentum)
   2160         for name in loss_names:
   2161             layer = self.keras_model.get_layer(name)
-> 2162             if layer.output in self.keras_model.losses:
   2163                 continue
   2164             loss = (

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py in __bool__(self)
    763       `TypeError`.
    764     """
--> 765     self._disallow_bool_casting()
    766 
    767   def __nonzero__(self):

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py in _disallow_bool_casting(self)
    532     else:
    533       # Default: V1-style Graph execution.
--> 534       self._disallow_in_graph_mode("using a `tf.Tensor` as a Python `bool`")
    535 
    536   def _disallow_iteration(self):

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py in _disallow_in_graph_mode(self, task)
    521     raise errors.OperatorNotAllowedInGraphError(
    522         "{} is not allowed in Graph execution. Use Eager execution or decorate"
--> 523         " this function with @tf.function.".format(task))
    524 
    525   def _disallow_bool_casting(self):

OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.`

I've been working with tf 2.1 and tf.keras 2.2.4. However, after downgrading to tf2.0 the issue persisted. I've looked around the Mask_RCNN issues section and I've seen this issue pop up, but haven't seen a clear solution. Has anybody figured out what needs to be changed in model.py to resolve this issue?
Thanks

Hi all

I publish mask-rcnn for tensorflow 2.0 https://github.com/lokinfey/MaskRCNNTF2.0 , you can download it to use in your tensorflow 2.0

Page not found

Any news guys ?

@lokinfey did you resolve this?

hi i finished tf 2.0 without gpu ,but i need to more test gpu version

Hi
I have convert to tf.2.2 ,can you help me with few queries>
Thanks

random_sh

Hi all
I publish mask-rcnn for tensorflow 2.0 https://github.com/lokinfey/MaskRCNNTF2.0 , you can download it to use in your tensorflow 2.0

Page not found

Another issue is:

AttributeError                            Traceback (most recent call last)
<ipython-input-55-0da0f5bdf6f6> in <module>
----> 1 model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)
      2 
      3 model.load_weights(COCO_WEIGHTS_PATH, by_name=True, exclude=[
      4     'mrcnn_class_logits', 'mrcnn_bbox_fc', 'mrcnn_bbox', 'mrcnn_mask'])

~/VC/backend/Mask_RCNN/mrcnn/model.py in __init__(self, mode, config, model_dir)
   1835         self.model_dir = model_dir
   1836         self.set_log_dir()
-> 1837         self.keras_model = self.build(mode=mode, config=config)
   1838 
   1839     def build(self, mode, config):

~/VC/backend/Mask_RCNN/mrcnn/model.py in build(self, mode, config)
   1988             rois, target_class_ids, target_bbox, target_mask =\
   1989                 DetectionTargetLayer(config, name="proposal_targets")([
-> 1990                     target_rois, input_gt_class_ids, gt_boxes, input_gt_masks])
   1991 
   1992             # Network Heads

~/VC/backend/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in symbolic_fn_wrapper(*args, **kwargs)
     73         if _SYMBOLIC_SCOPE.value:
     74             with get_graph().as_default():
---> 75                 return func(*args, **kwargs)
     76         else:
     77             return func(*args, **kwargs)

~/VC/backend/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    487             # Actually call the layer,
    488             # collecting output(s), mask(s), and shape(s).
--> 489             output = self.call(inputs, **kwargs)
    490             output_mask = self.compute_mask(inputs, previous_mask)
    491 

~/VC/backend/Mask_RCNN/mrcnn/model.py in call(self, inputs)
    662             lambda w, x, y, z: detection_targets_graph(
    663                 w, x, y, z, self.config),
--> 664             self.config.IMAGES_PER_GPU, names=names)
    665         return outputs
    666 

~/VC/backend/Mask_RCNN/mrcnn/utils.py in batch_slice(inputs, graph_fn, batch_size, names)
    818     for i in range(batch_size):
    819         inputs_slice = [x[i] for x in inputs]
--> 820         output_slice = graph_fn(*inputs_slice)
    821         if not isinstance(output_slice, (tuple, list)):
    822             output_slice = [output_slice]

~/VC/backend/Mask_RCNN/mrcnn/model.py in <lambda>(w, x, y, z)
    661             [proposals, gt_class_ids, gt_boxes, gt_masks],
    662             lambda w, x, y, z: detection_targets_graph(
--> 663                 w, x, y, z, self.config),
    664             self.config.IMAGES_PER_GPU, names=names)
    665         return outputs

~/VC/backend/Mask_RCNN/mrcnn/model.py in detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config)
    551     positive_count = int(config.TRAIN_ROIS_PER_IMAGE *
    552                          config.ROI_POSITIVE_RATIO)
--> 553     positive_indices = tf.random_shuffle(positive_indices)[:positive_count]
    554     positive_count = tf.shape(positive_indices)[0]
    555     # Negative ROIs. Add enough to maintain positive:negative ratio.

AttributeError: module 'tensorflow' has no attribute 'random_shuffle'

This is still an issue with mask-rcnn 2.1 and tensorflow 2.0.

Hi all,

I have been facing the same issue #1775 for a while and I just found a workaround that works for me. I am working with Tensorflow 2.2.0 and Keras 2.3.1 with GPU. This solution was proposed by @tmedeirosClostra on the issue #1896 which consists in modifying the following piece of code:

for name in loss_names:
            layer = self.keras_model.get_layer(name)
            if layer.output in self.keras_model.losses:
                continue
            loss = (
                tf.reduce_mean(layer.output, keepdims=True)
                * self.config.LOSS_WEIGHTS.get(name, 1.))
            self.keras_model.add_loss(loss)

to

output_names = []
for name in loss_names:
    layer = self.keras_model.get_layer(name)
    if layer.output.name in output_names:
        continue
    loss = (
                tf.reduce_mean(input_tensor=layer.output, keepdims=True)
                * self.config.LOSS_WEIGHTS.get(name, 1.))
    self.keras_model.add_loss(loss)
    output_names.append(layer.output.name)

Then you will be likely to face another problem like AttributeError: 'Model' object has no attribute 'metrics_tensors', which is referenced in the issue #1754 and the solution proposed by @mffigueroa. It consists in changing the line
self.keras_model.metrics_tensors.append(loss)
to
self.keras_model.add_metric(loss, name)

Hope this can solve your problem

Hi all,

I have been facing the same issue #1775 for a while and I just found a workaround that works for me. I am working with Tensorflow 2.2.0 and Keras 2.3.1 with GPU. This solution was proposed by @tmedeirosClostra on the issue #1896 which consists in modifying the following piece of code:

for name in loss_names:
            layer = self.keras_model.get_layer(name)
            if layer.output in self.keras_model.losses:
                continue
            loss = (
                tf.reduce_mean(layer.output, keepdims=True)
                * self.config.LOSS_WEIGHTS.get(name, 1.))
            self.keras_model.add_loss(loss)

to

output_names = []
for name in loss_names:
    layer = self.keras_model.get_layer(name)
    if layer.output.name in output_names:
        continue
    loss = (
                tf.reduce_mean(input_tensor=layer.output, keepdims=True)
                * self.config.LOSS_WEIGHTS.get(name, 1.))
    self.keras_model.add_loss(loss)
    output_names.append(layer.output.name)

Then you will be likely to face another problem like AttributeError: 'Model' object has no attribute 'metrics_tensors', which is referenced in the issue #1754 and the solution proposed by @mffigueroa. It consists in changing the line
self.keras_model.metrics_tensors.append(loss)
to
self.keras_model.add_metric(loss, name)

Hope this can solve your problem

problem have solve!!!!

Hi all,
I have been facing the same issue #1775 for a while and I just found a workaround that works for me. I am working with Tensorflow 2.2.0 and Keras 2.3.1 with GPU. This solution was proposed by @tmedeirosClostra on the issue #1896 which consists in modifying the following piece of code:

for name in loss_names:
            layer = self.keras_model.get_layer(name)
            if layer.output in self.keras_model.losses:
                continue
            loss = (
                tf.reduce_mean(layer.output, keepdims=True)
                * self.config.LOSS_WEIGHTS.get(name, 1.))
            self.keras_model.add_loss(loss)

to

output_names = []
for name in loss_names:
    layer = self.keras_model.get_layer(name)
    if layer.output.name in output_names:
        continue
    loss = (
                tf.reduce_mean(input_tensor=layer.output, keepdims=True)
                * self.config.LOSS_WEIGHTS.get(name, 1.))
    self.keras_model.add_loss(loss)
    output_names.append(layer.output.name)

Then you will be likely to face another problem like AttributeError: 'Model' object has no attribute 'metrics_tensors', which is referenced in the issue #1754 and the solution proposed by @mffigueroa. It consists in changing the line
self.keras_model.metrics_tensors.append(loss)
to
self.keras_model.add_metric(loss, name)
Hope this can solve your problem

problem have solve!!!!

Can you push your code ? Thanks

@ily666666 The changes I made in the model.py file are referenced in #2278 , hope this helps you solve your problem !

Hi! kindly see this issue https://github.com/matterport/Mask_RCNN/issues/2312 there is a pointer to the same implementation that supports TensorFlow 2=> (with GPU). If this solves your problem kindly close the issue so as others can navigate to other issues easier

Was this page helpful?
0 / 5 - 0 ratings