本文整理匯總了Python中torch.empty方法的典型用法代碼示例。如果您正苦於以下問題:Python torch.empty方法的具體用法?Python torch.empty怎麽用?Python torch.empty使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類torch
的用法示例。
在下文中一共展示了torch.empty方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def __init__(self, masks, height, width):
self.height = height
self.width = width
if len(masks) == 0:
self.masks = np.empty((0, self.height, self.width), dtype=np.uint8)
else:
assert isinstance(masks, (list, np.ndarray))
if isinstance(masks, list):
assert isinstance(masks[0], np.ndarray)
assert masks[0].ndim == 2 # (H, W)
else:
assert masks.ndim == 3 # (N, H, W)
self.masks = np.stack(masks).reshape(-1, height, width)
assert self.masks.shape[1] == self.height
assert self.masks.shape[2] == self.width
示例2: crop
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def crop(self, bbox):
"""See :func:`BaseInstanceMasks.crop`."""
assert isinstance(bbox, np.ndarray)
assert bbox.ndim == 1
# clip the boundary
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
x1, y1, x2, y2 = bbox
w = np.maximum(x2 - x1, 1)
h = np.maximum(y2 - y1, 1)
if len(self.masks) == 0:
cropped_masks = np.empty((0, h, w), dtype=np.uint8)
else:
cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w]
return BitmapMasks(cropped_masks, h, w)
示例3: test_max_iou_assigner_with_empty_boxes
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def test_max_iou_assigner_with_empty_boxes():
"""Test corner case where an network might predict no boxes."""
self = MaxIoUAssigner(
pos_iou_thr=0.5,
neg_iou_thr=0.5,
)
bboxes = torch.empty((0, 4))
gt_bboxes = torch.FloatTensor([
[0, 0, 10, 9],
[0, 10, 10, 19],
])
gt_labels = torch.LongTensor([2, 3])
# Test with gt_labels
assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels)
assert len(assign_result.gt_inds) == 0
assert tuple(assign_result.labels.shape) == (0, )
# Test without gt_labels
assign_result = self.assign(bboxes, gt_bboxes, gt_labels=None)
assert len(assign_result.gt_inds) == 0
assert assign_result.labels is None
示例4: test_approx_iou_assigner_with_empty_boxes
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def test_approx_iou_assigner_with_empty_boxes():
"""Test corner case where an network might predict no boxes."""
self = ApproxMaxIoUAssigner(
pos_iou_thr=0.5,
neg_iou_thr=0.5,
)
bboxes = torch.empty((0, 4))
gt_bboxes = torch.FloatTensor([
[0, 0, 10, 9],
[0, 10, 10, 19],
])
approxs_per_octave = 1
approxs = bboxes
squares = bboxes
assign_result = self.assign(approxs, squares, approxs_per_octave,
gt_bboxes)
assert len(assign_result.gt_inds) == 0
示例5: test_random_sampler_empty_gt
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def test_random_sampler_empty_gt():
assigner = MaxIoUAssigner(
pos_iou_thr=0.5,
neg_iou_thr=0.5,
ignore_iof_thr=0.5,
ignore_wrt_candidates=False,
)
bboxes = torch.FloatTensor([
[0, 0, 10, 10],
[10, 10, 20, 20],
[5, 5, 15, 15],
[32, 32, 38, 42],
])
gt_bboxes = torch.empty(0, 4)
gt_labels = torch.empty(0, ).long()
assign_result = assigner.assign(bboxes, gt_bboxes, gt_labels=gt_labels)
sampler = RandomSampler(
num=10, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=True)
sample_result = sampler.sample(assign_result, bboxes, gt_bboxes, gt_labels)
assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds)
assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds)
示例6: loss
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def loss(self, anchor_objectnesses: Tensor, anchor_transformers: Tensor,
gt_anchor_objectnesses: Tensor, gt_anchor_transformers: Tensor,
batch_size: int, batch_indices: Tensor) -> Tuple[Tensor, Tensor]:
cross_entropies = torch.empty(batch_size, dtype=torch.float, device=anchor_objectnesses.device)
smooth_l1_losses = torch.empty(batch_size, dtype=torch.float, device=anchor_transformers.device)
for batch_index in range(batch_size):
selected_indices = (batch_indices == batch_index).nonzero().view(-1)
cross_entropy = F.cross_entropy(input=anchor_objectnesses[selected_indices],
target=gt_anchor_objectnesses[selected_indices])
fg_indices = gt_anchor_objectnesses[selected_indices].nonzero().view(-1)
smooth_l1_loss = beta_smooth_l1_loss(input=anchor_transformers[selected_indices][fg_indices],
target=gt_anchor_transformers[selected_indices][fg_indices],
beta=self._anchor_smooth_l1_loss_beta)
cross_entropies[batch_index] = cross_entropy
smooth_l1_losses[batch_index] = smooth_l1_loss
return cross_entropies, smooth_l1_losses
示例7: __init__
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def __init__(self,
n_mels: int = 128,
sample_rate: int = 16000,
f_min: float = 0.,
f_max: Optional[float] = None,
n_stft: Optional[int] = None) -> None:
super(MelScale, self).__init__()
self.n_mels = n_mels
self.sample_rate = sample_rate
self.f_max = f_max if f_max is not None else float(sample_rate // 2)
self.f_min = f_min
assert f_min <= self.f_max, 'Require f_min: %f < f_max: %f' % (f_min, self.f_max)
fb = torch.empty(0) if n_stft is None else F.create_fb_matrix(
n_stft, self.f_min, self.f_max, self.n_mels, self.sample_rate)
self.register_buffer('fb', fb)
示例8: _test_get_strided_helper
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def _test_get_strided_helper(self, num_samples, window_size, window_shift, snip_edges):
waveform = torch.arange(num_samples).float()
output = kaldi._get_strided(waveform, window_size, window_shift, snip_edges)
# from NumFrames in feature-window.cc
n = window_size
if snip_edges:
m = 0 if num_samples < window_size else 1 + (num_samples - window_size) // window_shift
else:
m = (num_samples + (window_shift // 2)) // window_shift
self.assertTrue(output.dim() == 2)
self.assertTrue(output.shape[0] == m and output.shape[1] == n)
window = torch.empty((m, window_size))
for r in range(m):
extract_window(window, waveform, r, window_size, window_shift, snip_edges)
torch.testing.assert_allclose(window, output)
示例9: systematic
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def systematic(w: torch.Tensor, normalized=False, u: Union[torch.Tensor, float] = None):
"""
Performs systematic resampling on either a 1D or 2D array.
:param w: The weights to use for resampling
:param normalized: Whether the data is normalized
:param u: Parameter for overriding the sampled index, for testing
:return: Resampled indices
"""
shape = (1,) if w.dim() < 2 else (w.shape[0], 1)
u = u if u is not None else (torch.empty(shape, device=w.device)).uniform_()
w = normalize(w) if not normalized else w
if w.dim() > 1:
return _matrix(w, u)
return _vector(w, u)
示例10: test_HelperMixin
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def test_HelperMixin(self):
obj = Help(torch.empty(3000).normal_())
# ===== Verify that we don't break views when changing device ===== #
obj.to_('cpu:0')
temp = obj._params[0]
temp += 1
for p, v in zip(obj._params, obj._views):
assert (p == v).all() and v._base is p
# ===== Check state dict ===== #
sd = obj.state_dict()
newobj = Help(torch.empty(1))
newobj.load_state_dict(sd)
assert all((p1 == p2).all() for p1, p2 in zip(newobj._params, obj._params))
assert all((p1 == p2).all() for p1, p2 in zip(newobj._views, newobj._params))
assert all(p1._base is p2 for p1, p2 in zip(newobj._views, newobj._params))
示例11: __init__
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def __init__(self, c_in, c_out, k_size, stride=1, pad=0, bias=True):
""" constructor for the class """
from torch.nn.modules.utils import _pair
from numpy import sqrt, prod
super().__init__()
# define the weight and bias if to be used
self.weight = th.nn.Parameter(th.nn.init.normal_(
th.empty(c_out, c_in, *_pair(k_size))
))
self.use_bias = bias
self.stride = stride
self.pad = pad
if self.use_bias:
self.bias = th.nn.Parameter(th.FloatTensor(c_out).fill_(0))
fan_in = prod(_pair(k_size)) * c_in # value of fan_in
self.scale = sqrt(2) / sqrt(fan_in)
示例12: parsing_on_boxes
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def parsing_on_boxes(parsing, rois, heatmap_size):
device = rois.device
rois = rois.to(torch.device("cpu"))
parsing_list = []
for i in range(rois.shape[0]):
parsing_ins = parsing[i].cpu().numpy()
xmin, ymin, xmax, ymax = torch.round(rois[i]).int()
cropped_parsing = parsing_ins[ymin:ymax, xmin:xmax]
resized_parsing = cv2.resize(
cropped_parsing,
(heatmap_size[1], heatmap_size[0]),
interpolation=cv2.INTER_NEAREST
)
parsing_list.append(torch.from_numpy(resized_parsing))
if len(parsing_list) == 0:
return torch.empty(0, dtype=torch.int64, device=device)
return torch.stack(parsing_list, dim=0).to(device, dtype=torch.int64)
示例13: parsing_on_boxes
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def parsing_on_boxes(parsing, rois, heatmap_size):
device = rois.device
rois = rois.to(torch.device("cpu"))
parsing_list = []
for i in range(rois.shape[0]):
parsing_ins = parsing[i].cpu().numpy()
xmin, ymin, xmax, ymax = torch.round(rois[i]).int()
cropped_parsing = parsing_ins[max(0, ymin):ymax, max(0, xmin):xmax]
resized_parsing = cv2.resize(
cropped_parsing, (heatmap_size[1], heatmap_size[0]), interpolation=cv2.INTER_NEAREST
)
parsing_list.append(torch.from_numpy(resized_parsing))
if len(parsing_list) == 0:
return torch.empty(0, dtype=torch.int64, device=device)
return torch.stack(parsing_list, dim=0).to(device, dtype=torch.int64)
示例14: __init__
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def __init__(self, features, orthogonal_initialization=True, using_cache=False):
"""Constructor.
Args:
features: int, number of input features.
orthogonal_initialization: bool, if True initialize weights to be a random
orthogonal matrix.
Raises:
TypeError: if `features` is not a positive integer.
"""
super().__init__(features, using_cache)
if orthogonal_initialization:
self._weight = nn.Parameter(utils.random_orthogonal(features))
else:
self._weight = nn.Parameter(torch.empty(features, features))
stdv = 1.0 / np.sqrt(features)
init.uniform_(self._weight, -stdv, stdv)
示例15: test_inits
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import empty [as 別名]
def test_inits():
x = torch.empty(1, 4)
uniform(size=4, tensor=x)
assert x.min() >= -0.5
assert x.max() <= 0.5
glorot(x)
assert x.min() >= -1.25
assert x.max() <= 1.25
zeros(x)
assert x.tolist() == [[0, 0, 0, 0]]
ones(x)
assert x.tolist() == [[1, 1, 1, 1]]