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


Python torch.double方法代码示例

本文整理汇总了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 ------------------------ 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:24,代码来源:types.py

示例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 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:25,代码来源:time_sequence_prediction.py

示例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') 
开发者ID:oscarknagg,项目名称:few-shot,代码行数:22,代码来源:test_utils.py

示例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 
开发者ID:mjendrusch,项目名称:torchsupport,代码行数:22,代码来源:gan.py

示例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 
开发者ID:facebookresearch,项目名称:pyrobot,代码行数:20,代码来源:solve_for_calibration_params.py

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

示例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") 
开发者ID:diana-hep,项目名称:madminer,代码行数:22,代码来源:trainer.py

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

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

示例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) 
开发者ID:cornellius-gp,项目名称:gpytorch,代码行数:22,代码来源:test_multitask_multivariate_normal.py

示例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) 
开发者ID:cornellius-gp,项目名称:gpytorch,代码行数:22,代码来源:test_multivariate_normal.py

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

示例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]) 
开发者ID:aiqm,项目名称:torchani,代码行数:25,代码来源:test_aev.py

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

示例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]) 
开发者ID:aiqm,项目名称:torchani,代码行数:22,代码来源:test_aev.py


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