|
|
|
""" |
|
Common modules |
|
""" |
|
|
|
import math |
|
import warnings |
|
from copy import copy |
|
from pathlib import Path |
|
from urllib.parse import urlparse |
|
|
|
import cv2 |
|
import numpy as np |
|
import pandas as pd |
|
import requests |
|
import torch |
|
import torch.nn as nn |
|
from PIL import Image |
|
from torch.cuda import amp |
|
|
|
from utils import TryExcept |
|
from utils.dataloaders import exif_transpose, letterbox |
|
from utils.general import (LOGGER, ROOT, Profile, colorstr, |
|
increment_path, is_notebook, make_divisible, non_max_suppression, scale_boxes, xyxy2xywh, yaml_load) |
|
from utils.plots import Annotator, colors, save_one_box |
|
from utils.torch_utils import copy_attr, smart_inference_mode |
|
|
|
|
|
def autopad(k, p=None, d=1): |
|
|
|
if d > 1: |
|
k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] |
|
if p is None: |
|
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] |
|
return p |
|
|
|
|
|
class Conv(nn.Module): |
|
|
|
default_act = nn.SiLU() |
|
|
|
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True): |
|
super().__init__() |
|
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False) |
|
self.bn = nn.BatchNorm2d(c2) |
|
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity() |
|
|
|
def forward(self, x): |
|
return self.act(self.bn(self.conv(x))) |
|
|
|
def forward_fuse(self, x): |
|
return self.act(self.conv(x)) |
|
|
|
|
|
class DWConv(Conv): |
|
|
|
def __init__(self, c1, c2, k=1, s=1, d=1, act=True): |
|
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act) |
|
|
|
|
|
class DWConvTranspose2d(nn.ConvTranspose2d): |
|
|
|
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): |
|
super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2)) |
|
|
|
|
|
class TransformerLayer(nn.Module): |
|
|
|
def __init__(self, c, num_heads): |
|
super().__init__() |
|
self.q = nn.Linear(c, c, bias=False) |
|
self.k = nn.Linear(c, c, bias=False) |
|
self.v = nn.Linear(c, c, bias=False) |
|
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) |
|
self.fc1 = nn.Linear(c, c, bias=False) |
|
self.fc2 = nn.Linear(c, c, bias=False) |
|
|
|
def forward(self, x): |
|
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x |
|
x = self.fc2(self.fc1(x)) + x |
|
return x |
|
|
|
|
|
class TransformerBlock(nn.Module): |
|
|
|
def __init__(self, c1, c2, num_heads, num_layers): |
|
super().__init__() |
|
self.conv = None |
|
if c1 != c2: |
|
self.conv = Conv(c1, c2) |
|
self.linear = nn.Linear(c2, c2) |
|
self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers))) |
|
self.c2 = c2 |
|
|
|
def forward(self, x): |
|
if self.conv is not None: |
|
x = self.conv(x) |
|
b, _, w, h = x.shape |
|
p = x.flatten(2).permute(2, 0, 1) |
|
return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h) |
|
|
|
|
|
class Bottleneck(nn.Module): |
|
|
|
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): |
|
super().__init__() |
|
c_ = int(c2 * e) |
|
self.cv1 = Conv(c1, c_, 1, 1) |
|
self.cv2 = Conv(c_, c2, 3, 1, g=g) |
|
self.add = shortcut and c1 == c2 |
|
|
|
def forward(self, x): |
|
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) |
|
|
|
|
|
class BottleneckCSP(nn.Module): |
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): |
|
super().__init__() |
|
c_ = int(c2 * e) |
|
self.cv1 = Conv(c1, c_, 1, 1) |
|
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) |
|
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) |
|
self.cv4 = Conv(2 * c_, c2, 1, 1) |
|
self.bn = nn.BatchNorm2d(2 * c_) |
|
self.act = nn.SiLU() |
|
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) |
|
|
|
def forward(self, x): |
|
y1 = self.cv3(self.m(self.cv1(x))) |
|
y2 = self.cv2(x) |
|
return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1)))) |
|
|
|
|
|
class CrossConv(nn.Module): |
|
|
|
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): |
|
|
|
super().__init__() |
|
c_ = int(c2 * e) |
|
self.cv1 = Conv(c1, c_, (1, k), (1, s)) |
|
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) |
|
self.add = shortcut and c1 == c2 |
|
|
|
def forward(self, x): |
|
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) |
|
|
|
|
|
class C3(nn.Module): |
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): |
|
super().__init__() |
|
c_ = int(c2 * e) |
|
self.cv1 = Conv(c1, c_, 1, 1) |
|
self.cv2 = Conv(c1, c_, 1, 1) |
|
self.cv3 = Conv(2 * c_, c2, 1) |
|
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) |
|
|
|
def forward(self, x): |
|
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)) |
|
|
|
|
|
class C3x(C3): |
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): |
|
super().__init__(c1, c2, n, shortcut, g, e) |
|
c_ = int(c2 * e) |
|
self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n))) |
|
|
|
|
|
class C3TR(C3): |
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): |
|
super().__init__(c1, c2, n, shortcut, g, e) |
|
c_ = int(c2 * e) |
|
self.m = TransformerBlock(c_, c_, 4, n) |
|
|
|
|
|
class C3SPP(C3): |
|
|
|
def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5): |
|
super().__init__(c1, c2, n, shortcut, g, e) |
|
c_ = int(c2 * e) |
|
self.m = SPP(c_, c_, k) |
|
|
|
|
|
class C3Ghost(C3): |
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): |
|
super().__init__(c1, c2, n, shortcut, g, e) |
|
c_ = int(c2 * e) |
|
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n))) |
|
|
|
|
|
class SPP(nn.Module): |
|
|
|
def __init__(self, c1, c2, k=(5, 9, 13)): |
|
super().__init__() |
|
c_ = c1 // 2 |
|
self.cv1 = Conv(c1, c_, 1, 1) |
|
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) |
|
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) |
|
|
|
def forward(self, x): |
|
x = self.cv1(x) |
|
with warnings.catch_warnings(): |
|
warnings.simplefilter('ignore') |
|
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) |
|
|
|
|
|
class SPPF(nn.Module): |
|
|
|
def __init__(self, c1, c2, k=5): |
|
super().__init__() |
|
c_ = c1 // 2 |
|
self.cv1 = Conv(c1, c_, 1, 1) |
|
self.cv2 = Conv(c_ * 4, c2, 1, 1) |
|
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) |
|
|
|
def forward(self, x): |
|
x = self.cv1(x) |
|
with warnings.catch_warnings(): |
|
warnings.simplefilter('ignore') |
|
y1 = self.m(x) |
|
y2 = self.m(y1) |
|
return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1)) |
|
|
|
|
|
class Focus(nn.Module): |
|
|
|
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): |
|
super().__init__() |
|
self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act) |
|
|
|
|
|
def forward(self, x): |
|
return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1)) |
|
|
|
|
|
|
|
class GhostConv(nn.Module): |
|
|
|
def __init__(self, c1, c2, k=1, s=1, g=1, act=True): |
|
super().__init__() |
|
c_ = c2 // 2 |
|
self.cv1 = Conv(c1, c_, k, s, None, g, act=act) |
|
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act) |
|
|
|
def forward(self, x): |
|
y = self.cv1(x) |
|
return torch.cat((y, self.cv2(y)), 1) |
|
|
|
|
|
class GhostBottleneck(nn.Module): |
|
|
|
def __init__(self, c1, c2, k=3, s=1): |
|
super().__init__() |
|
c_ = c2 // 2 |
|
self.conv = nn.Sequential( |
|
GhostConv(c1, c_, 1, 1), |
|
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), |
|
GhostConv(c_, c2, 1, 1, act=False)) |
|
self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, |
|
act=False)) if s == 2 else nn.Identity() |
|
|
|
def forward(self, x): |
|
return self.conv(x) + self.shortcut(x) |
|
|
|
|
|
class Contract(nn.Module): |
|
|
|
def __init__(self, gain=2): |
|
super().__init__() |
|
self.gain = gain |
|
|
|
def forward(self, x): |
|
b, c, h, w = x.size() |
|
s = self.gain |
|
x = x.view(b, c, h // s, s, w // s, s) |
|
x = x.permute(0, 3, 5, 1, 2, 4).contiguous() |
|
return x.view(b, c * s * s, h // s, w // s) |
|
|
|
|
|
class Expand(nn.Module): |
|
|
|
def __init__(self, gain=2): |
|
super().__init__() |
|
self.gain = gain |
|
|
|
def forward(self, x): |
|
b, c, h, w = x.size() |
|
s = self.gain |
|
x = x.view(b, s, s, c // s ** 2, h, w) |
|
x = x.permute(0, 3, 4, 1, 5, 2).contiguous() |
|
return x.view(b, c // s ** 2, h * s, w * s) |
|
|
|
|
|
class Concat(nn.Module): |
|
|
|
def __init__(self, dimension=1): |
|
super().__init__() |
|
self.d = dimension |
|
|
|
def forward(self, x): |
|
return torch.cat(x, self.d) |
|
|
|
|
|
class DetectMultiBackend(nn.Module): |
|
|
|
def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True): |
|
|
|
|
|
from models.experimental import attempt_load |
|
|
|
super().__init__() |
|
w = str(weights[0] if isinstance(weights, list) else weights) |
|
pt = self._model_type(w)[0] |
|
fp16 = True |
|
nhwc = False |
|
stride = 32 |
|
cuda = torch.cuda.is_available() and device.type != 'cpu' |
|
model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse) |
|
stride = max(int(model.stride.max()), 32) |
|
names = model.module.names if hasattr(model, 'module') else model.names |
|
model.half() if fp16 else model.float() |
|
self.model = model |
|
|
|
|
|
if 'names' not in locals(): |
|
names = yaml_load(data)['names'] if data else {i: f'class{i}' for i in range(999)} |
|
if names[0] == 'n01440764' and len(names) == 1000: |
|
names = yaml_load(ROOT / 'data/ImageNet.yaml')['names'] |
|
|
|
self.__dict__.update(locals()) |
|
|
|
def forward(self, im, augment=False, visualize=False): |
|
|
|
b, ch, h, w = im.shape |
|
if self.fp16 and im.dtype != torch.float16: |
|
im = im.half() |
|
if self.nhwc: |
|
im = im.permute(0, 2, 3, 1) |
|
|
|
if self.pt: |
|
y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im) |
|
|
|
if isinstance(y, (list, tuple)): |
|
return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y] |
|
else: |
|
return self.from_numpy(y) |
|
|
|
def from_numpy(self, x): |
|
return torch.from_numpy(x).to(self.device) if isinstance(x, np.ndarray) else x |
|
|
|
def warmup(self, imgsz=(1, 3, 640, 640)): |
|
|
|
warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton |
|
if any(warmup_types) and (self.device.type != 'cpu' or self.triton): |
|
im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) |
|
for _ in range(2 if self.jit else 1): |
|
self.forward(im) |
|
|
|
@staticmethod |
|
def _model_type(p='path/to/model.pt'): |
|
|
|
def export_formats(): |
|
x = [['PyTorch', '-', '.pt', True, True],] |
|
return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU']) |
|
|
|
sf = list(export_formats().Suffix) |
|
url = urlparse(p) |
|
types = [s in Path(p).name for s in sf] |
|
triton = False |
|
return types + [triton] |
|
|
|
@staticmethod |
|
def _load_metadata(f=Path('path/to/meta.yaml')): |
|
|
|
if f.exists(): |
|
d = yaml_load(f) |
|
return d['stride'], d['names'] |
|
return None, None |
|
|
|
|
|
class AutoShape(nn.Module): |
|
|
|
conf = 0.25 |
|
iou = 0.45 |
|
agnostic = False |
|
multi_label = False |
|
classes = None |
|
max_det = 1000 |
|
amp = False |
|
|
|
def __init__(self, model, verbose=True): |
|
super().__init__() |
|
if verbose: |
|
LOGGER.info('Adding AutoShape... ') |
|
copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) |
|
self.dmb = isinstance(model, DetectMultiBackend) |
|
self.pt = not self.dmb or model.pt |
|
self.model = model.eval() |
|
if self.pt: |
|
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] |
|
m.inplace = False |
|
m.export = True |
|
|
|
def _apply(self, fn): |
|
|
|
self = super()._apply(fn) |
|
if self.pt: |
|
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] |
|
m.stride = fn(m.stride) |
|
m.grid = list(map(fn, m.grid)) |
|
if isinstance(m.anchor_grid, list): |
|
m.anchor_grid = list(map(fn, m.anchor_grid)) |
|
return self |
|
|
|
@smart_inference_mode() |
|
def forward(self, ims, size=640, augment=False, profile=False): |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dt = (Profile(), Profile(), Profile()) |
|
with dt[0]: |
|
if isinstance(size, int): |
|
size = (size, size) |
|
p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device) |
|
autocast = self.amp and (p.device.type != 'cpu') |
|
if isinstance(ims, torch.Tensor): |
|
with amp.autocast(autocast): |
|
return self.model(ims.to(p.device).type_as(p), augment=augment) |
|
|
|
|
|
n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims]) |
|
shape0, shape1, files = [], [], [] |
|
for i, im in enumerate(ims): |
|
f = f'image{i}' |
|
if isinstance(im, (str, Path)): |
|
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im |
|
im = np.asarray(exif_transpose(im)) |
|
elif isinstance(im, Image.Image): |
|
im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f |
|
files.append(Path(f).with_suffix('.jpg').name) |
|
if im.shape[0] < 5: |
|
im = im.transpose((1, 2, 0)) |
|
im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) |
|
s = im.shape[:2] |
|
shape0.append(s) |
|
g = max(size) / max(s) |
|
shape1.append([int(y * g) for y in s]) |
|
ims[i] = im if im.data.contiguous else np.ascontiguousarray(im) |
|
shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] |
|
x = [letterbox(im, shape1, auto=False)[0] for im in ims] |
|
x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) |
|
x = torch.from_numpy(x).to(p.device).type_as(p) / 255 |
|
|
|
with amp.autocast(autocast): |
|
|
|
with dt[1]: |
|
y = self.model(x, augment=augment) |
|
|
|
|
|
with dt[2]: |
|
y = non_max_suppression(y if self.dmb else y[0], |
|
self.conf, |
|
self.iou, |
|
self.classes, |
|
self.agnostic, |
|
self.multi_label, |
|
max_det=self.max_det) |
|
for i in range(n): |
|
scale_boxes(shape1, y[i][:, :4], shape0[i]) |
|
|
|
return Detections(ims, y, files, dt, self.names, x.shape) |
|
|
|
|
|
class Detections: |
|
|
|
def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None): |
|
super().__init__() |
|
d = pred[0].device |
|
gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims] |
|
self.ims = ims |
|
self.pred = pred |
|
self.names = names |
|
self.files = files |
|
self.times = times |
|
self.xyxy = pred |
|
self.xywh = [xyxy2xywh(x) for x in pred] |
|
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] |
|
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] |
|
self.n = len(self.pred) |
|
self.t = tuple(x.t / self.n * 1E3 for x in times) |
|
self.s = tuple(shape) |
|
|
|
def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')): |
|
s, crops = '', [] |
|
for i, (im, pred) in enumerate(zip(self.ims, self.pred)): |
|
s += f'\nimage {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' |
|
if pred.shape[0]: |
|
for c in pred[:, -1].unique(): |
|
n = (pred[:, -1] == c).sum() |
|
s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " |
|
s = s.rstrip(', ') |
|
if show or save or render or crop: |
|
annotator = Annotator(im, example=str(self.names)) |
|
for *box, conf, cls in reversed(pred): |
|
label = f'{self.names[int(cls)]} {conf:.2f}' |
|
if crop: |
|
file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None |
|
crops.append({ |
|
'box': box, |
|
'conf': conf, |
|
'cls': cls, |
|
'label': label, |
|
'im': save_one_box(box, im, file=file, save=save)}) |
|
else: |
|
annotator.box_label(box, label if labels else '', color=colors(cls)) |
|
im = annotator.im |
|
else: |
|
s += '(no detections)' |
|
|
|
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im |
|
|
|
if save: |
|
f = self.files[i] |
|
im.save(save_dir / f) |
|
if i == self.n - 1: |
|
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}") |
|
if render: |
|
self.ims[i] = np.asarray(im) |
|
if pprint: |
|
s = s.lstrip('\n') |
|
return f'{s}\nSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {self.s}' % self.t |
|
if crop: |
|
if save: |
|
LOGGER.info(f'Saved results to {save_dir}\n') |
|
return crops |
|
|
|
@TryExcept('Showing images is not supported in this environment') |
|
def show(self, labels=True): |
|
self._run(show=True, labels=labels) |
|
|
|
def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False): |
|
save_dir = increment_path(save_dir, exist_ok, mkdir=True) |
|
self._run(save=True, labels=labels, save_dir=save_dir) |
|
|
|
def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False): |
|
save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None |
|
return self._run(crop=True, save=save, save_dir=save_dir) |
|
|
|
def render(self, labels=True): |
|
self._run(render=True, labels=labels) |
|
return self.ims |
|
|
|
def pandas(self): |
|
|
|
new = copy(self) |
|
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' |
|
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' |
|
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]): |
|
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] |
|
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a]) |
|
return new |
|
|
|
def tolist(self): |
|
|
|
r = range(self.n) |
|
x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r] |
|
|
|
|
|
|
|
return x |
|
|
|
def print(self): |
|
LOGGER.info(self.__str__()) |
|
|
|
def __len__(self): |
|
return self.n |
|
|
|
def __str__(self): |
|
return self._run(pprint=True) |
|
|
|
def __repr__(self): |
|
return f'YOLOv5 {self.__class__} instance\n' + self.__str__() |
|
|
|
|
|
class Proto(nn.Module): |
|
|
|
def __init__(self, c1, c_=256, c2=32): |
|
super().__init__() |
|
self.cv1 = Conv(c1, c_, k=3) |
|
self.upsample = nn.Upsample(scale_factor=2, mode='nearest') |
|
self.cv2 = Conv(c_, c_, k=3) |
|
self.cv3 = Conv(c_, c2) |
|
|
|
def forward(self, x): |
|
return self.cv3(self.cv2(self.upsample(self.cv1(x)))) |
|
|
|
|
|
class Classify(nn.Module): |
|
|
|
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): |
|
super().__init__() |
|
c_ = 1280 |
|
self.conv = Conv(c1, c_, k, s, autopad(k, p), g) |
|
self.pool = nn.AdaptiveAvgPool2d(1) |
|
self.drop = nn.Dropout(p=0.0, inplace=True) |
|
self.linear = nn.Linear(c_, c2) |
|
|
|
def forward(self, x): |
|
if isinstance(x, list): |
|
x = torch.cat(x, 1) |
|
return self.linear(self.drop(self.pool(self.conv(x)).flatten(1))) |
|
|