本文整理匯總了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 = {}
示例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 = {}
示例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 = {}
示例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 = {}
示例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)
示例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()
示例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)
)
示例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
示例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 = {}
示例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
示例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
示例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
示例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()
示例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
示例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