Skip to content

Commit 62c46fa

Browse files
committed
Remove feature visualization
1 parent b23c047 commit 62c46fa

5 files changed

Lines changed: 17 additions & 54 deletions

File tree

detect.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ def run(
8787
classes=None, # filter by class: --class 0, or --class 0 2 3
8888
agnostic_nms=False, # class-agnostic NMS
8989
augment=False, # augmented inference
90-
visualize=False, # visualize features
9190
update=False, # update all models
9291
project=ROOT / "runs/detect", # save results to project/name
9392
name="exp", # save results to project/name
@@ -122,7 +121,6 @@ def run(
122121
classes (list[int]): List of class indices to filter detections by. Default is None.
123122
agnostic_nms (bool): If True, perform class-agnostic non-max suppression. Default is False.
124123
augment (bool): If True, use augmented inference. Default is False.
125-
visualize (bool): If True, visualize feature maps. Default is False.
126124
update (bool): If True, update all models' weights. Default is False.
127125
project (str | Path): Directory to save results. Default is 'runs/detect'.
128126
name (str): Name of the current experiment; used to create a subdirectory within 'project'. Default is 'exp'.
@@ -215,17 +213,16 @@ def write_to_csv(image_name, prediction, confidence):
215213

216214
# Inference
217215
with dt[1]:
218-
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
219216
if model.xml and im.shape[0] > 1:
220217
pred = None
221218
for image in ims:
222219
if pred is None:
223-
pred = model(image, augment=augment, visualize=visualize).unsqueeze(0)
220+
pred = model(image, augment=augment).unsqueeze(0)
224221
else:
225-
pred = torch.cat((pred, model(image, augment=augment, visualize=visualize).unsqueeze(0)), dim=0)
222+
pred = torch.cat((pred, model(image, augment=augment).unsqueeze(0)), dim=0)
226223
pred = [pred, None]
227224
else:
228-
pred = model(im, augment=augment, visualize=visualize)
225+
pred = model(im, augment=augment)
229226
# NMS
230227
with dt[2]:
231228
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
@@ -350,7 +347,6 @@ def parse_opt():
350347
None.
351348
--agnostic-nms (bool, optional): Flag for class-agnostic NMS. Defaults to False.
352349
--augment (bool, optional): Flag for augmented inference. Defaults to False.
353-
--visualize (bool, optional): Flag for visualizing features. Defaults to False.
354350
--update (bool, optional): Flag to update all models in the model directory. Defaults to False.
355351
--project (str, optional): Directory to save results. Defaults to ROOT / 'runs/detect'.
356352
--name (str, optional): Sub-directory name for saving results within --project. Defaults to 'exp'.
@@ -396,7 +392,6 @@ def parse_opt():
396392
parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3")
397393
parser.add_argument("--agnostic-nms", action="store_true", help="class-agnostic NMS")
398394
parser.add_argument("--augment", action="store_true", help="augmented inference")
399-
parser.add_argument("--visualize", action="store_true", help="visualize features")
400395
parser.add_argument("--update", action="store_true", help="update all models")
401396
parser.add_argument("--project", default=ROOT / "runs/detect", help="save results to project/name")
402397
parser.add_argument("--name", default="exp", help="save results to project/name")

models/common.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -682,16 +682,16 @@ def wrap_frozen_graph(gd, inputs, outputs):
682682

683683
self.__dict__.update(locals()) # assign all variables to self
684684

685-
def forward(self, im, augment=False, visualize=False):
686-
"""Performs YOLOv5 inference on input images with options for augmentation and visualization."""
685+
def forward(self, im, augment=False):
686+
"""Performs YOLOv5 inference on input images with optional augmentation."""
687687
_b, _ch, h, w = im.shape # batch, channel, height, width
688688
if self.fp16 and im.dtype != torch.float16:
689689
im = im.half() # to FP16
690690
if self.nhwc:
691691
im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3)
692692

693693
if self.pt: # PyTorch
694-
y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)
694+
y = self.model(im, augment=augment) if augment else self.model(im)
695695
elif self.jit: # TorchScript
696696
y = self.model(im)
697697
elif self.dnn: # ONNX OpenCV DNN

models/experimental.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,9 @@ def forward(self, x):
4848
class Ensemble(nn.ModuleList):
4949
"""Ensemble of models."""
5050

51-
def forward(self, x, augment=False, profile=False, visualize=False):
51+
def forward(self, x, augment=False, profile=False):
5252
"""Performs forward pass aggregating outputs from an ensemble of models."""
53-
y = [module(x, augment, profile, visualize)[0] for module in self]
53+
y = [module(x, augment, profile)[0] for module in self]
5454
# y = torch.stack(y).max(0)[0] # max ensemble
5555
# y = torch.stack(y).mean(0) # mean ensemble
5656
y = torch.cat(y, 1) # nms ensemble

models/yolo.py

Lines changed: 8 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -68,31 +68,6 @@
6868
thop = None
6969

