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


Python torch.as_tensor方法代码示例

本文整理汇总了Python中torch.as_tensor方法的典型用法代码示例。如果您正苦于以下问题:Python torch.as_tensor方法的具体用法?Python torch.as_tensor怎么用?Python torch.as_tensor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在torch的用法示例。


在下文中一共展示了torch.as_tensor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def __init__(self, keypoints, size, mode=None):
        # FIXME remove check once we have better integration with device
        # in my version this would consistently return a CPU tensor
        device = keypoints.device if isinstance(keypoints, torch.Tensor) else torch.device('cpu')
        keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=device)
        num_keypoints = keypoints.shape[0]
        if num_keypoints:
            keypoints = keypoints.view(num_keypoints, -1, 3)
        
        # TODO should I split them?
        # self.visibility = keypoints[..., 2]
        self.keypoints = keypoints# [..., :2]

        self.size = size
        self.mode = mode
        self.extra_fields = {} 
开发者ID:Res2Net,项目名称:Res2Net-maskrcnn,代码行数:18,代码来源:keypoint.py

示例2: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def __init__(self, bbox, image_size, mode="xyxy"):
        device = bbox.device if isinstance(bbox, torch.Tensor) else torch.device("cpu")
        bbox = torch.as_tensor(bbox, dtype=torch.float32, device=device)
        if bbox.ndimension() != 2:
            raise ValueError(
                "bbox should have 2 dimensions, got {}".format(bbox.ndimension())
            )
        if bbox.size(-1) != 4:
            raise ValueError(
                "last dimenion of bbox should have a "
                "size of 4, got {}".format(bbox.size(-1))
            )
        if mode not in ("xyxy", "xywh"):
            raise ValueError("mode should be 'xyxy' or 'xywh'")

        self.bbox = bbox
        self.size = image_size  # (image_width, image_height)
        self.mode = mode
        self.extra_fields = {} 
开发者ID:Res2Net,项目名称:Res2Net-maskrcnn,代码行数:21,代码来源:bounding_box.py

示例3: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def __init__(self, keypoints, size, mode=None):
        # FIXME remove check once we have better integration with device
        # in my version this would consistently return a CPU tensor
        device = keypoints.device if isinstance(keypoints, torch.Tensor) else torch.device('cpu')
        keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=device)
        num_keypoints = keypoints.shape[0]
        if num_keypoints:
            keypoints = keypoints.view(num_keypoints, -1, 3)

        # TODO should I split them?
        # self.visibility = keypoints[..., 2]
        self.keypoints = keypoints  # [..., :2]

        self.size = size
        self.mode = mode
        self.extra_fields = {} 
开发者ID:soeaver,项目名称:Parsing-R-CNN,代码行数:18,代码来源:keypoint.py

示例4: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def __init__(self, parsing, size, mode=None):
        if isinstance(parsing, torch.Tensor):
            # The raw data representation is passed as argument
            parsing = parsing.clone()
        elif isinstance(parsing, (list, tuple)):
            parsing = torch.as_tensor(parsing)

        if len(parsing.shape) == 2:
            # if only a single instance mask is passed
            parsing = parsing[None]

        assert len(parsing.shape) == 3
        assert parsing.shape[1] == size[1], "%s != %s" % (parsing.shape[1], size[1])
        assert parsing.shape[2] == size[0], "%s != %s" % (parsing.shape[2], size[0])

        self.parsing = parsing
        self.size = size
        self.mode = mode
        self.extra_fields = {} 
开发者ID:soeaver,项目名称:Parsing-R-CNN,代码行数:21,代码来源:parsing.py

示例5: log_prob

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def log_prob(self, inputs, context=None):
        """Calculate log probability under the distribution.

        Args:
            inputs: Tensor, input variables.
            context: Tensor or None, conditioning variables. If a Tensor, it must have the same
                number or rows as the inputs. If None, the context is ignored.

        Returns:
            A Tensor of shape [input_size], the log probability of the inputs given the context.
        """
        inputs = torch.as_tensor(inputs)
        if context is not None:
            context = torch.as_tensor(context)
            if inputs.shape[0] != context.shape[0]:
                raise ValueError('Number of input items must be equal to number of context items.')
        return self._log_prob(inputs, context) 
开发者ID:bayesiains,项目名称:nsf,代码行数:19,代码来源:base.py

