Open KevinYijunQian opened 6 years ago
Were you able to solve this? If yes are you willing to help me because more or less I have the same problem as well.
IMAGE_MIN_DIM and IMAGE_MIN_DIM should be multiple of 64. Ref: https://github.com/matterport/Mask_RCNN/blob/master/mrcnn/config.py#L106.
You are using Python2, so this line: https://github.com/matterport/Mask_RCNN/blob/master/mrcnn/model.py#L1850 fails to throw an exception.
I am facing the same issue ? and my image min dim and image max dim is also in multiples of 64 .. in my case Incompatible shapes: [1,38,26,256] vs. [1,38,25,256] [[{{node training_4/SGD/gradients/fpn_p4add_4/add_grad/BroadcastGradientArgs}}]]
please inform me of any solutions
I am facing the same issue during training. The error can occur at any time during the training process.
The error does not come from parameter settings or image shape. It looks like at some point a rounding of shape is done incorrectly.
Does anyone has a solution ? Basically this error makes impossible the training
Same here. Anyone has a solution?
I encountered the error when change train_shapes for my personal dataset and i only have one object to detect Epoch 1/2 Traceback (most recent call last): File "train_shapes.py", line 273, in
layers="all")
File "/home/zhiqi.cheng/Mask_RCNN-master/mrcnn/model.py", line 2328, in train
use_multiprocessing=False,
File "/home/zhiqi.cheng/anaconda2/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, kwargs)
File "/home/zhiqi.cheng/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 2230, in fit_generator
class_weight=class_weight)
File "/home/zhiqi.cheng/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 1883, in train_on_batch
outputs = self.train_function(ins)
File "/home/zhiqi.cheng/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 2482, in call
self.session_kwargs)
File "/home/zhiqi.cheng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 905, in run
run_metadata_ptr)
File "/home/zhiqi.cheng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1140, in _run
feed_dict_tensor, options, run_metadata)
File "/home/zhiqi.cheng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1321, in _do_run
run_metadata)
File "/home/zhiqi.cheng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1340, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [2,76,76,256] vs. [2,75,75,256]
[[Node: training/SGD/gradients/fpn_p3add/add_grad/BroadcastGradientArgs = BroadcastGradientArgs[T=DT_INT32, _class=["loc:@fpn_p3add/add"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](training/SGD/gradients/fpn_p3add/add_grad/Shape, training/SGD/gradients/fpn_p3add/add_grad/Shape_1-0-1-VecPermuteNCHWToNHWC-LayoutOptimizer/_6005)]]
[[Node: roi_align_mask/Cast_3/_6481 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_11117_roi_align_mask/Cast_3", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
And my changed train_shapes file are as followed:
coding: utf-8
Mask R-CNN - Train on Shapes Dataset
This notebook shows how to train Mask R-CNN on your own dataset. To keep things simple we use a synthetic dataset of shapes (squares, triangles, and circles) which enables fast training. You'd still need a GPU, though, because the network backbone is a Resnet101, which would be too slow to train on a CPU. On a GPU, you can start to get okay-ish results in a few minutes, and good results in less than an hour.
The code of the Shapes dataset is included below. It generates images on the fly, so it doesn't require downloading any data. And it can generate images of any size, so we pick a small image size to train faster.
In[1]:
import os import sys import random import math import re import time import numpy as np import cv2 import matplotlib import matplotlib.pyplot as plt from PIL import Image import yaml
Root directory of the project
ROOT_DIR = os.path.abspath("../../")
Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn.config import Config from mrcnn import utils import mrcnn.model as modellib from mrcnn import visualize from mrcnn.model import log
get_ipython().magic(u'matplotlib inline')
Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH): utils.download_trained_weights(COCO_MODEL_PATH)
Configurations
In[2]:
class ShapesConfig(Config): """Configuration for training on the toy shapes dataset. Derives from the base Config class and overrides values specific to the toy shapes dataset. """
Give the configuration a recognizable name
config = ShapesConfig() config.display()
Notebook Preferences
In[3]:
def get_ax(rows=1, cols=1, size=8): """Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes.
Dataset
Create a synthetic dataset
Extend the Dataset class and add a method to load the shapes dataset,
load_shapes()
, and override the following methods:* load_image()
* load_mask()
* image_reference()
In[4]:
class BallDataset(utils.Dataset): def get_obj_index(self, image): n = np.max(image) return n def from_yaml_get_class(self,image_id): info=self.image_info[image_id] with open(info['yaml_path']) as f: temp=yaml.load(f.read()) labels=temp['label_names'] del labels[0] return labels def draw_mask(self, num_obj, mask, image): info = self.image_info[image_id] for index in range(num_obj): for i in range(info['width']): for j in range(info['height']): at_pixel = image.getpixel((i, j)) if at_pixel == index + 1: mask[j, i, index] =1 return mask def load_shapes(self, count, height, width, img_floder, mask_floder, imglist,dataset_root_path,yaml_floder): """Generate the requested number of synthetic images. count: number of images to generate. height, width: the size of the generated images. """
Add classes
In[5]:
dataset_root_path="/home/zhiqi.cheng/Mask_RCNN-master/maskdataset/" img_floder = dataset_root_path+"pic" mask_floder = dataset_root_path+"mask" yaml_floder = dataset_root_path+"info.yaml" imglist = os.listdir(img_floder) count = len(imglist) width = 600 height = 600
Training dataset
dataset_train = BallDataset() dataset_train.load_shapes(count, 600, 600, img_floder, mask_floder, imglist,dataset_root_path,yaml_floder) dataset_train.prepare()
Validation dataset
dataset_val = BallDataset() dataset_val.load_shapes(count, 600, 600, img_floder, mask_floder, imglist,dataset_root_path,yaml_floder) dataset_val.prepare()
In[6]:
Load and display random samples
image_ids = np.random.choice(dataset_train.image_ids, 4) for image_id in image_ids: image = dataset_train.load_image(image_id) mask, class_ids = dataset_train.load_mask(image_id) visualize.display_top_masks(image, mask, class_ids, dataset_train.class_names)
Ceate Model
In[ ]:
Create model in training mode
model = modellib.MaskRCNN(mode="training", config=config, model_dir=MODEL_DIR)
In[7]:
Which weights to start with?
init_with = "coco" # imagenet, coco, or last
if init_with == "imagenet": model.load_weights(model.get_imagenet_weights(), by_name=True) elif init_with == "coco":
Load weights trained on MS COCO, but skip layers that
elif init_with == "last":
Load the last model you trained and continue training
Training
Train in two stages:
1. Only the heads. Here we're freezing all the backbone layers and training only the randomly initialized layers (i.e. the ones that we didn't use pre-trained weights from MS COCO). To train only the head layers, pass
layers='heads'
to thetrain()
function.2. Fine-tune all layers. For this simple example it's not necessary, but we're including it to show the process. Simply pass
layers="all
to train all layers.In[8]:
Train the head branches
Passing layers="heads" freezes all layers except the head
layers. You can also pass a regular expression to select
which layers to train by name pattern.
model.train(dataset_train, dataset_val,
In[9]:
Fine tune all layers
Passing layers="all" trains all layers. You can also
pass a regular expression to select which layers to
train by name pattern.
model.train(dataset_train, dataset_val, learning_rate=config.LEARNING_RATE / 10, epochs=2, layers="all")
In[10]:
Save weights
Typically not needed because callbacks save after every epoch
Uncomment to save manually
model_path = os.path.join(MODEL_DIR, "mask_rcnn_shapes.h5")
model.keras_model.save_weights(model_path)
Detection
In[11]: