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


Python torch.eye方法代码示例

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


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

示例1: construct_diag

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def construct_diag(x: torch.Tensor):
    """
    Constructs a diagonal matrix based on batched data. Solution found here:
    https://stackoverflow.com/questions/47372508/how-to-construct-a-3d-tensor-where-every-2d-sub-tensor-is-a-diagonal-matrix-in-p
    Do note that it only considers the last axis.
    :param x: The tensor
    """

    if x.dim() < 1:
        return x
    elif x.shape[-1] < 2:
        return x.unsqueeze(-1)
    elif x.dim() < 2:
        return torch.diag(x)

    b = torch.eye(x.size(-1), device=x.device)
    c = x.unsqueeze(-1).expand(*x.size(), x.size(-1))

    return c * b 
开发者ID:tingiskhan,项目名称:pyfilter,代码行数:21,代码来源:utils.py

示例2: exp

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def exp(x):
    x_ = x.view(-1, 6)
    w, v = x_[:, 0:3], x_[:, 3:6]
    t = w.norm(p=2, dim=1).view(-1, 1, 1)
    W = so3.mat(w)
    S = W.bmm(W)
    I = torch.eye(3).to(w)

    # Rodrigues' rotation formula.
    #R = cos(t)*eye(3) + sinc1(t)*W + sinc2(t)*(w*w');
    #  = eye(3) + sinc1(t)*W + sinc2(t)*S
    R = I + sinc1(t)*W + sinc2(t)*S

    #V = sinc1(t)*eye(3) + sinc2(t)*W + sinc3(t)*(w*w')
    #  = eye(3) + sinc2(t)*W + sinc3(t)*S
    V = I + sinc2(t)*W + sinc3(t)*S

    p = V.bmm(v.contiguous().view(-1, 3, 1))

    z = torch.Tensor([0, 0, 0, 1]).view(1, 1, 4).repeat(x_.size(0), 1, 1).to(x)
    Rp = torch.cat((R, p), dim=2)
    g = torch.cat((Rp, z), dim=1)

    return g.view(*(x.size()[0:-1]), 4, 4) 
开发者ID:vinits5,项目名称:pointnet-registration-framework,代码行数:26,代码来源:se3.py

示例3: loss

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def loss(self, out, target, w=0.001):
        loss_c = torch.nn.functional.nll_loss(
            torch.nn.functional.log_softmax(out, dim=1), target, size_average=False)

        t2 = self.features.t_out_t2
        if (t2 is None) or (w == 0):
            return loss_c

        batch = t2.size(0)
        K = t2.size(1)  # [B, K, K]
        I = torch.eye(K).repeat(batch, 1, 1).to(t2)
        A = t2.bmm(t2.transpose(1, 2))
        loss_m = torch.nn.functional.mse_loss(A, I, size_average=False)
        loss = loss_c + w * loss_m
        return loss


#EOF 
开发者ID:vinits5,项目名称:pointnet-registration-framework,代码行数:20,代码来源:pointnet.py

示例4: vecs_Xg_ig

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def vecs_Xg_ig(x):
    """ Vi = vec(dg/dxi * inv(g)), where g = exp(x)
        (== [Ad(exp(x))] * vecs_ig_Xg(x))
    """
    t = x.view(-1, 3).norm(p=2, dim=1).view(-1, 1, 1)
    X = mat(x)
    S = X.bmm(X)
    #B = x.view(-1,3,1).bmm(x.view(-1,1,3))  # B = x*x'
    I = torch.eye(3).to(X)

    #V = sinc1(t)*eye(3) + sinc2(t)*X + sinc3(t)*B
    #V = eye(3) + sinc2(t)*X + sinc3(t)*S

    V = I + sinc2(t)*X + sinc3(t)*S

    return V.view(*(x.size()[0:-1]), 3, 3) 
开发者ID:vinits5,项目名称:pointnet-registration-framework,代码行数:18,代码来源:so3.py

示例5: inv_vecs_Xg_ig

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def inv_vecs_Xg_ig(x):
    """ H = inv(vecs_Xg_ig(x)) """
    t = x.view(-1, 3).norm(p=2, dim=1).view(-1, 1, 1)
    X = mat(x)
    S = X.bmm(X)
    I = torch.eye(3).to(x)

    e = 0.01
    eta = torch.zeros_like(t)
    s = (t < e)
    c = (s == 0)
    t2 = t[s] ** 2
    eta[s] = ((t2/40 + 1)*t2/42 + 1)*t2/720 + 1/12 # O(t**8)
    eta[c] = (1 - (t[c]/2) / torch.tan(t[c]/2)) / (t[c]**2)

    H = I - 1/2*X + eta*S
    return H.view(*(x.size()[0:-1]), 3, 3) 
开发者ID:vinits5,项目名称:pointnet-registration-framework,代码行数:19,代码来源:so3.py