示例6: test_n_additions_via_scalar_multiplication

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def test_n_additions_via_scalar_multiplication(n, a, dtype, negative, manifold, strict):
    n = torch.as_tensor(n, dtype=a.dtype).requires_grad_()
    y = torch.zeros_like(a)
    for _ in range(int(n.item())):
        y = manifold.mobius_add(a, y)
    ny = manifold.mobius_scalar_mul(n, a)
    if negative:
        tolerance = {
            torch.float32: dict(atol=4e-5, rtol=1e-3),
            torch.float64: dict(atol=1e-5, rtol=1e-3),
        }
    else:
        tolerance = {
            torch.float32: dict(atol=2e-6, rtol=1e-3),
            torch.float64: dict(atol=1e-5, rtol=1e-3),
        }
    tolerant_allclose_check(y, ny, strict=strict, **tolerance[dtype])
    ny.sum().backward()
    assert torch.isfinite(n.grad).all()
    assert torch.isfinite(a.grad).all()
    assert torch.isfinite(manifold.k.grad).all() 
开发者ID:geoopt,项目名称:geoopt,代码行数:23,代码来源:test_gyrovector_math.py

示例7: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def __init__(self, manifold: Manifold, scale=1.0, learnable=False):
        super().__init__()
        self.base = manifold
        scale = torch.as_tensor(scale, dtype=torch.get_default_dtype())
        scale = scale.requires_grad_(False)
        if not learnable:
            self.register_buffer("_scale", scale)
            self.register_buffer("_log_scale", None)
        else:
            self.register_buffer("_scale", None)
            self.register_parameter("_log_scale", torch.nn.Parameter(scale.log()))
        # do not rebuild scaled functions very frequently, save them

        for method, scaling_info in self.base.__scaling__.items():
            # register rescaled functions as bound methods of this particular instance
            unbound_method = getattr(self.base, method).__func__  # unbound method
            self.__setattr__(
                method, types.MethodType(rescale(unbound_method, scaling_info), self)
            ) 
开发者ID:geoopt,项目名称:geoopt,代码行数:21,代码来源:scaled.py

示例8: __getitem__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def __getitem__(self, idx):
        anno = self.ids[idx]
        boxes = [obj["bbox"] for obj in anno['objs'] if self.keep_difficult or not obj['isDifficult']]
        boxes = torch.as_tensor(boxes).reshape(-1, 8)
        target = QuadBoxList(boxes, [anno['width'], anno['height']], mode="xyxy")
        classes = [obj["category_id"] for obj in anno['objs']]
        classes = torch.tensor(classes)
        target.add_field("labels", classes)
        target = target.clip_to_image(remove_empty=False)

        img = Image.open(os.path.join(self.img_dir, anno['img_name'])).convert("RGB")

        if self.transforms is not None:
            img, target = self.transforms(img, target)

        return img, target, idx 
开发者ID:Xiangyu-CAS,项目名称:R2CNN.pytorch,代码行数:18,代码来源:icdar.py

示例9: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def __init__(self, quad_bbox, image_size, mode="xyxy"):
        device = quad_bbox.device if isinstance(quad_bbox, torch.Tensor) else torch.device("cpu")
        quad_bbox = torch.as_tensor(quad_bbox, dtype=torch.float32, device=device)
        if quad_bbox.ndimension() != 2:
            raise ValueError(
                "bbox should have 2 dimensions, got {}".format(quad_bbox.ndimension())
            )
        if quad_bbox.size(-1) != 8:
            raise ValueError(
                "last dimenion of bbox should have a "
                "size of 8, got {}".format(quad_bbox.size(-1))
            )
        if mode not in ("xyxy"):
            raise ValueError("mode should be 'xyxy'")
        self.device = device
        self.quad_bbox = quad_bbox
        self.bbox = self.quad_bbox_to_bbox()
        self.size = image_size  # (image_width, image_height)
        self.mode = mode
        self.extra_fields = {} 
开发者ID:Xiangyu-CAS,项目名称:R2CNN.pytorch,代码行数:22,代码来源:quad_bounding_box.py

示例10: test_batched_negative_sampling

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def test_batched_negative_sampling():
    edge_index = torch.as_tensor([[0, 0, 1, 2], [0, 1, 2, 3]])
    edge_index = torch.cat([edge_index, edge_index + 4], dim=1)
    batch = torch.tensor([0, 0, 0, 0, 1, 1, 1, 1])

    neg_edge_index = batched_negative_sampling(edge_index, batch)
    assert neg_edge_index.size(1) <= edge_index.size(1)

    adj = torch.zeros(8, 8, dtype=torch.bool)
    adj[edge_index[0], edge_index[1]] = True

    neg_adj = torch.zeros(8, 8, dtype=torch.bool)
    neg_adj[neg_edge_index[0], neg_edge_index[1]] = True
    assert (adj & neg_adj).sum() == 0
    assert neg_adj[:4, 4:].sum() == 0
    assert neg_adj[4:, :4].sum() == 0 
