本文整理匯總了Python中torch.nonzero方法的典型用法代碼示例。如果您正苦於以下問題:Python torch.nonzero方法的具體用法?Python torch.nonzero怎麽用?Python torch.nonzero使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類torch
的用法示例。
在下文中一共展示了torch.nonzero方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: loss_shape_single
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def loss_shape_single(self, shape_pred, bbox_anchors, bbox_gts,
anchor_weights, anchor_total_num):
shape_pred = shape_pred.permute(0, 2, 3, 1).contiguous().view(-1, 2)
bbox_anchors = bbox_anchors.contiguous().view(-1, 4)
bbox_gts = bbox_gts.contiguous().view(-1, 4)
anchor_weights = anchor_weights.contiguous().view(-1, 4)
bbox_deltas = bbox_anchors.new_full(bbox_anchors.size(), 0)
bbox_deltas[:, 2:] += shape_pred
# filter out negative samples to speed-up weighted_bounded_iou_loss
inds = torch.nonzero(
anchor_weights[:, 0] > 0, as_tuple=False).squeeze(1)
bbox_deltas_ = bbox_deltas[inds]
bbox_anchors_ = bbox_anchors[inds]
bbox_gts_ = bbox_gts[inds]
anchor_weights_ = anchor_weights[inds]
pred_anchors_ = self.anchor_coder.decode(
bbox_anchors_, bbox_deltas_, wh_ratio_clip=1e-6)
loss_shape = self.loss_shape(
pred_anchors_,
bbox_gts_,
anchor_weights_,
avg_factor=anchor_total_num)
return loss_shape
示例2: sample
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def sample(self, assign_result, bboxes, gt_bboxes, **kwargs):
"""Directly returns the positive and negative indices of samples.
Args:
assign_result (:obj:`AssignResult`): Assigned results
bboxes (torch.Tensor): Bounding boxes
gt_bboxes (torch.Tensor): Ground truth boxes
Returns:
:obj:`SamplingResult`: sampler results
"""
pos_inds = torch.nonzero(
assign_result.gt_inds > 0, as_tuple=False).squeeze(-1).unique()
neg_inds = torch.nonzero(
assign_result.gt_inds == 0, as_tuple=False).squeeze(-1).unique()
gt_flags = bboxes.new_zeros(bboxes.shape[0], dtype=torch.uint8)
sampling_result = SamplingResult(pos_inds, neg_inds, bboxes, gt_bboxes,
assign_result, gt_flags)
return sampling_result
示例3: m_ggnn
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def m_ggnn(self, h_v, h_w, e_vw, opt={}):
m = Variable(torch.zeros(h_w.size(0), h_w.size(1), self.args['out']).type_as(h_w.data))
for w in range(h_w.size(1)):
if torch.nonzero(e_vw[:, w, :].data).size():
for i, el in enumerate(self.args['e_label']):
ind = (el == e_vw[:,w,:]).type_as(self.learn_args[0][i])
parameter_mat = self.learn_args[0][i][None, ...].expand(h_w.size(0), self.learn_args[0][i].size(0),
self.learn_args[0][i].size(1))
m_w = torch.transpose(torch.bmm(torch.transpose(parameter_mat, 1, 2),
torch.transpose(torch.unsqueeze(h_w[:, w, :], 1),
1, 2)), 1, 2)
m_w = torch.squeeze(m_w)
m[:,w,:] = ind.expand_as(m_w)*m_w
return m
示例4: compute_rpn_bbox_loss
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def compute_rpn_bbox_loss(rpn_target_deltas, rpn_pred_deltas, rpn_match):
"""
:param rpn_target_deltas: (b, n_positive_anchors, (dy, dx, (dz), log(dh), log(dw), (log(dd)))).
Uses 0 padding to fill in unsed bbox deltas.
:param rpn_pred_deltas: predicted deltas from RPN. (b, n_anchors, (dy, dx, (dz), log(dh), log(dw), (log(dd))))
:param rpn_match: (n_anchors). [-1, 0, 1] for negative, neutral, and positive matched anchors.
:return: loss: torch 1D tensor.
"""
if 0 not in torch.nonzero(rpn_match == 1).size():
indices = torch.nonzero(rpn_match == 1).squeeze(1)
# Pick bbox deltas that contribute to the loss
rpn_pred_deltas = rpn_pred_deltas[indices]
# Trim target bounding box deltas to the same length as rpn_bbox.
target_deltas = rpn_target_deltas[:rpn_pred_deltas.size()[0], :]
# Smooth L1 loss
loss = F.smooth_l1_loss(rpn_pred_deltas, target_deltas)
else:
loss = torch.FloatTensor([0]).cuda()
return loss
示例5: compute_mrcnn_bbox_loss
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def compute_mrcnn_bbox_loss(mrcnn_target_deltas, mrcnn_pred_deltas, target_class_ids):
"""
:param mrcnn_target_deltas: (n_sampled_rois, (dy, dx, (dz), log(dh), log(dw), (log(dh)))
:param mrcnn_pred_deltas: (n_sampled_rois, n_classes, (dy, dx, (dz), log(dh), log(dw), (log(dh)))
:param target_class_ids: (n_sampled_rois)
:return: loss: torch 1D tensor.
"""
if 0 not in torch.nonzero(target_class_ids > 0).size():
positive_roi_ix = torch.nonzero(target_class_ids > 0)[:, 0]
positive_roi_class_ids = target_class_ids[positive_roi_ix].long()
target_bbox = mrcnn_target_deltas[positive_roi_ix, :].detach()
pred_bbox = mrcnn_pred_deltas[positive_roi_ix, positive_roi_class_ids, :]
loss = F.smooth_l1_loss(pred_bbox, target_bbox)
else:
loss = torch.FloatTensor([0]).cuda()
return loss
示例6: __call__
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def __call__(self, proposals, keypoint_logits):
heatmaps = []
valid = []
for proposals_per_image in proposals:
kp = proposals_per_image.get_field("keypoints")
heatmaps_per_image, valid_per_image = project_keypoints_to_heatmap(
kp, proposals_per_image, self.discretization_size
)
heatmaps.append(heatmaps_per_image.view(-1))
valid.append(valid_per_image.view(-1))
keypoint_targets = cat(heatmaps, dim=0)
valid = cat(valid, dim=0).to(dtype=torch.uint8)
valid = torch.nonzero(valid).squeeze(1)
# torch.mean (in binary_cross_entropy_with_logits) does'nt
# accept empty tensors, so handle it sepaartely
if keypoint_targets.numel() == 0 or len(valid) == 0:
return keypoint_logits.sum() * 0
N, K, H, W = keypoint_logits.shape
keypoint_logits = keypoint_logits.view(N * K, H * W)
keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid])
return keypoint_loss
示例7: select_top_predictions
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def select_top_predictions(self, predictions):
"""
Select only predictions which have a `score` > self.confidence_threshold,
and returns the predictions in descending order of score
Arguments:
predictions (BoxList): the result of the computation by the model.
It should contain the field `scores`.
Returns:
prediction (BoxList): the detected objects. Additional information
of the detection properties can be found in the fields of
the BoxList via `prediction.fields()`
"""
scores = predictions.get_field("scores")
keep = torch.nonzero(scores > self.confidence_threshold).squeeze(1)
predictions = predictions[keep]
scores = predictions.get_field("scores")
_, idx = scores.sort(0, descending=True)
return predictions[idx]
示例8: loss_shape_single
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def loss_shape_single(self, shape_pred, bbox_anchors, bbox_gts,
anchor_weights, anchor_total_num):
shape_pred = shape_pred.permute(0, 2, 3, 1).contiguous().view(-1, 2)
bbox_anchors = bbox_anchors.contiguous().view(-1, 4)
bbox_gts = bbox_gts.contiguous().view(-1, 4)
anchor_weights = anchor_weights.contiguous().view(-1, 4)
bbox_deltas = bbox_anchors.new_full(bbox_anchors.size(), 0)
bbox_deltas[:, 2:] += shape_pred
# filter out negative samples to speed-up weighted_bounded_iou_loss
inds = torch.nonzero(anchor_weights[:, 0] > 0).squeeze(1)
bbox_deltas_ = bbox_deltas[inds]
bbox_anchors_ = bbox_anchors[inds]
bbox_gts_ = bbox_gts[inds]
anchor_weights_ = anchor_weights[inds]
pred_anchors_ = delta2bbox(bbox_anchors_,
bbox_deltas_,
self.anchoring_means,
self.anchoring_stds,
wh_ratio_clip=1e-6)
loss_shape = self.loss_shape(pred_anchors_,
bbox_gts_,
anchor_weights_,
avg_factor=anchor_total_num)
return loss_shape
示例9: weighted_iou_loss
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def weighted_iou_loss(pred,
target,
weight,
style='naive',
beta=0.2,
eps=1e-3,
avg_factor=None):
if style not in ['bounded', 'naive']:
raise ValueError('Only support bounded iou loss and naive iou loss.')
inds = torch.nonzero(weight[:, 0] > 0)
if avg_factor is None:
avg_factor = inds.numel() + 1e-6
if inds.numel() > 0:
inds = inds.squeeze(1)
else:
return (pred * weight).sum()[None] / avg_factor
if style == 'bounded':
loss = bounded_iou_loss(
pred[inds], target[inds], beta=beta, eps=eps, reduction='sum')
else:
loss = iou_loss(pred[inds], target[inds], reduction='sum')
loss = loss[None] / avg_factor
return loss
示例10: _subsample
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def _subsample(self, pos_idx, neg_idx):
num_pos = int(self.num_samples * self.pos_ratio)
pos_idx = torch.nonzero(pos_idx).view(-1)
if pos_idx.numel() > 0:
rand_selection = np.random.permutation(pos_idx.numel()).astype(np.int64)
rand_selection = torch.from_numpy(rand_selection).to(pos_idx.device)
num_pos = min(num_pos, pos_idx.numel())
pos_idx = pos_idx[rand_selection[:num_pos]]
else:
num_pos = 0
pos_idx = torch.tensor((), dtype=torch.long, device=pos_idx.device)
num_neg = self.num_samples - num_pos
neg_idx = torch.nonzero(neg_idx).view(-1)
if neg_idx.numel() > 0:
rand_selection = np.random.permutation(neg_idx.numel()).astype(np.int64)
rand_selection = torch.from_numpy(rand_selection).to(neg_idx.device)
num_neg = min(num_neg, neg_idx.numel())
neg_idx = neg_idx[rand_selection[:num_neg]]
else:
neg_idx = torch.tensor((), dtype=torch.long, device=neg_idx.device)
return pos_idx, neg_idx
示例11: _prepare_inputs
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def _prepare_inputs(self, msk, cat, iscrowd, bbx):
cat_out, iscrowd_out, bbx_out, ids_out = [], [], [], []
for msk_i, cat_i, iscrowd_i, bbx_i in zip(msk, cat, iscrowd, bbx):
thing = (cat_i >= self.num_stuff) & (cat_i != 255)
valid = thing & ~iscrowd_i
if valid.any().item():
cat_out.append(cat_i[valid])
bbx_out.append(bbx_i[valid])
ids_out.append(torch.nonzero(valid))
else:
cat_out.append(None)
bbx_out.append(None)
ids_out.append(None)
if iscrowd_i.any().item():
iscrowd_i = iscrowd_i & thing
iscrowd_out.append(iscrowd_i[msk_i].any(dim=0))
else:
iscrowd_out.append(None)
return cat_out, iscrowd_out, bbx_out, ids_out
示例12: _prepare_inputs
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def _prepare_inputs(self, msk, cat, iscrowd, bbx):
cat_out, iscrowd_out, bbx_out, ids_out, sem_out = [], [], [], [], []
for msk_i, cat_i, iscrowd_i, bbx_i in zip(msk, cat, iscrowd, bbx):
msk_i = msk_i.squeeze(0)
thing = (cat_i >= self.num_stuff) & (cat_i != 255)
valid = thing & ~iscrowd_i
if valid.any().item():
cat_out.append(cat_i[valid])
bbx_out.append(bbx_i[valid])
ids_out.append(torch.nonzero(valid))
else:
cat_out.append(None)
bbx_out.append(None)
ids_out.append(None)
if iscrowd_i.any().item():
iscrowd_i = iscrowd_i & thing
iscrowd_out.append(iscrowd_i[msk_i])
else:
iscrowd_out.append(None)
sem_out.append(cat_i[msk_i])
return cat_out, iscrowd_out, bbx_out, ids_out, sem_out
示例13: _compute_loss
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def _compute_loss(self, batch, output, target):
scores = self.generator(self._bottle(output))
gtruth = target.view(-1)
if self.confidence < 1:
tdata = gtruth.data
mask = torch.nonzero(tdata.eq(self.padding_idx)).squeeze()
log_likelihood = torch.gather(scores.data, 1, tdata.unsqueeze(1))
tmp_ = self.one_hot.repeat(gtruth.size(0), 1)
tmp_.scatter_(1, tdata.unsqueeze(1), self.confidence)
if mask.dim() > 0:
log_likelihood.index_fill_(0, mask, 0)
tmp_.index_fill_(0, mask, 0)
gtruth = Variable(tmp_, requires_grad=False)
loss = self.criterion(scores, gtruth)
if self.confidence < 1:
# Default: report smoothed ppl.
# loss_data = -log_likelihood.sum(0)
loss_data = loss.data.clone()
else:
loss_data = loss.data.clone()
stats = self._stats(loss_data, scores.data, target.view(-1).data)
return loss, stats
示例14: forward
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def forward(self, x, target):
assert x.size(1) == self.size
true_dist = x.data.clone()
true_dist.fill_(self.smoothing / (self.size - 2))
true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)
true_dist[:, self.padding_idx] = 0
mask = torch.nonzero(target.data == self.padding_idx)
if mask.dim() > 0:
true_dist.index_fill_(0, mask.squeeze(), 0.0)
self.true_dist = true_dist
return self.criterion(x, Variable(true_dist, requires_grad=False))
示例15: _expand_binary_labels
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import nonzero [as 別名]
def _expand_binary_labels(labels, label_weights, label_channels):
# Caution: this function should only be used in RPN
# in other files such as in ghm_loss, the _expand_binary_labels
# is used for multi-class classification.
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero(labels >= 1, as_tuple=False).squeeze()
if inds.numel() > 0:
bin_labels[inds, labels[inds] - 1] = 1
if label_weights is None:
bin_label_weights = None
else:
bin_label_weights = label_weights.view(-1, 1).expand(
label_weights.size(0), label_channels)
return bin_labels, bin_label_weights