7070

71-
def feature_visualization(x, module_type, stage, n=32, save_dir=Path("runs/detect/exp")):
72-
"""Visualize feature maps of a given model module during inference."""
73-
import matplotlib.pyplot as plt
74-
import numpy as np
75-
76-
if any(m in module_type for m in ("Detect", "Segment", "Classify")):
77-
return
78-
if isinstance(x, torch.Tensor):
79-
_, channels, height, width = x.shape
80-
if height > 1 and width > 1:
81-
f = save_dir / f"stage{stage}_{module_type.rsplit('.', 1)[-1]}_features.png"
82-
blocks = torch.chunk(x[0].cpu(), channels, dim=0)
83-
n = min(n, channels)
84-
_, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True)
85-
ax = ax.ravel()
86-
plt.subplots_adjust(wspace=0.05, hspace=0.05)
87-
for i in range(n):
88-
ax[i].imshow(blocks[i].squeeze().numpy())
89-
ax[i].axis("off")
90-
LOGGER.info(f"Saving {f}... ({n}/{channels})")
91-
plt.savefig(f, dpi=300, bbox_inches="tight")
92-
plt.close()
93-
np.save(str(f.with_suffix(".npy")), x[0].cpu().numpy())
94-
95-
9671
class Detect(nn.Module):
9772
"""YOLOv5 Detect head for processing input tensors and generating detection outputs in object detection models."""
9873

@@ -178,14 +153,12 @@ def forward(self, x):
178153
class BaseModel(nn.Module):
179154
"""YOLOv5 base model."""
180155

181-
def forward(self, x, profile=False, visualize=False):
182-
"""Executes a single-scale inference or training pass on the YOLOv5 base model, with options for profiling and
183-
visualization.
184-
"""
185-
return self._forward_once(x, profile, visualize) # single-scale inference, train
156+
def forward(self, x, profile=False):
157+
"""Executes a single-scale inference or training pass on the YOLOv5 base model."""
158+
return self._forward_once(x, profile) # single-scale inference, train
186159

187-
def _forward_once(self, x, profile=False, visualize=False):
188-
"""Performs a forward pass on the YOLOv5 model, enabling profiling and feature visualization options."""
160+
def _forward_once(self, x, profile=False):
161+
"""Performs a forward pass on the YOLOv5 model, enabling profiling when requested."""
189162
y, dt = [], [] # outputs
190163
for m in self.model:
191164
if m.f != -1: # if not from previous layer
@@ -194,8 +167,6 @@ def _forward_once(self, x, profile=False, visualize=False):
194167
self._profile_one_layer(m, x, dt)
195168
x = m(x) # run
196169
y.append(x if m.i in self.save else None) # save output
197-
if visualize:
198-
feature_visualization(x, m.type, m.i, save_dir=visualize)
199170
return x
200171

201172
def _profile_one_layer(self, m, x, dt):
@@ -289,11 +260,11 @@ def _forward(x):
289260
self.info()
290261
LOGGER.info("")
291262

292-
def forward(self, x, augment=False, profile=False, visualize=False):
293-
"""Performs single-scale or augmented inference and may include profiling or visualization."""
263+
def forward(self, x, augment=False, profile=False):
264+
"""Performs single-scale or augmented inference and may include profiling."""
294265
if augment:
295266
return self._forward_augment(x) # augmented inference, None
296-
return self._forward_once(x, profile, visualize) # single-scale inference, train
267+
return self._forward_once(x, profile) # single-scale inference, train
297268

298269
def _forward_augment(self, x):
299270
"""Performs augmented inference across different scales and flips, returning combined detections."""

segment/predict.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,6 @@ def run(
8585
classes=None, # filter by class: --class 0, or --class 0 2 3
8686
agnostic_nms=False, # class-agnostic NMS
8787
augment=False, # augmented inference
88-
visualize=False, # visualize features
8988
update=False, # update all models
9089
project=ROOT / "runs/predict-seg", # save results to project/name
9190
name="exp", # save results to project/name
@@ -143,8 +142,7 @@ def run(
143142

144143
# Inference
145144
with dt[1]:
146-
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
147-
pred, proto = model(im, augment=augment, visualize=visualize)[:2]
145+
pred, proto = model(im, augment=augment)[:2]
148146

149147
# NMS
150148
with dt[2]:
@@ -271,7 +269,6 @@ def parse_opt():
271269
parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3")
272270
parser.add_argument("--agnostic-nms", action="store_true", help="class-agnostic NMS")
273271
parser.add_argument("--augment", action="store_true", help="augmented inference")
274-
parser.add_argument("--visualize", action="store_true", help="visualize features")
275272
parser.add_argument("--update", action="store_true", help="update all models")
276273
parser.add_argument("--project", default=ROOT / "runs/predict-seg", help="save results to project/name")
277274
parser.add_argument("--name", default="exp", help="save results to project/name")

0 commit comments

Comments
 (0)