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.

--------------------------------------------------------------------

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

# 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

%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

----------------------------------------------------------------------------------

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
NAME = "shapes"

# Train on 1 GPU and 8 images per GPU. We can put multiple images on each
# GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
GPU_COUNT = 1
IMAGES_PER_GPU = 8

# Number of classes (including background)
NUM_CLASSES = 1 + 3 # background + 3 shapes

# Use small images for faster training. Set the limits of the small side
# the large side, and that determines the image shape.
IMAGE_MIN_DIM = 128
IMAGE_MAX_DIM = 128

# Use smaller anchors because our image and objects are small
RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) # anchor side in pixels

# Reduce training ROIs per image because the images are small and have
# few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
TRAIN_ROIS_PER_IMAGE = 32

# Use a small epoch since the data is simple
STEPS_PER_EPOCH = 100

# use small validation steps since the epoch is small
VALIDATION_STEPS = 5

config = ShapesConfig()
config.display()

-------------------------------------------------------------------------

运行结果:

Configurations:
BACKBONE resnet101
BACKBONE_STRIDES [4, 8, 16, 32, 64]
BATCH_SIZE 8
BBOX_STD_DEV [0.1 0.1 0.2 0.2]
COMPUTE_BACKBONE_SHAPE None
DETECTION_MAX_INSTANCES 100
DETECTION_MIN_CONFIDENCE 0.7
DETECTION_NMS_THRESHOLD 0.3
FPN_CLASSIF_FC_LAYERS_SIZE 1024
GPU_COUNT 1
GRADIENT_CLIP_NORM 5.0
IMAGES_PER_GPU 8
IMAGE_MAX_DIM 128
IMAGE_META_SIZE 16
IMAGE_MIN_DIM 128
IMAGE_MIN_SCALE 0
IMAGE_RESIZE_MODE square
IMAGE_SHAPE [128 128 3]
LEARNING_MOMENTUM 0.9
LEARNING_RATE 0.001
LOSS_WEIGHTS {'rpn_class_loss': 1.0, 'rpn_bbox_loss': 1.0, 'mrcnn_class_loss': 1.0, 'mrcnn_bbox_loss': 1.0, 'mrcnn_mask_loss': 1.0}
MASK_POOL_SIZE 14
MASK_SHAPE [28, 28]
MAX_GT_INSTANCES 100
MEAN_PIXEL [123.7 116.8 103.9]
MINI_MASK_SHAPE (56, 56)
NAME shapes
NUM_CLASSES 4
POOL_SIZE 7
POST_NMS_ROIS_INFERENCE 1000
POST_NMS_ROIS_TRAINING 2000
ROI_POSITIVE_RATIO 0.33
RPN_ANCHOR_RATIOS [0.5, 1, 2]
RPN_ANCHOR_SCALES (8, 16, 32, 64, 128)
RPN_ANCHOR_STRIDE 1
RPN_BBOX_STD_DEV [0.1 0.1 0.2 0.2]
RPN_NMS_THRESHOLD 0.7
RPN_TRAIN_ANCHORS_PER_IMAGE 256
STEPS_PER_EPOCH 100
TOP_DOWN_PYRAMID_SIZE 256
TRAIN_BN False
TRAIN_ROIS_PER_IMAGE 32
USE_MINI_MASK True
USE_RPN_ROIS True
VALIDATION_STEPS 5
WEIGHT_DECAY 0.0001
--------------------------------------------------------

Notebook Preferences

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.

