MCPcopy Create free account
hub / github.com/open-mmlab/mmengine / cat

Method cat

mmengine/structures/instance_data.py:251–304  ·  view source on GitHub ↗

Concat the instances of all :obj:`InstanceData` in the list. Note: To ensure that cat returns as expected, make sure that all elements in the list must have exactly the same keys. Args: instances_list (list[:obj:`InstanceData`]): A list of :obj:`

(instances_list: List['InstanceData'])

Source from the content-addressed store, hash-verified

249
250 @staticmethod
251 def cat(instances_list: List['InstanceData']) -> 'InstanceData':
252 """Concat the instances of all :obj:`InstanceData` in the list.
253
254 Note: To ensure that cat returns as expected, make sure that
255 all elements in the list must have exactly the same keys.
256
257 Args:
258 instances_list (list[:obj:`InstanceData`]): A list
259 of :obj:`InstanceData`.
260
261 Returns:
262 :obj:`InstanceData`
263 """
264 assert all(
265 isinstance(results, InstanceData) for results in instances_list)
266 assert len(instances_list) > 0
267 if len(instances_list) == 1:
268 return instances_list[0]
269
270 # metainfo and data_fields must be exactly the
271 # same for each element to avoid exceptions.
272 field_keys_list = [
273 instances.all_keys() for instances in instances_list
274 ]
275 assert len({len(field_keys) for field_keys in field_keys_list}) \
276 == 1 and len(set(itertools.chain(*field_keys_list))) \
277 == len(field_keys_list[0]), 'There are different keys in ' \
278 '`instances_list`, which may ' \
279 'cause the cat operation ' \
280 'to fail. Please make sure all ' \
281 'elements in `instances_list` ' \
282 'have the exact same key.'
283
284 new_data = instances_list[0].__class__(
285 metainfo=instances_list[0].metainfo)
286 for k in instances_list[0].keys():
287 values = [results[k] for results in instances_list]
288 v0 = values[0]
289 if isinstance(v0, torch.Tensor):
290 new_values = torch.cat(values, dim=0)
291 elif isinstance(v0, np.ndarray):
292 new_values = np.concatenate(values, axis=0)
293 elif isinstance(v0, (str, list, tuple)):
294 new_values = v0[:]
295 for v in values[1:]:
296 new_values += v
297 elif hasattr(v0, 'cat'):
298 new_values = v0.cat(values)
299 else:
300 raise ValueError(
301 f'The type of `{k}` is `{type(v0)}` which has no '
302 'attribute of `cat`')
303 new_data[k] = new_values
304 return new_data # type:ignore
305
306 def __len__(self) -> int:
307 """int: The length of InstanceData."""

Callers 2

__getitem__Method · 0.45
__getitem__Method · 0.45

Calls 2

all_keysMethod · 0.80
keysMethod · 0.45

Tested by

no test coverage detected