开发者ID:rusty1s,项目名称:pytorch_geometric,代码行数:18,代码来源:test_negative_sampling.py

示例11: load_pytorch_policy

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def load_pytorch_policy(fpath, itr, deterministic=False):
    """ Load a pytorch policy saved with Spinning Up Logger."""
    
    fname = osp.join(fpath, 'pyt_save', 'model'+itr+'.pt')
    print('\n\nLoading from %s.\n\n'%fname)

    model = torch.load(fname)

    # make function for producing an action given a single state
    def get_action(x):
        with torch.no_grad():
            x = torch.as_tensor(x, dtype=torch.float32)
            action = model.act(x)
        return action

    return get_action 
开发者ID:openai,项目名称:spinningup,代码行数:18,代码来源:test_policy.py

示例12: get_action

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def get_action(self, obs):
        """Sample action from the policy, conditioned on the task embedding.

        Args:
            obs (torch.Tensor): Observation values, with shape :math:`(1, O)`.
                O is the size of the flattened observation space.

        Returns:
            torch.Tensor: Output action value, with shape :math:`(1, A)`.
                A is the size of the flattened action space.
            dict:
                * np.ndarray[float]: Mean of the distribution.
                * np.ndarray[float]: Standard deviation of logarithmic values
                    of the distribution.

        """
        z = self.z
        obs = torch.as_tensor(obs[None], device=global_device()).float()
        obs_in = torch.cat([obs, z], dim=1)
        action, info = self._policy.get_action(obs_in)
        action = np.squeeze(action, axis=0)
        info['mean'] = np.squeeze(info['mean'], axis=0)
        return action, info 
开发者ID:rlworkgroup,项目名称:garage,代码行数:25,代码来源:context_conditioned_policy.py

示例13: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def __init__(self, bbox, image_size, mode="xyxy"):
        device = bbox.device if isinstance(bbox, torch.Tensor) else torch.device("cpu")
        bbox = torch.as_tensor(bbox, dtype=torch.float32, device=device)
        if bbox.ndimension() != 2:
            raise ValueError(
                "bbox should have 2 dimensions, got {}".format(bbox.ndimension())
            )
        if bbox.size(-1) != 4:
            raise ValueError(
                "last dimension of bbox should have a "
                "size of 4, got {}".format(bbox.size(-1))
            )
        if mode not in ("xyxy", "xywh"):
            raise ValueError("mode should be 'xyxy' or 'xywh'")

        self.bbox = bbox
        self.size = image_size  # (image_width, image_height)
        self.mode = mode
        self.extra_fields = {}
        #self.bbox_id = uuid.uuid4() 
开发者ID:simaiden,项目名称:Clothing-Detection,代码行数:22,代码来源:bounding_box.py

示例14: normalize

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def normalize(tensor, mean, std, inplace=False):
    """Normalize a tensor image with mean and standard deviation.

    .. note::
        This transform acts out of place by default, i.e., it does not mutates the input tensor.

    See :class:`~torchvision.transforms.Normalize` for more details.

    Args:
        tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channel.
        inplace(bool,optional): Bool to make this operation inplace.

    Returns:
        Tensor: Normalized Tensor image.
    """
    if not _is_tensor_image(tensor):
        raise TypeError('tensor is not a torch image.')

    if not inplace:
        tensor = tensor.clone()

    dtype = tensor.dtype
    mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device)
    std = torch.as_tensor(std, dtype=dtype, device=tensor.device)
    tensor.sub_(mean[:, None, None]).div_(std[:, None, None])
    return tensor 
开发者ID:PistonY,项目名称:torch-toolbox,代码行数:30,代码来源:functional.py

示例15: sample

# 需要导入模块: import torch [as 别名]
# 或者: from torch import as_tensor [as 别名]
def sample(self):
        idxs = np.random.randint(
            0, self.capacity if self.full else self.idx, size=self.batch_size
        )

        obses = torch.as_tensor(self.obses[idxs], device=self.device).float()
        actions = torch.as_tensor(self.actions[idxs], device=self.device)
        rewards = torch.as_tensor(self.rewards[idxs], device=self.device)
        next_obses = torch.as_tensor(
            self.next_obses[idxs], device=self.device
        ).float()
        not_dones = torch.as_tensor(self.not_dones[idxs], device=self.device)

        return obses, actions, rewards, next_obses, not_dones 
开发者ID:denisyarats,项目名称:pytorch_sac_ae,代码行数:16,代码来源:utils.py


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