Change the default size attribute to control the size
of rendered images
"""
_, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows))
return ax

--------------------------------------------------------------------

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()

-----------------------------------------------------------------------

class ShapesDataset(utils.Dataset):
"""Generates the shapes synthetic dataset. The dataset consists of simple
shapes (triangles, squares, circles) placed randomly on a blank surface.
The images are generated on the fly. No file access required.
"""

def load_shapes(self, count, height, width):
"""Generate the requested number of synthetic images.
count: number of images to generate.
height, width: the size of the generated images.
"""
# Add classes
self.add_class("shapes", 1, "square")
self.add_class("shapes", 2, "circle")
self.add_class("shapes", 3, "triangle")

# Add images
# Generate random specifications of images (i.e. color and
# list of shapes sizes and locations). This is more compact than
# actual images. Images are generated on the fly in load_image().
for i in range(count):
bg_color, shapes = self.random_image(height, width)
self.add_image("shapes", image_id=i, path=None,
width=width, height=height,
bg_color=bg_color, shapes=shapes)

def load_image(self, image_id):
"""Generate an image from the specs of the given image ID.
Typically this function loads the image from a file, but
in this case it generates the image on the fly from the
specs in image_info.
"""
info = self.image_info[image_id]
bg_color = np.array(info['bg_color']).reshape([1, 1, 3])
image = np.ones([info['height'], info['width'], 3], dtype=np.uint8)
image = image * bg_color.astype(np.uint8)
for shape, color, dims in info['shapes']:
image = self.draw_shape(image, shape, dims, color)
return image

def image_reference(self, image_id):
"""Return the shapes data of the image."""
info = self.image_info[image_id]
if info["source"] == "shapes":
return info["shapes"]
else:
super(self.__class__).image_reference(self, image_id)

def load_mask(self, image_id):
"""Generate instance masks for shapes of the given image ID.
"""
info = self.image_info[image_id]
shapes = info['shapes']
count = len(shapes)
mask = np.zeros([info['height'], info['width'], count], dtype=np.uint8)
for i, (shape, _, dims) in enumerate(info['shapes']):
mask[:, :, i:i+1] = self.draw_shape(mask[:, :, i:i+1].copy(),
shape, dims, 1)
# Handle occlusions
occlusion = np.logical_not(mask[:, :, -1]).astype(np.uint8)
for i in range(count-2, -1, -1):
mask[:, :, i] = mask[:, :, i] * occlusion
occlusion = np.logical_and(occlusion, np.logical_not(mask[:, :, i]))
# Map class names to class IDs.
class_ids = np.array([self.class_names.index(s[0]) for s in shapes])
return mask.astype(np.bool), class_ids.astype(np.int32)

def draw_shape(self, image, shape, dims, color):
"""Draws a shape from the given specs."""
# Get the center x, y and the size s
x, y, s = dims
if shape == 'square':
cv2.rectangle(image, (x-s, y-s), (x+s, y+s), color, -1)
elif shape == "circle":
cv2.circle(image, (x, y), s, color, -1)
elif shape == "triangle":
points = np.array([[(x, y-s),
(x-s/math.sin(math.radians(60)), y+s),
(x+s/math.sin(math.radians(60)), y+s),
]], dtype=np.int32)
cv2.fillPoly(image, points, color)
return image

def random_shape(self, height, width):
"""Generates specifications of a random shape that lies within
the given height and width boundaries.
Returns a tuple of three valus:
* The shape name (square, circle, ...)
* Shape color: a tuple of 3 values, RGB.
* Shape dimensions: A tuple of values that define the shape size
and location. Differs per shape type.
"""
# Shape
shape = random.choice(["square", "circle", "triangle"])
# Color
color = tuple([random.randint(0, 255) for _ in range(3)])
# Center x, y
buffer = 20
y = random.randint(buffer, height - buffer - 1)
x = random.randint(buffer, width - buffer - 1)
# Size
s = random.randint(buffer, height//4)
return shape, color, (x, y, s)

def random_image(self, height, width):
"""Creates random specifications of an image with multiple shapes.
Returns the background color of the image and a list of shape
specifications that can be used to draw the image.
"""
# Pick random background color
bg_color = np.array([random.randint(0, 255) for _ in range(3)])
# Generate a few random shapes and record their
# bounding boxes
shapes = []
boxes = []
N = random.randint(1, 4)
for _ in range(N):
shape, color, dims = self.random_shape(height, width)
shapes.append((shape, color, dims))
x, y, s = dims
boxes.append([y-s, x-s, y+s, x+s])
# Apply non-max suppression wit 0.3 threshold to avoid
# shapes covering each other
keep_ixs = utils.non_max_suppression(np.array(boxes), np.arange(N), 0.3)
shapes = [s for i, s in enumerate(shapes) if i in keep_ixs]
return bg_color, shapes

------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------

# Training dataset

dataset_train = ShapesDataset()

dataset_train.load_shapes(500, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1])

dataset_train.prepare()

------------------------------------------------------------------------------------

------------------------------------------------------------------------------------

# 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

------------------------------------------------------------------------

# Create model in training mode

model = modellib.MaskRCNN(mode="training", config=config,model_dir=MODEL_DIR)

-----------------------------------------------------------------------

----------------------------------------------------------------------

# 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

# are different due to the different number of classes

# See README for instructions to download the COCO weights

model.load_weights(COCO_MODEL_PATH, by_name=True,

exclude=["mrcnn_class_logits", "mrcnn_bbox_fc",

"mrcnn_bbox", "mrcnn_mask"])

elif init_with == "last":

# Load the last model you trained and continue training

model.load_weights(model.find_last(), by_name=True)

----------------------------------------------------------------------

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 the train() 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.

--------------------------------------------------------------------------

# 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,

learning_rate=config.LEARNING_RATE,

epochs=1,

layers='heads')

-------------------------------------------------------------------------

Starting at epoch 0. LR=0.001

Checkpoint Path: C:\Users\luo\tensorflow\Mask_RCNN-master\logs\shapes20180817T1409\mask_rcnn_shapes_{epoch:04d}.h5
Selecting layers to train
fpn_c5p5 (Conv2D)
fpn_c4p4 (Conv2D)
fpn_c3p3 (Conv2D)
fpn_c2p2 (Conv2D)
fpn_p5 (Conv2D)
fpn_p2 (Conv2D)
fpn_p3 (Conv2D)
fpn_p4 (Conv2D)
In model: rpn_model
rpn_conv_shared (Conv2D)
rpn_class_raw (Conv2D)
rpn_bbox_pred (Conv2D)
mrcnn_mask_conv1 (TimeDistributed)
mrcnn_mask_bn1 (TimeDistributed)
mrcnn_mask_conv2 (TimeDistributed)
mrcnn_mask_bn2 (TimeDistributed)
mrcnn_class_conv1 (TimeDistributed)
mrcnn_class_bn1 (TimeDistributed)
mrcnn_mask_conv3 (TimeDistributed)
mrcnn_mask_bn3 (TimeDistributed)
mrcnn_class_conv2 (TimeDistributed)
mrcnn_class_bn2 (TimeDistributed)
mrcnn_mask_conv4 (TimeDistributed)
mrcnn_mask_bn4 (TimeDistributed)
mrcnn_bbox_fc (TimeDistributed)
mrcnn_mask_deconv (TimeDistributed)
mrcnn_class_logits (TimeDistributed)
mrcnn_mask (TimeDistributed)
 
E:\Anaconda3\install1\lib\site-packages\tensorflow\python\ops\gradients_impl.py:97: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.
"Converting sparse IndexedSlices to a dense Tensor of unknown shape. "
 
Epoch 1/1
100/100 [==============================] - 2824s 28s/step - loss: 1.5765 - rpn_class_loss: 0.0302 - rpn_bbox_loss: 0.5675 - mrcnn_class_loss: 0.3577 - mrcnn_bbox_loss: 0.3586 - mrcnn_mask_loss: 0.2625 - val_loss: 0.9420 - val_rpn_class_loss: 0.0130 - val_rpn_bbox_loss: 0.4263 - val_mrcnn_class_loss: 0.1708 - val_mrcnn_bbox_loss: 0.1679 - val_mrcnn_mask_loss: 0.1640

-------------------------------------------------------------------

# 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=1,

layers="all")

-------------------------------------------------------------------

Starting at epoch 1. LR=0.0001

Checkpoint Path: C:\Users\luo\tensorflow\Mask_RCNN-master\logs\shapes20180817T1409\mask_rcnn_shapes_{epoch:04d}.h5
Selecting layers to train
conv1 (Conv2D)
bn_conv1 (BatchNorm)
res2a_branch2a (Conv2D)
bn2a_branch2a (BatchNorm)
res2a_branch2b (Conv2D)
bn2a_branch2b (BatchNorm)
res2a_branch2c (Conv2D)
res2a_branch1 (Conv2D)
bn2a_branch2c (BatchNorm)
bn2a_branch1 (BatchNorm)
res2b_branch2a (Conv2D)
bn2b_branch2a (BatchNorm)
res2b_branch2b (Conv2D)
bn2b_branch2b (BatchNorm)
res2b_branch2c (Conv2D)
bn2b_branch2c (BatchNorm)
res2c_branch2a (Conv2D)
bn2c_branch2a (BatchNorm)
res2c_branch2b (Conv2D)
bn2c_branch2b (BatchNorm)
res2c_branch2c (Conv2D)
bn2c_branch2c (BatchNorm)
res3a_branch2a (Conv2D)
bn3a_branch2a (BatchNorm)
res3a_branch2b (Conv2D)
bn3a_branch2b (BatchNorm)
res3a_branch2c (Conv2D)
res3a_branch1 (Conv2D)
bn3a_branch2c (BatchNorm)
bn3a_branch1 (BatchNorm)
res3b_branch2a (Conv2D)
bn3b_branch2a (BatchNorm)
res3b_branch2b (Conv2D)
bn3b_branch2b (BatchNorm)
res3b_branch2c (Conv2D)
bn3b_branch2c (BatchNorm)
res3c_branch2a (Conv2D)
bn3c_branch2a (BatchNorm)
res3c_branch2b (Conv2D)
bn3c_branch2b (BatchNorm)
res3c_branch2c (Conv2D)
bn3c_branch2c (BatchNorm)
res3d_branch2a (Conv2D)
bn3d_branch2a (BatchNorm)
res3d_branch2b (Conv2D)
bn3d_branch2b (BatchNorm)
res3d_branch2c (Conv2D)
bn3d_branch2c (BatchNorm)
res4a_branch2a (Conv2D)
bn4a_branch2a (BatchNorm)
res4a_branch2b (Conv2D)
bn4a_branch2b (BatchNorm)
res4a_branch2c (Conv2D)
res4a_branch1 (Conv2D)
bn4a_branch2c (BatchNorm)
bn4a_branch1 (BatchNorm)
res4b_branch2a (Conv2D)
bn4b_branch2a (BatchNorm)
res4b_branch2b (Conv2D)
bn4b_branch2b (BatchNorm)
res4b_branch2c (Conv2D)
bn4b_branch2c (BatchNorm)
res4c_branch2a (Conv2D)
bn4c_branch2a (BatchNorm)
res4c_branch2b (Conv2D)
bn4c_branch2b (BatchNorm)
res4c_branch2c (Conv2D)
bn4c_branch2c (BatchNorm)
res4d_branch2a (Conv2D)
bn4d_branch2a (BatchNorm)
res4d_branch2b (Conv2D)
bn4d_branch2b (BatchNorm)
res4d_branch2c (Conv2D)
bn4d_branch2c (BatchNorm)
res4e_branch2a (Conv2D)
bn4e_branch2a (BatchNorm)
res4e_branch2b (Conv2D)
bn4e_branch2b (BatchNorm)
res4e_branch2c (Conv2D)
bn4e_branch2c (BatchNorm)
res4f_branch2a (Conv2D)
bn4f_branch2a (BatchNorm)
res4f_branch2b (Conv2D)
bn4f_branch2b (BatchNorm)
res4f_branch2c (Conv2D)
bn4f_branch2c (BatchNorm)
res4g_branch2a (Conv2D)
bn4g_branch2a (BatchNorm)
res4g_branch2b (Conv2D)
bn4g_branch2b (BatchNorm)
res4g_branch2c (Conv2D)
bn4g_branch2c (BatchNorm)
res4h_branch2a (Conv2D)
bn4h_branch2a (BatchNorm)
res4h_branch2b (Conv2D)
bn4h_branch2b (BatchNorm)
res4h_branch2c (Conv2D)
bn4h_branch2c (BatchNorm)
res4i_branch2a (Conv2D)
bn4i_branch2a (BatchNorm)
res4i_branch2b (Conv2D)
bn4i_branch2b (BatchNorm)
res4i_branch2c (Conv2D)
bn4i_branch2c (BatchNorm)
res4j_branch2a (Conv2D)
bn4j_branch2a (BatchNorm)
res4j_branch2b (Conv2D)
bn4j_branch2b (BatchNorm)
res4j_branch2c (Conv2D)
bn4j_branch2c (BatchNorm)
res4k_branch2a (Conv2D)
bn4k_branch2a (BatchNorm)
res4k_branch2b (Conv2D)
bn4k_branch2b (BatchNorm)
res4k_branch2c (Conv2D)
bn4k_branch2c (BatchNorm)
res4l_branch2a (Conv2D)
bn4l_branch2a (BatchNorm)
res4l_branch2b (Conv2D)
bn4l_branch2b (BatchNorm)
res4l_branch2c (Conv2D)
bn4l_branch2c (BatchNorm)
res4m_branch2a (Conv2D)
bn4m_branch2a (BatchNorm)
res4m_branch2b (Conv2D)
bn4m_branch2b (BatchNorm)
res4m_branch2c (Conv2D)
bn4m_branch2c (BatchNorm)
res4n_branch2a (Conv2D)
bn4n_branch2a (BatchNorm)
res4n_branch2b (Conv2D)
bn4n_branch2b (BatchNorm)
res4n_branch2c (Conv2D)
bn4n_branch2c (BatchNorm)
res4o_branch2a (Conv2D)
bn4o_branch2a (BatchNorm)
res4o_branch2b (Conv2D)
bn4o_branch2b (BatchNorm)
res4o_branch2c (Conv2D)
bn4o_branch2c (BatchNorm)
res4p_branch2a (Conv2D)
bn4p_branch2a (BatchNorm)
res4p_branch2b (Conv2D)
bn4p_branch2b (BatchNorm)
res4p_branch2c (Conv2D)
bn4p_branch2c (BatchNorm)
res4q_branch2a (Conv2D)
bn4q_branch2a (BatchNorm)
res4q_branch2b (Conv2D)
bn4q_branch2b (BatchNorm)
res4q_branch2c (Conv2D)
bn4q_branch2c (BatchNorm)
res4r_branch2a (Conv2D)
bn4r_branch2a (BatchNorm)
res4r_branch2b (Conv2D)
bn4r_branch2b (BatchNorm)
res4r_branch2c (Conv2D)
bn4r_branch2c (BatchNorm)
res4s_branch2a (Conv2D)
bn4s_branch2a (BatchNorm)
res4s_branch2b (Conv2D)
bn4s_branch2b (BatchNorm)
res4s_branch2c (Conv2D)
bn4s_branch2c (BatchNorm)
res4t_branch2a (Conv2D)
bn4t_branch2a (BatchNorm)
res4t_branch2b (Conv2D)
bn4t_branch2b (BatchNorm)
res4t_branch2c (Conv2D)
bn4t_branch2c (BatchNorm)
res4u_branch2a (Conv2D)
bn4u_branch2a (BatchNorm)
res4u_branch2b (Conv2D)
bn4u_branch2b (BatchNorm)
res4u_branch2c (Conv2D)
bn4u_branch2c (BatchNorm)
res4v_branch2a (Conv2D)
bn4v_branch2a (BatchNorm)
res4v_branch2b (Conv2D)
bn4v_branch2b (BatchNorm)
res4v_branch2c (Conv2D)
bn4v_branch2c (BatchNorm)
res4w_branch2a (Conv2D)
bn4w_branch2a (BatchNorm)
res4w_branch2b (Conv2D)
bn4w_branch2b (BatchNorm)
res4w_branch2c (Conv2D)
bn4w_branch2c (BatchNorm)
res5a_branch2a (Conv2D)
bn5a_branch2a (BatchNorm)
res5a_branch2b (Conv2D)
bn5a_branch2b (BatchNorm)
res5a_branch2c (Conv2D)
res5a_branch1 (Conv2D)
bn5a_branch2c (BatchNorm)
bn5a_branch1 (BatchNorm)
res5b_branch2a (Conv2D)
bn5b_branch2a (BatchNorm)
res5b_branch2b (Conv2D)
bn5b_branch2b (BatchNorm)
res5b_branch2c (Conv2D)
bn5b_branch2c (BatchNorm)
res5c_branch2a (Conv2D)
bn5c_branch2a (BatchNorm)
res5c_branch2b (Conv2D)
bn5c_branch2b (BatchNorm)
res5c_branch2c (Conv2D)
bn5c_branch2c (BatchNorm)
fpn_c5p5 (Conv2D)
fpn_c4p4 (Conv2D)
fpn_c3p3 (Conv2D)
fpn_c2p2 (Conv2D)
fpn_p5 (Conv2D)
fpn_p2 (Conv2D)
fpn_p3 (Conv2D)
fpn_p4 (Conv2D)
In model: rpn_model
rpn_conv_shared (Conv2D)
rpn_class_raw (Conv2D)
rpn_bbox_pred (Conv2D)
mrcnn_mask_conv1 (TimeDistributed)
mrcnn_mask_bn1 (TimeDistributed)
mrcnn_mask_conv2 (TimeDistributed)
mrcnn_mask_bn2 (TimeDistributed)
mrcnn_class_conv1 (TimeDistributed)
mrcnn_class_bn1 (TimeDistributed)
mrcnn_mask_conv3 (TimeDistributed)
mrcnn_mask_bn3 (TimeDistributed)
mrcnn_class_conv2 (TimeDistributed)
mrcnn_class_bn2 (TimeDistributed)
mrcnn_mask_conv4 (TimeDistributed)
mrcnn_mask_bn4 (TimeDistributed)
mrcnn_bbox_fc (TimeDistributed)
mrcnn_mask_deconv (TimeDistributed)
mrcnn_class_logits (TimeDistributed)
mrcnn_mask (TimeDistributed)
 
E:\Anaconda3\install1\lib\site-packages\tensorflow\python\ops\gradients_impl.py:97: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.
"Converting sparse IndexedSlices to a dense Tensor of unknown shape. "

# 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

------------------------------------------------------------------------------

class InferenceConfig(ShapesConfig):

GPU_COUNT = 1

IMAGES_PER_GPU = 1

inference_config = InferenceConfig()

# Recreate the model in inference mode

model = modellib.MaskRCNN(mode="inference",

config=inference_config,

model_dir=MODEL_DIR)

# Get path to saved weights

# Either set a specific path or find last trained weights

# model_path = os.path.join(ROOT_DIR, ".h5 file name here")

model_path = model.find_last()

# Load trained weights

print("Loading weights from ", model_path)

model.load_weights(model_path, by_name=True)

-----------------------------------------------------------------------------

运行结果:

Loading weights from  C:\Users\luo\tensorflow\Mask_RCNN-master\logs\shapes20180817T1459\mask_rcnn_shapes_0001.h5

----------------------------------------------------
# Test on a random image
image_id = random.choice(dataset_val.image_ids)
original_image, image_meta, gt_class_id, gt_bbox, gt_mask =\
modellib.load_image_gt(dataset_val, inference_config,
image_id, use_mini_mask=False)
log("original_image", original_image)
log("image_meta", image_meta)
log("gt_class_id", gt_class_id)
log("gt_bbox", gt_bbox)
log("gt_mask", gt_mask)
visualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id, dataset_train.class_names, figsize=(8, 8))

-----------------------------------------------------------------------------------

original_image           shape: (128, 128, 3)         min:   72.00000  max:  248.00000  uint8
image_meta shape: (16,) min: 0.00000 max: 128.00000 int32
gt_class_id shape: (3,) min: 2.00000 max: 3.00000 int32
gt_bbox shape: (3, 4) min: 0.00000 max: 128.00000 int32
gt_mask shape: (128, 128, 3) min: 0.00000 max: 1.00000 bool

Evaluation

-----------------------------------------------------

# Compute VOC-Style mAP @ IoU=0.5 # Running on 10 images. Increase for better accuracy. image_ids = np.random.choice(dataset_val.image_ids, 10) APs = [] for image_id in image_ids: # Load image and ground truth data image, image_meta, gt_class_id, gt_bbox, gt_mask =\ modellib.load_image_gt(dataset_val, inference_config, image_id, use_mini_mask=False) molded_images = np.expand_dims(modellib.mold_image(image, inference_config), 0) # Run object detection results = model.detect([image], verbose=0) r = results[0] # Compute AP AP, precisions, recalls, overlaps =\ utils.compute_ap(gt_bbox, gt_class_id, gt_mask, r["rois"], r["class_ids"], r["scores"], r['masks']) APs.append(AP) print("mAP: ", np.mean(APs))

----------------------------------------------------

运行结果:

mAP:  0.966666667163372

train_shapesLast Checkpoint: 1 小时前(autosaved)Logout

 

Python 3 

Trusted
 
 
 
 
Run

Code
Markdown
Raw NBConvert
Heading
-

 
 
 

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 [13]:
 
 
 
 
 
1
import os
2
import sys
3
import random
4
import math
5
import re
6
import time
7
import numpy as np
8
import cv2
9
import matplotlib
10
import matplotlib.pyplot as plt
11
12
# Root directory of the project
13
ROOT_DIR = os.path.abspath("../../")
14
15
# Import Mask RCNN
16
sys.path.append(ROOT_DIR)  # To find local version of the library
17
from mrcnn.config import Config
18
from mrcnn import utils
19
import mrcnn.model as modellib
20
from mrcnn import visualize
21
from mrcnn.model import log
22
23
%matplotlib inline 
24
25
# Directory to save logs and trained model
26
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
27
28
# Local path to trained weights file
29
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
30
# Download COCO trained weights from Releases if needed
31
if not os.path.exists(COCO_MODEL_PATH):
32
    utils.download_trained_weights(COCO_MODEL_PATH)
 
 
 
 

Configurations

In [14]:
 
 
 
 
 
1
class ShapesConfig(Config):
2
    """Configuration for training on the toy shapes dataset.
