本文整理匯總了Python中torch.double方法的典型用法代碼示例。如果您正苦於以下問題:Python torch.double方法的具體用法?Python torch.double怎麽用?Python torch.double使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類torch
的用法示例。
在下文中一共展示了torch.double方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: torch_dtype_to_np_dtype
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def torch_dtype_to_np_dtype(dtype):
dtype_dict = {
torch.bool : np.dtype(np.bool),
torch.uint8 : np.dtype(np.uint8),
torch.int8 : np.dtype(np.int8),
torch.int16 : np.dtype(np.int16),
torch.short : np.dtype(np.int16),
torch.int32 : np.dtype(np.int32),
torch.int : np.dtype(np.int32),
torch.int64 : np.dtype(np.int64),
torch.long : np.dtype(np.int64),
torch.float16 : np.dtype(np.float16),
torch.half : np.dtype(np.float16),
torch.float32 : np.dtype(np.float32),
torch.float : np.dtype(np.float32),
torch.float64 : np.dtype(np.float64),
torch.double : np.dtype(np.float64),
}
return dtype_dict[dtype]
# ---------------------- InferenceEngine internal types ------------------------
示例2: forward
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def forward(self, input, future):
outputs = []
h_t = torch.zeros(input.size(0), 51, dtype=torch.double)
c_t = torch.zeros(input.size(0), 51, dtype=torch.double)
h_t2 = torch.zeros(input.size(0), 51, dtype=torch.double)
c_t2 = torch.zeros(input.size(0), 51, dtype=torch.double)
for i, input_t in enumerate(input.chunk(input.size(1), dim=1)):
h_t, c_t = self.lstm1(input_t, (h_t, c_t))
h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2))
output = self.linear(h_t2)
outputs += [output]
for i in range(future):# if we should predict the future
h_t, c_t = self.lstm1(output, (h_t, c_t))
h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2))
output = self.linear(h_t2)
outputs += [output]
# EDIT(momohatt): Add 'dim='
outputs = torch.stack(outputs, dim=1).squeeze(dim=2)
return outputs
# Example input
示例3: test_no_nans_on_zero_vectors
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def test_no_nans_on_zero_vectors(self):
"""Cosine distance calculation involves a divide-through by vector magnitude which
can divide by zeros to occur.
"""
# Create some dummy data with easily verifiable distances
q = 1 # 1 query per class
k = 3 # 3 way classification
d = 2 # embedding dimension of two
query = torch.zeros([q * k, d], dtype=torch.double)
query[0] = torch.Tensor([0, 0]) # First query sample is all zeros
query[1] = torch.Tensor([0, 1])
query[2] = torch.Tensor([1, 1])
support = torch.zeros([k, d], dtype=torch.double)
support[0] = torch.Tensor([1, 1])
support[1] = torch.Tensor([-1, -1])
support[2] = torch.Tensor([0, 0]) # Third support sample is all zeros
distances = pairwise_distances(query, support, 'cosine')
self.assertTrue(torch.isnan(distances).sum() == 0, 'Cosine distances between 0-vectors should not be nan')
示例4: _mix_on_path
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def _mix_on_path(real, fake):
result = None
if isinstance(real, (list, tuple)):
result = [
_mix_on_path(real_part, fake_part)
for real_part, fake_part in zip(real, fake)
]
elif isinstance(real, dict):
result = {
key: _mix_on_path(real[key], fake[key])
for key in real
}
elif isinstance(real, torch.Tensor):
if real.dtype in (torch.half, torch.float, torch.double):
result = _mix_on_path_aux(real, fake)
else:
result = random.choice([real, fake])
else:
result = random.choice([real, fake])
return result
示例5: get_transforms_to_optimize
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def get_transforms_to_optimize(chain, to_optimize_quat, to_optimize_trans, device):
"""Returns pytorch tensors to optimize along the chain as per
to_optimize_trans and to_optimize_quat."""
opt_pyt_trans, opt_pyt_quat = [], []
for i in range(len(chain) - 1):
t = None
q = None
if chain[i + 1] in to_optimize_trans:
t = torch.zeros(1, 3, device=device, dtype=torch.double, requires_grad=True)
if chain[i + 1] in to_optimize_quat:
qxyz = torch.zeros(
1, 3, device=device, dtype=torch.double, requires_grad=True
)
qw = torch.ones(1, 1, device=device, dtype=torch.double, requires_grad=True)
q = [qw, qxyz]
opt_pyt_trans.append(t)
opt_pyt_quat.append(q)
return opt_pyt_quat, opt_pyt_trans
示例6: reprojection_error
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def reprojection_error(
t_pts_2d, pts_2d_observed, min_inlier_fraction, inlier_pixel_threshold, mask=None
):
"""Computes re-projection error for observed and projected points."""
n_pts = t_pts_2d.shape[0]
err_all = t_pts_2d - pts_2d_observed
err_all = err_all ** 2
err_all = err_all.sum(2)
topk_k = int(4 * n_pts * min_inlier_fraction)
topk, _ = torch.topk(err_all.view(-1), k=topk_k, largest=False)
in_px_thresh_pyt = torch.from_numpy(np.array([inlier_pixel_threshold ** 2]))
in_px_thresh_pyt = in_px_thresh_pyt.double()
topk = torch.max(topk[-1], in_px_thresh_pyt)
err_all_robust = torch.min(topk, err_all)
if mask is not None:
err_all_robust = err_all_robust * mask
err = err_all_robust.sum() / mask.sum()
else:
err = err_all_robust.mean()
err_all = torch.sqrt(err_all)
return err, err_all, topk
示例7: __init__
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def __init__(self, model, run_on_gpu=True, double_precision=False, n_workers=8):
self._init_timer()
self._timer(start="ALL")
self._timer(start="initialize model")
self.model = model
self.run_on_gpu = run_on_gpu and torch.cuda.is_available()
self.device = torch.device("cuda" if self.run_on_gpu else "cpu")
self.dtype = torch.double if double_precision else torch.float
self.n_workers = n_workers
self.model = self.model.to(self.device, self.dtype)
logger.info(
"Training on %s with %s precision",
"GPU" if self.run_on_gpu else "CPU",
"double" if double_precision else "single",
)
self._timer(stop="initialize model")
self._timer(stop="ALL")
示例8: forward
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def forward(self, input, future = 0):
outputs = []
h_t = torch.zeros(input.size(0), 51, dtype=torch.double)
c_t = torch.zeros(input.size(0), 51, dtype=torch.double)
h_t2 = torch.zeros(input.size(0), 51, dtype=torch.double)
c_t2 = torch.zeros(input.size(0), 51, dtype=torch.double)
for i, input_t in enumerate(input.chunk(input.size(1), dim=1)):
h_t, c_t = self.lstm1(input_t, (h_t, c_t))
h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2))
output = self.linear(h_t2)
outputs += [output]
for i in range(future):# if we should predict the future
h_t, c_t = self.lstm1(output, (h_t, c_t))
h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2))
output = self.linear(h_t2)
outputs += [output]
outputs = torch.stack(outputs, 1).squeeze(2)
return outputs
示例9: test_replay_myattr
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def test_replay_myattr(self):
standard_replay = self.replay
vector = np.random.rand(VECTOR_SIZE)
# a random tensor to be stuffed in
test_tensor = th.randn(3, 3, dtype=th.double)
# initialization, stuff just tensors in
# and the results type should still be tensor
for i in range(NUM_SAMPLES):
standard_replay.append(vector,
vector,
i,
vector,
False,
test=test_tensor)
self.assertTrue(isinstance(standard_replay.test(), th.Tensor))
示例10: test_log_prob
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def test_log_prob(self, cuda=False):
device = torch.device("cuda") if cuda else torch.device("cpu")
for dtype in (torch.float, torch.double):
mean = torch.randn(4, 3, device=device, dtype=dtype)
var = torch.randn(12, device=device, dtype=dtype).abs_()
values = mean + 0.5
diffs = (values - mean).view(-1)
res = MultitaskMultivariateNormal(mean, DiagLazyTensor(var)).log_prob(values)
actual = -0.5 * (math.log(math.pi * 2) * 12 + var.log().sum() + (diffs / var * diffs).sum())
self.assertLess((res - actual).div(res).abs().item(), 1e-2)
mean = torch.randn(3, 4, 3, device=device, dtype=dtype)
var = torch.randn(3, 12, device=device, dtype=dtype).abs_()
values = mean + 0.5
diffs = (values - mean).view(3, -1)
res = MultitaskMultivariateNormal(mean, DiagLazyTensor(var)).log_prob(values)
actual = -0.5 * (math.log(math.pi * 2) * 12 + var.log().sum(-1) + (diffs / var * diffs).sum(-1))
self.assertLess((res - actual).div(res).abs().norm(), 1e-2)
示例11: test_log_prob
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def test_log_prob(self, cuda=False):
device = torch.device("cuda") if cuda else torch.device("cpu")
for dtype in (torch.float, torch.double):
mean = torch.randn(4, device=device, dtype=dtype)
var = torch.randn(4, device=device, dtype=dtype).abs_()
values = torch.randn(4, device=device, dtype=dtype)
res = MultivariateNormal(mean, DiagLazyTensor(var)).log_prob(values)
actual = TMultivariateNormal(mean, torch.eye(4, device=device, dtype=dtype) * var).log_prob(values)
self.assertLess((res - actual).div(res).abs().item(), 1e-2)
mean = torch.randn(3, 4, device=device, dtype=dtype)
var = torch.randn(3, 4, device=device, dtype=dtype).abs_()
values = torch.randn(3, 4, device=device, dtype=dtype)
res = MultivariateNormal(mean, DiagLazyTensor(var)).log_prob(values)
actual = TMultivariateNormal(
mean, var.unsqueeze(-1) * torch.eye(4, device=device, dtype=dtype).repeat(3, 1, 1)
).log_prob(values)
self.assertLess((res - actual).div(res).abs().norm(), 1e-2)
示例12: double
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def double(self, device_id=None):
"""
This method operates identically to :func:`torch.Tensor.double`.
"""
new_args = []
new_kwargs = {}
for arg in self._args:
if hasattr(arg, "double"):
new_args.append(arg.double())
else:
new_args.append(arg)
for name, val in self._kwargs.items():
if hasattr(val, "double"):
new_kwargs[name] = val.double()
else:
new_kwargs[name] = val
return self.__class__(*new_args, **new_kwargs)
示例13: testPBCConnersSeeEachOther
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def testPBCConnersSeeEachOther(self):
species = torch.tensor([[0, 0]])
cell = torch.eye(3, dtype=torch.double) * 10
pbc = torch.ones(3, dtype=torch.bool)
allshifts = torchani.aev.compute_shifts(cell, pbc, 1)
xyz1 = torch.tensor([0.1, 0.1, 0.1])
xyz2s = [
torch.tensor([9.9, 0.0, 0.0]),
torch.tensor([0.0, 9.9, 0.0]),
torch.tensor([0.0, 0.0, 9.9]),
torch.tensor([9.9, 9.9, 0.0]),
torch.tensor([0.0, 9.9, 9.9]),
torch.tensor([9.9, 0.0, 9.9]),
torch.tensor([9.9, 9.9, 9.9]),
]
for xyz2 in xyz2s:
coordinates = torch.stack([xyz1, xyz2]).to(torch.double).unsqueeze(0)
atom_index12, _ = torchani.aev.neighbor_pairs(species == -1, coordinates, cell, allshifts, 1)
atom_index1, atom_index2 = atom_index12.unbind(0)
self.assertEqual(atom_index1.tolist(), [0])
self.assertEqual(atom_index2.tolist(), [1])
示例14: testPBCSurfaceSeeEachOther
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def testPBCSurfaceSeeEachOther(self):
cell = torch.eye(3, dtype=torch.double) * 10
pbc = torch.ones(3, dtype=torch.bool)
allshifts = torchani.aev.compute_shifts(cell, pbc, 1)
species = torch.tensor([[0, 0]])
for i in range(3):
xyz1 = torch.tensor([5.0, 5.0, 5.0], dtype=torch.double)
xyz1[i] = 0.1
xyz2 = xyz1.clone()
xyz2[i] = 9.9
coordinates = torch.stack([xyz1, xyz2]).unsqueeze(0)
atom_index12, _ = torchani.aev.neighbor_pairs(species == -1, coordinates, cell, allshifts, 1)
atom_index1, atom_index2 = atom_index12.unbind(0)
self.assertEqual(atom_index1.tolist(), [0])
self.assertEqual(atom_index2.tolist(), [1])
示例15: testPBCEdgesSeeEachOther
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import double [as 別名]
def testPBCEdgesSeeEachOther(self):
cell = torch.eye(3, dtype=torch.double) * 10
pbc = torch.ones(3, dtype=torch.bool)
allshifts = torchani.aev.compute_shifts(cell, pbc, 1)
species = torch.tensor([[0, 0]])
for i, j in itertools.combinations(range(3), 2):
xyz1 = torch.tensor([5.0, 5.0, 5.0], dtype=torch.double)
xyz1[i] = 0.1
xyz1[j] = 0.1
for new_i, new_j in [[0.1, 9.9], [9.9, 0.1], [9.9, 9.9]]:
xyz2 = xyz1.clone()
xyz2[i] = new_i
xyz2[j] = new_j
coordinates = torch.stack([xyz1, xyz2]).unsqueeze(0)
atom_index12, _ = torchani.aev.neighbor_pairs(species == -1, coordinates, cell, allshifts, 1)
atom_index1, atom_index2 = atom_index12.unbind(0)
self.assertEqual(atom_index1.tolist(), [0])
self.assertEqual(atom_index2.tolist(), [1])