示例6: test_UnscentedTransform2D

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def test_UnscentedTransform2D(self):
        # ===== 2D model ===== #
        mat = torch.eye(2)
        scale = torch.diag(mat)

        norm = Normal(0., 1.)
        mvn = MultivariateNormal(torch.zeros(2), torch.eye(2))
        mvnlinear = AffineProcess((fmvn, g), (mat, scale), mvn, mvn)
        mvnoblinear = AffineObservations((fomvn, gomvn), (1.,), norm)

        mvnmodel = StateSpaceModel(mvnlinear, mvnoblinear)

        # ===== Perform unscented transform ===== #
        uft = UnscentedFilterTransform(mvnmodel)
        res = uft.initialize(3000)
        p = uft.predict(res)
        c = uft.correct(0., p)

        assert isinstance(c.x_dist(), MultivariateNormal) and c.x_dist().mean.shape == torch.Size([3000, 2]) 
开发者ID:tingiskhan,项目名称:pyfilter,代码行数:21,代码来源:utils.py

示例7: test_Stacker

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def test_Stacker(self):
        # ===== Define a mix of parameters ====== #
        zerod = Parameter(Normal(0., 1.)).sample_((1000,))
        oned_luring = Parameter(Normal(torch.tensor([0.]), torch.tensor([1.]))).sample_(zerod.shape)
        oned = Parameter(MultivariateNormal(torch.zeros(2), torch.eye(2))).sample_(zerod.shape)

        mu = torch.zeros((3, 3))
        norm = Independent(Normal(mu, torch.ones_like(mu)), 2)
        twod = Parameter(norm).sample_(zerod.shape)

        # ===== Stack ===== #
        params = (zerod, oned, oned_luring, twod)
        stacked = stacker(params, lambda u: u.t_values, dim=1)

        # ===== Verify it's recreated correctly ====== #
        for p, m, ps in zip(params, stacked.mask, stacked.prev_shape):
            v = stacked.concated[..., m]

            if len(p.c_shape) != 0:
                v = v.reshape(*v.shape[:-1], *ps)

            assert (p.t_values == v).all() 
开发者ID:tingiskhan,项目名称:pyfilter,代码行数:24,代码来源:utils.py

示例8: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def __init__(self,in_channel):
        super(InvConv,self).__init__()

        weight=np.random.randn(in_channel,in_channel)
        q,_=linalg.qr(weight)
        w_p,w_l,w_u=linalg.lu(q.astype(np.float32))
        w_s=np.diag(w_u)
        w_u=np.triu(w_u,1)
        u_mask=np.triu(np.ones_like(w_u),1)
        l_mask=u_mask.T

        self.register_buffer('w_p',torch.from_numpy(w_p))
        self.register_buffer('u_mask',torch.from_numpy(u_mask))
        self.register_buffer('l_mask',torch.from_numpy(l_mask))
        self.register_buffer('l_eye',torch.eye(l_mask.shape[0]))
        self.register_buffer('s_sign',torch.sign(torch.from_numpy(w_s)))
        self.w_l=torch.nn.Parameter(torch.from_numpy(w_l))
        self.w_s=torch.nn.Parameter(torch.log(1e-7+torch.abs(torch.from_numpy(w_s))))
        self.w_u=torch.nn.Parameter(torch.from_numpy(w_u))

        self.weight=None
        self.invweight=None

        return 
开发者ID:joansj,项目名称:blow,代码行数:26,代码来源:blow.py

示例9: test_weighted_midpoint_weighted_zero_sum

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def test_weighted_midpoint_weighted_zero_sum(_k, lincomb):
    manifold = stereographic.Stereographic(_k, learnable=True)
    a = manifold.expmap0(torch.eye(3, 10)).detach().requires_grad_(True)
    weights = torch.rand_like(a[..., 0])
    weights = weights - weights.sum() / weights.numel()
    mid = manifold.weighted_midpoint(
        a, lincomb=lincomb, weights=weights, posweight=True
    )
    if _k == 0 and lincomb:
        np.testing.assert_allclose(
            mid.detach(),
            torch.cat([weights, torch.zeros(a.size(-1) - a.size(0))]),
            atol=1e-6,
        )
    assert mid.shape == a.shape[-1:]
    assert torch.isfinite(mid).all()
    mid.sum().backward()
    assert torch.isfinite(a.grad).all() 
开发者ID:geoopt,项目名称:geoopt,代码行数:20,代码来源:test_gyrovector_math.py

示例10: origin

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def origin(self, *size, dtype=None, device=None, seed=42) -> torch.Tensor:
        """
        Identity matrix point origin.

        Parameters
        ----------
        size : shape
            the desired shape
        device : torch.device
            the desired device
        dtype : torch.dtype
            the desired dtype
        seed : int
            ignored

        Returns
        -------
        ManifoldTensor
        """
        shape = size2shape(*size)
        self._assert_check_shape(shape, "x")
        eye = torch.eye(*shape[-2:], dtype=dtype, device=device)
        eye = eye.expand(shape)
        return ManifoldTensor(eye, manifold=self) 
