当前位置: 首页>>代码示例>>Python>>正文


Python torch.empty方法代码示例

本文整理汇总了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 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:18,代码来源:structures.py

示例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) 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:20,代码来源:structures.py

示例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 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:24,代码来源:test_assigner.py

示例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 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:19,代码来源:test_assigner.py

示例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) 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:26,代码来源:test_sampler.py

示例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 
开发者ID:potterhsu,项目名称:easy-faster-rcnn.pytorch,代码行数:23,代码来源:region_proposal_network.py

示例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) 
开发者ID:pytorch,项目名称:audio,代码行数:19,代码来源:transforms.py

示例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) 
开发者ID:pytorch,项目名称:audio,代码行数:21,代码来源:test_compliance_kaldi.py

示例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) 
开发者ID:tingiskhan,项目名称:pyfilter,代码行数:19,代码来源:resampling.py

示例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)) 
开发者ID:tingiskhan,项目名称:pyfilter,代码行数:23,代码来源:utils.py

示例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) 
开发者ID:akanimax,项目名称:BMSG-GAN,代码行数:23,代码来源:CustomLayers.py

示例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) 
开发者ID:soeaver,项目名称:Parsing-R-CNN,代码行数:20,代码来源:parsing.py

示例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) 
开发者ID:soeaver,项目名称:Parsing-R-CNN,代码行数:18,代码来源:loss.py

示例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) 
开发者ID:bayesiains,项目名称:nsf,代码行数:21,代码来源:linear.py

示例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]] 
开发者ID:rusty1s,项目名称:pytorch_geometric,代码行数:18,代码来源:test_inits.py


注:本文中的torch.empty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。