Spaces:
Runtime error
Runtime error
File size: 13,185 Bytes
153628e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
# Copyright (C) 2021-2024, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
from copy import deepcopy
from typing import Any, Callable, Dict, List, Optional, Tuple
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.models import Sequential
from doctr.datasets import VOCABS
from ...utils import conv_sequence, load_pretrained_params
__all__ = ["ResNet", "resnet18", "resnet31", "resnet34", "resnet50", "resnet34_wide"]
default_cfgs: Dict[str, Dict[str, Any]] = {
"resnet18": {
"mean": (0.694, 0.695, 0.693),
"std": (0.299, 0.296, 0.301),
"input_shape": (32, 32, 3),
"classes": list(VOCABS["french"]),
"url": "https://doctr-static.mindee.com/models?id=v0.4.1/resnet18-d4634669.zip&src=0",
},
"resnet31": {
"mean": (0.694, 0.695, 0.693),
"std": (0.299, 0.296, 0.301),
"input_shape": (32, 32, 3),
"classes": list(VOCABS["french"]),
"url": "https://doctr-static.mindee.com/models?id=v0.5.0/resnet31-5a47a60b.zip&src=0",
},
"resnet34": {
"mean": (0.694, 0.695, 0.693),
"std": (0.299, 0.296, 0.301),
"input_shape": (32, 32, 3),
"classes": list(VOCABS["french"]),
"url": "https://doctr-static.mindee.com/models?id=v0.5.0/resnet34-5dcc97ca.zip&src=0",
},
"resnet50": {
"mean": (0.694, 0.695, 0.693),
"std": (0.299, 0.296, 0.301),
"input_shape": (32, 32, 3),
"classes": list(VOCABS["french"]),
"url": "https://doctr-static.mindee.com/models?id=v0.5.0/resnet50-e75e4cdf.zip&src=0",
},
"resnet34_wide": {
"mean": (0.694, 0.695, 0.693),
"std": (0.299, 0.296, 0.301),
"input_shape": (32, 32, 3),
"classes": list(VOCABS["french"]),
"url": "https://doctr-static.mindee.com/models?id=v0.5.0/resnet34_wide-c1271816.zip&src=0",
},
}
class ResnetBlock(layers.Layer):
"""Implements a resnet31 block with shortcut
Args:
----
conv_shortcut: Use of shortcut
output_channels: number of channels to use in Conv2D
kernel_size: size of square kernels
strides: strides to use in the first convolution of the block
"""
def __init__(self, output_channels: int, conv_shortcut: bool, strides: int = 1, **kwargs) -> None:
super().__init__(**kwargs)
if conv_shortcut:
self.shortcut = Sequential([
layers.Conv2D(
filters=output_channels,
strides=strides,
padding="same",
kernel_size=1,
use_bias=False,
kernel_initializer="he_normal",
),
layers.BatchNormalization(),
])
else:
self.shortcut = layers.Lambda(lambda x: x)
self.conv_block = Sequential(self.conv_resnetblock(output_channels, 3, strides))
self.act = layers.Activation("relu")
@staticmethod
def conv_resnetblock(
output_channels: int,
kernel_size: int,
strides: int = 1,
) -> List[layers.Layer]:
return [
*conv_sequence(output_channels, "relu", bn=True, strides=strides, kernel_size=kernel_size),
*conv_sequence(output_channels, None, bn=True, kernel_size=kernel_size),
]
def call(self, inputs: tf.Tensor) -> tf.Tensor:
clone = self.shortcut(inputs)
conv_out = self.conv_block(inputs)
out = self.act(clone + conv_out)
return out
def resnet_stage(
num_blocks: int, out_channels: int, shortcut: bool = False, downsample: bool = False
) -> List[layers.Layer]:
_layers: List[layers.Layer] = [ResnetBlock(out_channels, conv_shortcut=shortcut, strides=2 if downsample else 1)]
for _ in range(1, num_blocks):
_layers.append(ResnetBlock(out_channels, conv_shortcut=False))
return _layers
class ResNet(Sequential):
"""Implements a ResNet architecture
Args:
----
num_blocks: number of resnet block in each stage
output_channels: number of channels in each stage
stage_downsample: whether the first residual block of a stage should downsample
stage_conv: whether to add a conv_sequence after each stage
stage_pooling: pooling to add after each stage (if None, no pooling)
origin_stem: whether to use the orginal ResNet stem or ResNet-31's
stem_channels: number of output channels of the stem convolutions
attn_module: attention module to use in each stage
include_top: whether the classifier head should be instantiated
num_classes: number of output classes
input_shape: shape of inputs
"""
def __init__(
self,
num_blocks: List[int],
output_channels: List[int],
stage_downsample: List[bool],
stage_conv: List[bool],
stage_pooling: List[Optional[Tuple[int, int]]],
origin_stem: bool = True,
stem_channels: int = 64,
attn_module: Optional[Callable[[int], layers.Layer]] = None,
include_top: bool = True,
num_classes: int = 1000,
cfg: Optional[Dict[str, Any]] = None,
input_shape: Optional[Tuple[int, int, int]] = None,
) -> None:
inplanes = stem_channels
if origin_stem:
_layers = [
*conv_sequence(inplanes, "relu", True, kernel_size=7, strides=2, input_shape=input_shape),
layers.MaxPool2D(pool_size=(3, 3), strides=2, padding="same"),
]
else:
_layers = [
*conv_sequence(inplanes // 2, "relu", True, kernel_size=3, input_shape=input_shape),
*conv_sequence(inplanes, "relu", True, kernel_size=3),
layers.MaxPool2D(pool_size=2, strides=2, padding="valid"),
]
for n_blocks, out_chan, down, conv, pool in zip(
num_blocks, output_channels, stage_downsample, stage_conv, stage_pooling
):
_layers.extend(resnet_stage(n_blocks, out_chan, out_chan != inplanes, down))
if attn_module is not None:
_layers.append(attn_module(out_chan))
if conv:
_layers.extend(conv_sequence(out_chan, activation="relu", bn=True, kernel_size=3))
if pool:
_layers.append(layers.MaxPool2D(pool_size=pool, strides=pool, padding="valid"))
inplanes = out_chan
if include_top:
_layers.extend([
layers.GlobalAveragePooling2D(),
layers.Dense(num_classes),
])
super().__init__(_layers)
self.cfg = cfg
def _resnet(
arch: str,
pretrained: bool,
num_blocks: List[int],
output_channels: List[int],
stage_downsample: List[bool],
stage_conv: List[bool],
stage_pooling: List[Optional[Tuple[int, int]]],
origin_stem: bool = True,
**kwargs: Any,
) -> ResNet:
kwargs["num_classes"] = kwargs.get("num_classes", len(default_cfgs[arch]["classes"]))
kwargs["input_shape"] = kwargs.get("input_shape", default_cfgs[arch]["input_shape"])
kwargs["classes"] = kwargs.get("classes", default_cfgs[arch]["classes"])
_cfg = deepcopy(default_cfgs[arch])
_cfg["num_classes"] = kwargs["num_classes"]
_cfg["classes"] = kwargs["classes"]
_cfg["input_shape"] = kwargs["input_shape"]
kwargs.pop("classes")
# Build the model
model = ResNet(
num_blocks, output_channels, stage_downsample, stage_conv, stage_pooling, origin_stem, cfg=_cfg, **kwargs
)
# Load pretrained parameters
if pretrained:
load_pretrained_params(model, default_cfgs[arch]["url"])
return model
def resnet18(pretrained: bool = False, **kwargs: Any) -> ResNet:
"""Resnet-18 architecture as described in `"Deep Residual Learning for Image Recognition",
<https://arxiv.org/pdf/1512.03385.pdf>`_.
>>> import tensorflow as tf
>>> from doctr.models import resnet18
>>> model = resnet18(pretrained=False)
>>> input_tensor = tf.random.uniform(shape=[1, 512, 512, 3], maxval=1, dtype=tf.float32)
>>> out = model(input_tensor)
Args:
----
pretrained: boolean, True if model is pretrained
**kwargs: keyword arguments of the ResNet architecture
Returns:
-------
A classification model
"""
return _resnet(
"resnet18",
pretrained,
[2, 2, 2, 2],
[64, 128, 256, 512],
[False, True, True, True],
[False] * 4,
[None] * 4,
True,
**kwargs,
)
def resnet31(pretrained: bool = False, **kwargs: Any) -> ResNet:
"""Resnet31 architecture with rectangular pooling windows as described in
`"Show, Attend and Read:A Simple and Strong Baseline for Irregular Text Recognition",
<https://arxiv.org/pdf/1811.00751.pdf>`_. Downsizing: (H, W) --> (H/8, W/4)
>>> import tensorflow as tf
>>> from doctr.models import resnet31
>>> model = resnet31(pretrained=False)
>>> input_tensor = tf.random.uniform(shape=[1, 512, 512, 3], maxval=1, dtype=tf.float32)
>>> out = model(input_tensor)
Args:
----
pretrained: boolean, True if model is pretrained
**kwargs: keyword arguments of the ResNet architecture
Returns:
-------
A classification model
"""
return _resnet(
"resnet31",
pretrained,
[1, 2, 5, 3],
[256, 256, 512, 512],
[False] * 4,
[True] * 4,
[(2, 2), (2, 1), None, None],
False,
stem_channels=128,
**kwargs,
)
def resnet34(pretrained: bool = False, **kwargs: Any) -> ResNet:
"""Resnet-34 architecture as described in `"Deep Residual Learning for Image Recognition",
<https://arxiv.org/pdf/1512.03385.pdf>`_.
>>> import tensorflow as tf
>>> from doctr.models import resnet34
>>> model = resnet34(pretrained=False)
>>> input_tensor = tf.random.uniform(shape=[1, 512, 512, 3], maxval=1, dtype=tf.float32)
>>> out = model(input_tensor)
Args:
----
pretrained: boolean, True if model is pretrained
**kwargs: keyword arguments of the ResNet architecture
Returns:
-------
A classification model
"""
return _resnet(
"resnet34",
pretrained,
[3, 4, 6, 3],
[64, 128, 256, 512],
[False, True, True, True],
[False] * 4,
[None] * 4,
True,
**kwargs,
)
def resnet50(pretrained: bool = False, **kwargs: Any) -> ResNet:
"""Resnet-50 architecture as described in `"Deep Residual Learning for Image Recognition",
<https://arxiv.org/pdf/1512.03385.pdf>`_.
>>> import tensorflow as tf
>>> from doctr.models import resnet50
>>> model = resnet50(pretrained=False)
>>> input_tensor = tf.random.uniform(shape=[1, 512, 512, 3], maxval=1, dtype=tf.float32)
>>> out = model(input_tensor)
Args:
----
pretrained: boolean, True if model is pretrained
**kwargs: keyword arguments of the ResNet architecture
Returns:
-------
A classification model
"""
kwargs["num_classes"] = kwargs.get("num_classes", len(default_cfgs["resnet50"]["classes"]))
kwargs["input_shape"] = kwargs.get("input_shape", default_cfgs["resnet50"]["input_shape"])
kwargs["classes"] = kwargs.get("classes", default_cfgs["resnet50"]["classes"])
_cfg = deepcopy(default_cfgs["resnet50"])
_cfg["num_classes"] = kwargs["num_classes"]
_cfg["classes"] = kwargs["classes"]
_cfg["input_shape"] = kwargs["input_shape"]
kwargs.pop("classes")
model = ResNet50(
weights=None,
include_top=True,
pooling=True,
input_shape=kwargs["input_shape"],
classes=kwargs["num_classes"],
classifier_activation=None,
)
model.cfg = _cfg
# Load pretrained parameters
if pretrained:
load_pretrained_params(model, default_cfgs["resnet50"]["url"])
return model
def resnet34_wide(pretrained: bool = False, **kwargs: Any) -> ResNet:
"""Resnet-34 architecture as described in `"Deep Residual Learning for Image Recognition",
<https://arxiv.org/pdf/1512.03385.pdf>`_ with twice as many output channels for each stage.
>>> import tensorflow as tf
>>> from doctr.models import resnet34_wide
>>> model = resnet34_wide(pretrained=False)
>>> input_tensor = tf.random.uniform(shape=[1, 512, 512, 3], maxval=1, dtype=tf.float32)
>>> out = model(input_tensor)
Args:
----
pretrained: boolean, True if model is pretrained
**kwargs: keyword arguments of the ResNet architecture
Returns:
-------
A classification model
"""
return _resnet(
"resnet34_wide",
pretrained,
[3, 4, 6, 3],
[128, 256, 512, 1024],
[False, True, True, True],
[False] * 4,
[None] * 4,
True,
stem_channels=128,
**kwargs,
)
|