开发者ID:geoopt,项目名称:geoopt,代码行数:26,代码来源:birkhoff_polytope.py

示例11: forward

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def forward(self, input):
        laplacian = input.exp() + self.eps
        output = input.clone()
        for b in range(input.size(0)):
            lap = laplacian[b].masked_fill(
                Variable(torch.eye(input.size(1)).cuda().ne(0)), 0)
            lap = -lap + torch.diag(lap.sum(0))
            # store roots on diagonal
            lap[0] = input[b].diag().exp()
            inv_laplacian = lap.inverse()

            factor = inv_laplacian.diag().unsqueeze(1)\
                                         .expand_as(input[b]).transpose(0, 1)
            term1 = input[b].exp().mul(factor).clone()
            term2 = input[b].exp().mul(inv_laplacian.transpose(0, 1)).clone()
            term1[:, 0] = 0
            term2[0] = 0
            output[b] = term1 - term2
            roots_output = input[b].diag().exp().mul(
                inv_laplacian.transpose(0, 1)[0])
            output[b] = output[b] + torch.diag(roots_output)
        return output 
开发者ID:xiadingZ,项目名称:video-caption-openNMT.pytorch,代码行数:24,代码来源:StructuredAttention.py

示例12: transform_np

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def transform_np(point, center, scale, resolution, invert=False):
    _pt = np.ones(3)
    _pt[0] = point[0]
    _pt[1] = point[1]

    h = 200.0 * scale
    t = np.eye(3)
    t[0, 0] = resolution / h
    t[1, 1] = resolution / h
    t[0, 2] = resolution * (-center[0] / h + 0.5)
    t[1, 2] = resolution * (-center[1] / h + 0.5)

    if invert:
        t = np.ascontiguousarray(np.linalg.pinv(t))

    new_point = np.dot(t, _pt)[0:2]

    return new_point.astype(np.int32) 
开发者ID:kwea123,项目名称:VTuber_Unity,代码行数:20,代码来源:utils.py

示例13: __init__

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def __init__(self, num_inputs):
        super(LUInvertibleMM, self).__init__()
        self.W = torch.Tensor(num_inputs, num_inputs)
        nn.init.orthogonal_(self.W)
        self.L_mask = torch.tril(torch.ones(self.W.size()), -1)
        self.U_mask = self.L_mask.t().clone()

        P, L, U = sp.linalg.lu(self.W.numpy())
        self.P = torch.from_numpy(P)
        self.L = nn.Parameter(torch.from_numpy(L))
        self.U = nn.Parameter(torch.from_numpy(U))

        S = np.diag(U)
        sign_S = np.sign(S)
        log_S = np.log(abs(S))
        self.sign_S = torch.from_numpy(sign_S)
        self.log_S = nn.Parameter(torch.from_numpy(log_S))

        self.I = torch.eye(self.L.size(0)) 
开发者ID:ikostrikov,项目名称:pytorch-flows,代码行数:21,代码来源:flows.py

示例14: forward

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def forward(self, x):
        batchsize = x.size()[0]
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.relu(self.bn2(self.conv2(x)))
        x = F.relu(self.bn3(self.conv3(x)))
        x = torch.max(x, 2, keepdim=True)[0]
        x = x.view(-1, 1024)

        x = F.relu(self.bn4(self.fc1(x)))
        x = F.relu(self.bn5(self.fc2(x)))
        x = self.fc3(x)

        iden = Variable(torch.from_numpy(np.eye(self.k).flatten().astype(np.float32))).view(1, self.k * self.k).repeat(
            batchsize, 1)
        if x.is_cuda:
            iden = iden.cuda()
        x = x + iden
        x = x.view(-1, self.k, self.k)
        return x 
开发者ID:yanx27,项目名称:Pointnet_Pointnet2_pytorch,代码行数:21,代码来源:pointnet.py

示例15: forward

# 需要导入模块: import torch [as 别名]
# 或者: from torch import eye [as 别名]
def forward(self, im, s):
        # compute image-sentence score matrix
        scores = self.sim(im, s)
        diagonal = scores.diag().view(im.size(0), 1)
        d1 = diagonal.expand_as(scores)

        # compare every diagonal score to scores in its column
        # caption retrieval
        cost_s = (self.margin + scores - d1).clamp(min=0)

        # clear diagonals
        mask = torch.eye(scores.size(0)) > .5
        I = Variable(mask)
        if torch.cuda.is_available():
            I = I.cuda()
        cost_s = cost_s.masked_fill_(I, 0)

        # keep the maximum violating negative for each query
        if self.max_violation:
            cost_s = cost_s.max(1)[0]

        return cost_s.sum() 
开发者ID:Hangz-nju-cuhk,项目名称:Talking-Face-Generation-DAVS,代码行数:24,代码来源:loss_functions.py


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