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

Method __getitem__

mmengine/structures/instance_data.py:165–248  ·  view source on GitHub ↗

Args: item (str, int, list, :obj:`slice`, :obj:`numpy.ndarray`, :obj:`torch.LongTensor`, :obj:`torch.BoolTensor`): Get the corresponding values according to item. Returns: :obj:`InstanceData`: Corresponding values.

(self, item: IndexType)

Source from the content-addressed store, hash-verified

163 __setitem__ = __setattr__
164
165 def __getitem__(self, item: IndexType) -> 'InstanceData':
166 """
167 Args:
168 item (str, int, list, :obj:`slice`, :obj:`numpy.ndarray`,
169 :obj:`torch.LongTensor`, :obj:`torch.BoolTensor`):
170 Get the corresponding values according to item.
171
172 Returns:
173 :obj:`InstanceData`: Corresponding values.
174 """
175 assert isinstance(item, IndexType.__args__)
176 if isinstance(item, list):
177 item = np.array(item)
178 if isinstance(item, np.ndarray):
179 # The default int type of numpy is platform dependent, int32 for
180 # windows and int64 for linux. `torch.Tensor` requires the index
181 # should be int64, therefore we simply convert it to int64 here.
182 # More details in https://github.com/numpy/numpy/issues/9464
183 item = item.astype(np.int64) if item.dtype == np.int32 else item
184 item = torch.from_numpy(item)
185
186 if isinstance(item, str):
187 return getattr(self, item)
188
189 if isinstance(item, int):
190 if item >= len(self) or item < -len(self): # type:ignore
191 raise IndexError(f'Index {item} out of range!')
192 else:
193 # keep the dimension
194 item = slice(item, None, len(self))
195
196 new_data = self.__class__(metainfo=self.metainfo)
197 if isinstance(item, torch.Tensor):
198 assert item.dim() == 1, 'Only support to get the' \
199 ' values along the first dimension.'
200 if isinstance(item, BoolTypeTensor.__args__):
201 assert len(item) == len(self), 'The shape of the ' \
202 'input(BoolTensor) ' \
203 f'{len(item)} ' \
204 'does not match the shape ' \
205 'of the indexed tensor ' \
206 'in results_field ' \
207 f'{len(self)} at ' \
208 'first dimension.'
209
210 for k, v in self.items():
211 if isinstance(v, torch.Tensor):
212 new_data[k] = v[item]
213 elif isinstance(v, np.ndarray):
214 new_data[k] = v[item.cpu().numpy()]
215 elif isinstance(
216 v, (str, list, tuple)) or (hasattr(v, '__getitem__')
217 and hasattr(v, 'cat')):
218 # convert to indexes from BoolTensor
219 if isinstance(item, BoolTypeTensor.__args__):
220 indexes = torch.nonzero(item).view(
221 -1).cpu().numpy().tolist()
222 else:

Callers

nothing calls this directly

Calls 4

numpyMethod · 0.80
itemsMethod · 0.45
cpuMethod · 0.45
catMethod · 0.45

Tested by

no test coverage detected