3
    Derives from the base Config class and overrides values specific
4
    to the toy shapes dataset.
5
    """
6
    # Give the configuration a recognizable name
7
    NAME = "shapes"
8
9
    # Train on 1 GPU and 8 images per GPU. We can put multiple images on each
10
    # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
11
    GPU_COUNT = 1
12
    IMAGES_PER_GPU = 8
13
14
    # Number of classes (including background)
15
    NUM_CLASSES = 1 + 3  # background + 3 shapes
16
17
    # Use small images for faster training. Set the limits of the small side
18
    # the large side, and that determines the image shape.
19
    IMAGE_MIN_DIM = 128
20
    IMAGE_MAX_DIM = 128
21
22
    # Use smaller anchors because our image and objects are small
23
    RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128)  # anchor side in pixels
24
25
    # Reduce training ROIs per image because the images are small and have
26
    # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
27
    TRAIN_ROIS_PER_IMAGE = 32
28
29
    # Use a small epoch since the data is simple
30
    STEPS_PER_EPOCH = 100
31
32
    # use small validation steps since the epoch is small
33
    VALIDATION_STEPS = 5
34

35
config = ShapesConfig()
36
config.display()
 
 
 
 
Configurations:
BACKBONE resnet101
BACKBONE_STRIDES [4, 8, 16, 32, 64]
BATCH_SIZE 8
BBOX_STD_DEV [0.1 0.1 0.2 0.2]
COMPUTE_BACKBONE_SHAPE None
DETECTION_MAX_INSTANCES 100
DETECTION_MIN_CONFIDENCE 0.7
DETECTION_NMS_THRESHOLD 0.3
FPN_CLASSIF_FC_LAYERS_SIZE 1024
GPU_COUNT 1
GRADIENT_CLIP_NORM 5.0
IMAGES_PER_GPU 8
IMAGE_MAX_DIM 128
IMAGE_META_SIZE 16
IMAGE_MIN_DIM 128
IMAGE_MIN_SCALE 0
IMAGE_RESIZE_MODE square
IMAGE_SHAPE [128 128 3]
LEARNING_MOMENTUM 0.9
LEARNING_RATE 0.001
LOSS_WEIGHTS {'rpn_class_loss': 1.0, 'rpn_bbox_loss': 1.0, 'mrcnn_class_loss': 1.0, 'mrcnn_bbox_loss': 1.0, 'mrcnn_mask_loss': 1.0}
MASK_POOL_SIZE 14
MASK_SHAPE [28, 28]
MAX_GT_INSTANCES 100
MEAN_PIXEL [123.7 116.8 103.9]
MINI_MASK_SHAPE (56, 56)
NAME shapes
NUM_CLASSES 4
POOL_SIZE 7
POST_NMS_ROIS_INFERENCE 1000
POST_NMS_ROIS_TRAINING 2000
ROI_POSITIVE_RATIO 0.33
RPN_ANCHOR_RATIOS [0.5, 1, 2]
RPN_ANCHOR_SCALES (8, 16, 32, 64, 128)
RPN_ANCHOR_STRIDE 1
RPN_BBOX_STD_DEV [0.1 0.1 0.2 0.2]
RPN_NMS_THRESHOLD 0.7
RPN_TRAIN_ANCHORS_PER_IMAGE 256
STEPS_PER_EPOCH 100
TOP_DOWN_PYRAMID_SIZE 256
TRAIN_BN False
TRAIN_ROIS_PER_IMAGE 32
USE_MINI_MASK True
USE_RPN_ROIS True
VALIDATION_STEPS 5
WEIGHT_DECAY 0.0001
 

Notebook Preferences

In [15]:
 
 
 
 
 
1
def get_ax(rows=1, cols=1, size=8):
2
    """Return a Matplotlib Axes array to be used in
3
    all visualizations in the notebook. Provide a
4
    central point to control graph sizes.
5

6
    Change the default size attribute to control the size
7
    of rendered images
8
    """
9
    _, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows))
10
    return ax
 
 
 
 

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 [16]:
 
 
 
 
 
1
class ShapesDataset(utils.Dataset):
2
    """Generates the shapes synthetic dataset. The dataset consists of simple
3
    shapes (triangles, squares, circles) placed randomly on a blank surface.
4
    The images are generated on the fly. No file access required.
5
    """
6
7
    def load_shapes(self, count, height, width):
8
        """Generate the requested number of synthetic images.
9
        count: number of images to generate.
10
        height, width: the size of the generated images.
11
        """
12
        # Add classes
13
        self.add_class("shapes", 1, "square")
14
        self.add_class("shapes", 2, "circle")
15
        self.add_class("shapes", 3, "triangle")
16
17
        # Add images
18
        # Generate random specifications of images (i.e. color and
19
        # list of shapes sizes and locations). This is more compact than
20
        # actual images. Images are generated on the fly in load_image().
21
        for i in range(count):
22
            bg_color, shapes = self.random_image(height, width)
23
            self.add_image("shapes", image_id=i, path=None,
24
                           width=width, height=height,
25
                           bg_color=bg_color, shapes=shapes)
26
27
    def load_image(self, image_id):
28
        """Generate an image from the specs of the given image ID.
29
        Typically this function loads the image from a file, but
30
        in this case it generates the image on the fly from the
31
        specs in image_info.
32
        """
33
        info = self.image_info[image_id]
34
        bg_color = np.array(info['bg_color']).reshape([1, 1, 3])
35
        image = np.ones([info['height'], info['width'], 3], dtype=np.uint8)
36
        image = image * bg_color.astype(np.uint8)
37
        for shape, color, dims in info['shapes']:
38
            image = self.draw_shape(image, shape, dims, color)
39
        return image
40
41
    def image_reference(self, image_id):
42
        """Return the shapes data of the image."""
43
        info = self.image_info[image_id]
44
        if info["source"] == "shapes":
45
            return info["shapes"]
46
        else:
47
            super(self.__class__).image_reference(self, image_id)
48
49
    def load_mask(self, image_id):
50
        """Generate instance masks for shapes of the given image ID.
51
        """
52
        info = self.image_info[image_id]
53
        shapes = info['shapes']
54
        count = len(shapes)
55
        mask = np.zeros([info['height'], info['width'], count], dtype=np.uint8)
56
        for i, (shape, _, dims) in enumerate(info['shapes']):
57
            mask[:, :, i:i+1] = self.draw_shape(mask[:, :, i:i+1].copy(),
58
                                                shape, dims, 1)
59
        # Handle occlusions
60
        occlusion = np.logical_not(mask[:, :, -1]).astype(np.uint8)
61
        for i in range(count-2, -1, -1):
62
            mask[:, :, i] = mask[:, :, i] * occlusion
63
            occlusion = np.logical_and(occlusion, np.logical_not(mask[:, :, i]))
64
        # Map class names to class IDs.
65
        class_ids = np.array([self.class_names.index(s[0]) for s in shapes])
66
        return mask.astype(np.bool), class_ids.astype(np.int32)
67
68
    def draw_shape(self, image, shape, dims, color):
69
        """Draws a shape from the given specs."""
70
        # Get the center x, y and the size s
71
        x, y, s = dims
72
        if shape == 'square':
73
            cv2.rectangle(image, (x-s, y-s), (x+s, y+s), color, -1)
74
        elif shape == "circle":
75
            cv2.circle(image, (x, y), s, color, -1)
76
        elif shape == "triangle":
77
            points = np.array([[(x, y-s),
78
                                (x-s/math.sin(math.radians(60)), y+s),
79
                                (x+s/math.sin(math.radians(60)), y+s),
80
                                ]], dtype=np.int32)
81
            cv2.fillPoly(image, points, color)
82
        return image
83
84
    def random_shape(self, height, width):
85
        """Generates specifications of a random shape that lies within
86
        the given height and width boundaries.
87
        Returns a tuple of three valus:
88
        * The shape name (square, circle, ...)
89
        * Shape color: a tuple of 3 values, RGB.
90
        * Shape dimensions: A tuple of values that define the shape size
91
                            and location. Differs per shape type.
92
        """
93
        # Shape
94
        shape = random.choice(["square", "circle", "triangle"])
95
        # Color
96
        color = tuple([random.randint(0, 255) for _ in range(3)])
97
        # Center x, y
98
        buffer = 20
99
        y = random.randint(buffer, height - buffer - 1)
100
        x = random.randint(buffer, width - buffer - 1)
101
        # Size
102
        s = random.randint(buffer, height//4)
103
        return shape, color, (x, y, s)
104
105
    def random_image(self, height, width):
106
        """Creates random specifications of an image with multiple shapes.
107
        Returns the background color of the image and a list of shape
108
        specifications that can be used to draw the image.
109
        """
110
        # Pick random background color
111
        bg_color = np.array([random.randint(0, 255) for _ in range(3)])
112
        # Generate a few random shapes and record their
113
        # bounding boxes
114
        shapes = []
115
        boxes = []
116
        N = random.randint(1, 4)
117
        for _ in range(N):
118
            shape, color, dims = self.random_shape(height, width)
119
            shapes.append((shape, color, dims))
120
            x, y, s = dims
121
            boxes.append([y-s, x-s, y+s, x+s])
122
        # Apply non-max suppression wit 0.3 threshold to avoid
123
        # shapes covering each other
124
        keep_ixs = utils.non_max_suppression(np.array(boxes), np.arange(N), 0.3)
125
        shapes = [s for i, s in enumerate(shapes) if i in keep_ixs]
126
        return bg_color, shapes
 
 
 
In [17]:
 
 
 
 
 
1
# Training dataset
2
dataset_train = ShapesDataset()
3
dataset_train.load_shapes(500, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1])
4
dataset_train.prepare()
5
6
# Validation dataset
7
dataset_val = ShapesDataset()
8
dataset_val.load_shapes(50, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1])
9
dataset_val.prepare()
 
 
 
In [18]:
 
 
 
 
 
1
# Load and display random samples
2
image_ids = np.random.choice(dataset_train.image_ids, 4)
3
for image_id in image_ids:
4
    image = dataset_train.load_image(image_id)
5
    mask, class_ids = dataset_train.load_mask(image_id)
6
    visualize.display_top_masks(image, mask, class_ids, dataset_train.class_names)
 
 
 
 
 
 
 
 

Ceate Model

In [19]:
 
 
 
 
 
1
# Create model in training mode
2
model = modellib.MaskRCNN(mode="training", config=config,
3
                          model_dir=MODEL_DIR)
 
 
 
In [20]:
 
 
 
 
 
1
# Which weights to start with?
2
init_with = "coco"  # imagenet, coco, or last
3
4
if init_with == "imagenet":
5
    model.load_weights(model.get_imagenet_weights(), by_name=True)
6
elif init_with == "coco":
7
    # Load weights trained on MS COCO, but skip layers that
8
    # are different due to the different number of classes
9
    # See README for instructions to download the COCO weights
10
    model.load_weights(COCO_MODEL_PATH, by_name=True,
11
                       exclude=["mrcnn_class_logits", "mrcnn_bbox_fc", 
12
                                "mrcnn_bbox", "mrcnn_mask"])
13
elif init_with == "last":
14
    # Load the last model you trained and continue training
15
    model.load_weights(model.find_last(), by_name=True)
 
 
 
 

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 the train() 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 [21]:
 
 
 
 
 
1
# Train the head branches
2
# Passing layers="heads" freezes all layers except the head
3
# layers. You can also pass a regular expression to select
4
# which layers to train by name pattern.
5
model.train(dataset_train, dataset_val, 
6
            learning_rate=config.LEARNING_RATE, 
7
            epochs=1, 
8
            layers='heads')
 
 
 
 
Starting at epoch 0. LR=0.001

Checkpoint Path: C:\Users\luo\tensorflow\Mask_RCNN-master\logs\shapes20180817T1409\mask_rcnn_shapes_{epoch:04d}.h5
Selecting layers to train
fpn_c5p5 (Conv2D)
fpn_c4p4 (Conv2D)
fpn_c3p3 (Conv2D)
fpn_c2p2 (Conv2D)
fpn_p5 (Conv2D)
fpn_p2 (Conv2D)
fpn_p3 (Conv2D)
fpn_p4 (Conv2D)
In model: rpn_model
rpn_conv_shared (Conv2D)
rpn_class_raw (Conv2D)
rpn_bbox_pred (Conv2D)
mrcnn_mask_conv1 (TimeDistributed)
mrcnn_mask_bn1 (TimeDistributed)
mrcnn_mask_conv2 (TimeDistributed)
mrcnn_mask_bn2 (TimeDistributed)
mrcnn_class_conv1 (TimeDistributed)
mrcnn_class_bn1 (TimeDistributed)
mrcnn_mask_conv3 (TimeDistributed)
mrcnn_mask_bn3 (TimeDistributed)
mrcnn_class_conv2 (TimeDistributed)
mrcnn_class_bn2 (TimeDistributed)
mrcnn_mask_conv4 (TimeDistributed)
mrcnn_mask_bn4 (TimeDistributed)
mrcnn_bbox_fc (TimeDistributed)
mrcnn_mask_deconv (TimeDistributed)
mrcnn_class_logits (TimeDistributed)
mrcnn_mask (TimeDistributed)
 
E:\Anaconda3\install1\lib\site-packages\tensorflow\python\ops\gradients_impl.py:97: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.
"Converting sparse IndexedSlices to a dense Tensor of unknown shape. "
 
Epoch 1/1
100/100 [==============================] - 2824s 28s/step - loss: 1.5765 - rpn_class_loss: 0.0302 - rpn_bbox_loss: 0.5675 - mrcnn_class_loss: 0.3577 - mrcnn_bbox_loss: 0.3586 - mrcnn_mask_loss: 0.2625 - val_loss: 0.9420 - val_rpn_class_loss: 0.0130 - val_rpn_bbox_loss: 0.4263 - val_mrcnn_class_loss: 0.1708 - val_mrcnn_bbox_loss: 0.1679 - val_mrcnn_mask_loss: 0.1640
In [22]:
 
 
 
 
 
1
# Fine tune all layers
2
# Passing layers="all" trains all layers. You can also 
3
# pass a regular expression to select which layers to
4
# train by name pattern.
5
model.train(dataset_train, dataset_val, 
6
            learning_rate=config.LEARNING_RATE / 10,
7
            epochs=1, 
8
            layers="all")
 
 
 
 
Starting at epoch 1. LR=0.0001

Checkpoint Path: C:\Users\luo\tensorflow\Mask_RCNN-master\logs\shapes20180817T1409\mask_rcnn_shapes_{epoch:04d}.h5
Selecting layers to train
conv1 (Conv2D)
bn_conv1 (BatchNorm)
res2a_branch2a (Conv2D)
bn2a_branch2a (BatchNorm)
res2a_branch2b (Conv2D)
bn2a_branch2b (BatchNorm)
res2a_branch2c (Conv2D)
res2a_branch1 (Conv2D)
bn2a_branch2c (BatchNorm)
bn2a_branch1 (BatchNorm)
res2b_branch2a (Conv2D)
bn2b_branch2a (BatchNorm)
res2b_branch2b (Conv2D)
bn2b_branch2b (BatchNorm)
res2b_branch2c (Conv2D)
bn2b_branch2c (BatchNorm)
res2c_branch2a (Conv2D)
bn2c_branch2a (BatchNorm)
res2c_branch2b (Conv2D)
bn2c_branch2b (BatchNorm)
res2c_branch2c (Conv2D)
bn2c_branch2c (BatchNorm)
res3a_branch2a (Conv2D)
bn3a_branch2a (BatchNorm)
res3a_branch2b (Conv2D)
bn3a_branch2b (BatchNorm)
res3a_branch2c (Conv2D)
res3a_branch1 (Conv2D)
bn3a_branch2c (BatchNorm)
bn3a_branch1 (BatchNorm)
res3b_branch2a (Conv2D)
bn3b_branch2a (BatchNorm)
res3b_branch2b (Conv2D)
bn3b_branch2b (BatchNorm)
res3b_branch2c (Conv2D)
bn3b_branch2c (BatchNorm)
res3c_branch2a (Conv2D)
bn3c_branch2a (BatchNorm)
res3c_branch2b (Conv2D)
bn3c_branch2b (BatchNorm)
res3c_branch2c (Conv2D)
bn3c_branch2c (BatchNorm)
res3d_branch2a (Conv2D)
bn3d_branch2a (BatchNorm)
res3d_branch2b (Conv2D)
bn3d_branch2b (BatchNorm)
res3d_branch2c (Conv2D)
bn3d_branch2c (BatchNorm)
res4a_branch2a (Conv2D)
bn4a_branch2a (BatchNorm)
res4a_branch2b (Conv2D)
bn4a_branch2b (BatchNorm)
res4a_branch2c (Conv2D)
res4a_branch1 (Conv2D)
bn4a_branch2c (BatchNorm)
bn4a_branch1 (BatchNorm)
res4b_branch2a (Conv2D)
bn4b_branch2a (BatchNorm)
res4b_branch2b (Conv2D)
bn4b_branch2b (BatchNorm)
res4b_branch2c (Conv2D)
bn4b_branch2c (BatchNorm)
res4c_branch2a (Conv2D)
bn4c_branch2a (BatchNorm)
res4c_branch2b (Conv2D)
bn4c_branch2b (BatchNorm)
res4c_branch2c (Conv2D)
bn4c_branch2c (BatchNorm)
res4d_branch2a (Conv2D)
bn4d_branch2a (BatchNorm)
res4d_branch2b (Conv2D)
bn4d_branch2b (BatchNorm)
res4d_branch2c (Conv2D)
bn4d_branch2c (BatchNorm)
res4e_branch2a (Conv2D)
bn4e_branch2a (BatchNorm)
res4e_branch2b (Conv2D)
bn4e_branch2b (BatchNorm)
res4e_branch2c (Conv2D)
bn4e_branch2c (BatchNorm)
res4f_branch2a (Conv2D)
bn4f_branch2a (BatchNorm)
res4f_branch2b (Conv2D)
bn4f_branch2b (BatchNorm)
res4f_branch2c (Conv2D)
bn4f_branch2c (BatchNorm)
res4g_branch2a (Conv2D)
bn4g_branch2a (BatchNorm)
res4g_branch2b (Conv2D)
bn4g_branch2b (BatchNorm)
res4g_branch2c (Conv2D)
bn4g_branch2c (BatchNorm)
res4h_branch2a (Conv2D)
bn4h_branch2a (BatchNorm)
res4h_branch2b (Conv2D)
bn4h_branch2b (BatchNorm)
res4h_branch2c (Conv2D)
bn4h_branch2c (BatchNorm)
res4i_branch2a (Conv2D)
bn4i_branch2a (BatchNorm)
res4i_branch2b (Conv2D)
bn4i_branch2b (BatchNorm)
res4i_branch2c (Conv2D)
bn4i_branch2c (BatchNorm)
res4j_branch2a (Conv2D)
bn4j_branch2a (BatchNorm)
res4j_branch2b (Conv2D)
bn4j_branch2b (BatchNorm)
res4j_branch2c (Conv2D)
bn4j_branch2c (BatchNorm)
res4k_branch2a (Conv2D)
bn4k_branch2a (BatchNorm)
res4k_branch2b (Conv2D)
bn4k_branch2b (BatchNorm)
res4k_branch2c (Conv2D)
bn4k_branch2c (BatchNorm)
res4l_branch2a (Conv2D)
bn4l_branch2a (BatchNorm)
res4l_branch2b (Conv2D)
bn4l_branch2b (BatchNorm)
res4l_branch2c (Conv2D)
bn4l_branch2c (BatchNorm)
res4m_branch2a (Conv2D)
bn4m_branch2a (BatchNorm)
res4m_branch2b (Conv2D)
bn4m_branch2b (BatchNorm)
res4m_branch2c (Conv2D)
bn4m_branch2c (BatchNorm)
res4n_branch2a (Conv2D)
bn4n_branch2a (BatchNorm)
res4n_branch2b (Conv2D)
bn4n_branch2b (BatchNorm)
res4n_branch2c (Conv2D)
bn4n_branch2c (BatchNorm)
res4o_branch2a (Conv2D)
bn4o_branch2a (BatchNorm)
res4o_branch2b (Conv2D)
bn4o_branch2b (BatchNorm)
res4o_branch2c (Conv2D)
bn4o_branch2c (BatchNorm)
res4p_branch2a (Conv2D)
bn4p_branch2a (BatchNorm)
res4p_branch2b (Conv2D)
bn4p_branch2b (BatchNorm)
res4p_branch2c (Conv2D)
bn4p_branch2c (BatchNorm)
res4q_branch2a (Conv2D)
bn4q_branch2a (BatchNorm)
res4q_branch2b (Conv2D)
bn4q_branch2b (BatchNorm)
res4q_branch2c (Conv2D)
bn4q_branch2c (BatchNorm)
res4r_branch2a (Conv2D)
bn4r_branch2a (BatchNorm)
res4r_branch2b (Conv2D)
bn4r_branch2b (BatchNorm)
res4r_branch2c (Conv2D)
bn4r_branch2c (BatchNorm)
res4s_branch2a (Conv2D)
bn4s_branch2a (BatchNorm)
res4s_branch2b (Conv2D)
bn4s_branch2b (BatchNorm)
res4s_branch2c (Conv2D)
bn4s_branch2c (BatchNorm)
res4t_branch2a (Conv2D)
bn4t_branch2a (BatchNorm)
res4t_branch2b (Conv2D)
bn4t_branch2b (BatchNorm)
res4t_branch2c (Conv2D)
bn4t_branch2c (BatchNorm)
res4u_branch2a (Conv2D)
bn4u_branch2a (BatchNorm)
res4u_branch2b (Conv2D)
bn4u_branch2b (BatchNorm)
res4u_branch2c (Conv2D)
bn4u_branch2c (BatchNorm)
res4v_branch2a (Conv2D)
bn4v_branch2a (BatchNorm)
res4v_branch2b (Conv2D)
bn4v_branch2b (BatchNorm)
res4v_branch2c (Conv2D)
bn4v_branch2c (BatchNorm)
res4w_branch2a (Conv2D)
bn4w_branch2a (BatchNorm)
res4w_branch2b (Conv2D)
bn4w_branch2b (BatchNorm)
res4w_branch2c (Conv2D)
bn4w_branch2c (BatchNorm)
res5a_branch2a (Conv2D)
bn5a_branch2a (BatchNorm)
res5a_branch2b (Conv2D)
bn5a_branch2b (BatchNorm)
res5a_branch2c (Conv2D)
res5a_branch1 (Conv2D)
bn5a_branch2c (BatchNorm)
bn5a_branch1 (BatchNorm)
res5b_branch2a (Conv2D)
bn5b_branch2a (BatchNorm)
res5b_branch2b (Conv2D)
bn5b_branch2b (BatchNorm)
res5b_branch2c (Conv2D)
bn5b_branch2c (BatchNorm)
res5c_branch2a (Conv2D)
bn5c_branch2a (BatchNorm)
res5c_branch2b (Conv2D)
bn5c_branch2b (BatchNorm)
res5c_branch2c (Conv2D)
bn5c_branch2c (BatchNorm)
fpn_c5p5 (Conv2D)
fpn_c4p4 (Conv2D)
fpn_c3p3 (Conv2D)
fpn_c2p2 (Conv2D)
fpn_p5 (Conv2D)
fpn_p2 (Conv2D)
fpn_p3 (Conv2D)
fpn_p4 (Conv2D)
In model: rpn_model
rpn_conv_shared (Conv2D)
rpn_class_raw (Conv2D)
rpn_bbox_pred (Conv2D)
mrcnn_mask_conv1 (TimeDistributed)
mrcnn_mask_bn1 (TimeDistributed)
mrcnn_mask_conv2 (TimeDistributed)
mrcnn_mask_bn2 (TimeDistributed)
mrcnn_class_conv1 (TimeDistributed)
mrcnn_class_bn1 (TimeDistributed)
mrcnn_mask_conv3 (TimeDistributed)
mrcnn_mask_bn3 (TimeDistributed)
mrcnn_class_conv2 (TimeDistributed)
mrcnn_class_bn2 (TimeDistributed)
mrcnn_mask_conv4 (TimeDistributed)
mrcnn_mask_bn4 (TimeDistributed)
mrcnn_bbox_fc (TimeDistributed)
mrcnn_mask_deconv (TimeDistributed)
mrcnn_class_logits (TimeDistributed)
mrcnn_mask (TimeDistributed)
 
E:\Anaconda3\install1\lib\site-packages\tensorflow\python\ops\gradients_impl.py:97: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.
"Converting sparse IndexedSlices to a dense Tensor of unknown shape. "
In [23]:
 
 
 
 
 
1
# Save weights
2
# Typically not needed because callbacks save after every epoch
3
# Uncomment to save manually
4
# model_path = os.path.join(MODEL_DIR, "mask_rcnn_shapes.h5")
5
# model.keras_model.save_weights(model_path)
 
 
 
 

Detection

In [26]:
 
 
 
 
 
1
class InferenceConfig(ShapesConfig):
2
    GPU_COUNT = 1
3
    IMAGES_PER_GPU = 1
4
5
inference_config = InferenceConfig()
6
7
# Recreate the model in inference mode
8
model = modellib.MaskRCNN(mode="inference", 
9
                          config=inference_config,
10
                          model_dir=MODEL_DIR)
11
12
# Get path to saved weights
13
# Either set a specific path or find last trained weights
14
# model_path = os.path.join(ROOT_DIR, ".h5 file name here")
15
model_path = model.find_last()
16
17
# Load trained weights
18
print("Loading weights from ", model_path)
19
model.load_weights(model_path, by_name=True)
 
 
 
 
Loading weights from  C:\Users\luo\tensorflow\Mask_RCNN-master\logs\shapes20180817T1459\mask_rcnn_shapes_0001.h5
In [27]:
 
 
 
 
 
1
# Test on a random image
2
image_id = random.choice(dataset_val.image_ids)
3
original_image, image_meta, gt_class_id, gt_bbox, gt_mask =\
4
    modellib.load_image_gt(dataset_val, inference_config, 
5
                           image_id, use_mini_mask=False)
6
7
log("original_image", original_image)
8
log("image_meta", image_meta)
9
log("gt_class_id", gt_class_id)
10
log("gt_bbox", gt_bbox)
11
log("gt_mask", gt_mask)
12
13
visualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id, 
14
                            dataset_train.class_names, figsize=(8, 8))
 
 
 
 
original_image           shape: (128, 128, 3)         min:   72.00000  max:  248.00000  uint8
image_meta shape: (16,) min: 0.00000 max: 128.00000 int32
gt_class_id shape: (3,) min: 2.00000 max: 3.00000 int32
gt_bbox shape: (3, 4) min: 0.00000 max: 128.00000 int32
gt_mask shape: (128, 128, 3) min: 0.00000 max: 1.00000 bool
 
In [28]:
 
 
 
 
 
1
results = model.detect([original_image], verbose=1)
2
3
r = results[0]
4
visualize.display_instances(original_image, r['rois'], r['masks'], r['class_ids'], 
5
                            dataset_val.class_names, r['scores'], ax=get_ax())
 
 
 
 
Processing 1 images
image shape: (128, 128, 3) min: 72.00000 max: 248.00000 uint8
molded_images shape: (1, 128, 128, 3) min: -51.70000 max: 144.10000 float64
image_metas shape: (1, 16) min: 0.00000 max: 128.00000 int32
anchors shape: (1, 4092, 4) min: -0.71267 max: 1.20874 float32
 
 

Evaluation

In [29]:
 
 
 
 
 
1
# Compute VOC-Style mAP @ IoU=0.5
2
# Running on 10 images. Increase for better accuracy.
3
image_ids = np.random.choice(dataset_val.image_ids, 10)
4
APs = []
5
for image_id in image_ids:
6
    # Load image and ground truth data
7
    image, image_meta, gt_class_id, gt_bbox, gt_mask =\
8
        modellib.load_image_gt(dataset_val, inference_config,
9
                               image_id, use_mini_mask=False)
10
    molded_images = np.expand_dims(modellib.mold_image(image, inference_config), 0)
11
    # Run object detection
12
    results = model.detect([image], verbose=0)
13
    r = results[0]
14
    # Compute AP
15
    AP, precisions, recalls, overlaps =\
16
        utils.compute_ap(gt_bbox, gt_class_id, gt_mask,
17
                         r["rois"], r["class_ids"], r["scores"], r['masks'])
18
    APs.append(AP)
19

20
print("mAP: ", np.mean(APs))
 
 
 
 
mAP:  0.966666667163372
In [ ]:
 
 
 
 
 
1
 
 
 

Tensorflow学习(练习)—CPU训练模型的更多相关文章

  1. Tensorflow学习教程------读取数据、建立网络、训练模型,小巧而完整的代码示例

    紧接上篇Tensorflow学习教程------tfrecords数据格式生成与读取,本篇将数据读取.建立网络以及模型训练整理成一个小样例,完整代码如下. #coding:utf-8 import t ...

  2. 用tensorflow学习贝叶斯个性化排序(BPR)

    在贝叶斯个性化排序(BPR)算法小结中,我们对贝叶斯个性化排序(Bayesian Personalized Ranking, 以下简称BPR)的原理做了讨论,本文我们将从实践的角度来使用BPR做一个简 ...

  3. Tensorflow学习笔记2019.01.22

    tensorflow学习笔记2 edit by Strangewx 2019.01.04 4.1 机器学习基础 4.1.1 一般结构: 初始化模型参数:通常随机赋值,简单模型赋值0 训练数据:一般打乱 ...

  4. Tensorflow学习笔记2019.01.03

    tensorflow学习笔记: 3.2 Tensorflow中定义数据流图 张量知识矩阵的一个超集. 超集:如果一个集合S2中的每一个元素都在集合S1中,且集合S1中可能包含S2中没有的元素,则集合S ...

  5. 深度学习-tensorflow学习笔记(2)-MNIST手写字体识别

    深度学习-tensorflow学习笔记(2)-MNIST手写字体识别超级详细版 这是tf入门的第一个例子.minst应该是内置的数据集. 前置知识在学习笔记(1)里面讲过了 这里直接上代码 # -*- ...

  6. tensorflow学习笔记(2)-反向传播

    tensorflow学习笔记(2)-反向传播 反向传播是为了训练模型参数,在所有参数上使用梯度下降,让NN模型在的损失函数最小 损失函数:学过机器学习logistic回归都知道损失函数-就是预测值和真 ...

  7. tensorflow学习笔记——使用TensorFlow操作MNIST数据(2)

    tensorflow学习笔记——使用TensorFlow操作MNIST数据(1) 一:神经网络知识点整理 1.1,多层:使用多层权重,例如多层全连接方式 以下定义了三个隐藏层的全连接方式的神经网络样例 ...

  8. tensorflow学习笔记——自编码器及多层感知器

    1,自编码器简介 传统机器学习任务很大程度上依赖于好的特征工程,比如对数值型,日期时间型,种类型等特征的提取.特征工程往往是非常耗时耗力的,在图像,语音和视频中提取到有效的特征就更难了,工程师必须在这 ...

  9. tensorflow学习笔记——使用TensorFlow操作MNIST数据(1)

    续集请点击我:tensorflow学习笔记——使用TensorFlow操作MNIST数据(2) 本节开始学习使用tensorflow教程,当然从最简单的MNIST开始.这怎么说呢,就好比编程入门有He ...

  10. TensorFlow学习笔记(1)—— 基本概念与框架

    入门框架时的常见问题 学习框架的原因? 方便.易用 学习框架的哪些知识点? 掌握一个项目的基本流程,就知道需要学习哪些知识点了 迅速学习框架的方法 根据项目每块流程的需要针对性的学 可以看官方的入门教 ...

随机推荐

  1. rebar安装及创建项目

    rebar作为erlang开发中编译,构建,发布,打包,动态升级的常用工具,下面我记录下rebar工具的安装及使用 从源码安装rebar 1. 建立文件 install_rebar.sh 2. 拷贝如 ...

  2. 【英语】Bingo口语笔记(84) - 惊讶的表达

  3. Http基础(记忆笔记)

    地址解析:http://localhost.com:8080/index.htm 协议名:Http 主机名:localhost.com 端口:8080 对象路径:/index.htm 通过域名解析lo ...

  4. HDU - 5088: Revenge of Nim II (问是否存在子集的异或为0)

    Nim is a mathematical game of strategy in which two players take turns removing objects from distinc ...

  5. Spring XML和Annotation混合配置的时候,XML中Bean名称写错会导致启动异常不打印、死循环

    今天做Tomcat迁移Spring Boot,遇到一个坑.启动没有错误,CPU特别高 经过把堆栈kill -3 打印出来,发现堆栈特别长(没有死循环),所有的堆栈信息都集中在org.springfra ...

  6. elasticsearch5.6.8中文分词器

    安装分词器,务必确保版本一致! 下载地址:https://github.com/medcl/elasticsearch-analysis-ik 为了保证一致,我特地将elasticsearch进行降级 ...

  7. left join的多重串联与groupby

    有三张表或组合查询,f1,f2,f3,其中,f1分别与f2,f3是一对多关系,f1一条记录可能对应f2或f3中0条或多条记录 要创建一个查询,以f1为基准,即f1中有多少条记录,结果也就返回对应数量的 ...

  8. 10.solr学习速成之高亮显示

    Solr高亮显示的三种实现 高亮显示在搜索中使用的比较多,比较常用的有三种使用方式,如果要对某field做高亮显示,必须对该field设置stored=true .          第一种是普通的高 ...

  9. temp3

  10. linux grep打印匹配的上下几行

    $grep -5 'parttern' inputfile //打印匹配行的前后5行 $grep -C 5 'parttern' inputfile //打印匹配行的前后5行 $grep -A 5 ' ...