How to use the torch.tensor function in torch

To help you get started, we’ve selected a few torch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github marsermd / DeepestScatter / DeepestScatter_Train / DisneyDescriptorDataset.py View on Github external
def __getLightAngle(self, sampleId):
        sceneId = sampleId // BATCH_SIZE
        scene = self.lmdbDataset.get(SceneSetup, sceneId)

        sample = self.lmdbDataset.get(ScatterSample, sampleId)

        lightDirection = np.array([scene.light_direction.x, scene.light_direction.y, scene.light_direction.z])
        viewDirection = np.array([sample.view_direction.x, sample.view_direction.y, sample.view_direction.z])

        angle = np.math.acos(np.dot(normalized(lightDirection), normalized(viewDirection)))
        return torch.tensor(angle, dtype=torch.float32)
github rusty1s / pytorch_geometric / test / nn / pool / test_edge_pool.py View on Github external
def test_edge_pooling():
    x = torch.Tensor([[0], [1], [2], [3], [4], [5], [-1]])
    edge_index = torch.tensor([[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6],
                               [1, 2, 3, 0, 2, 3, 0, 1, 3, 0, 1, 2, 5, 4, 0]])
    batch = torch.tensor([0, 0, 0, 0, 1, 1, 0])

    op = EdgePooling(in_channels=1)
    assert op.__repr__() == 'EdgePooling(1)'

    # Setting parameters fixed so we can test the expected outcome.
    op.lin.weight[0, 0] = 1
    op.lin.weight[0, 1] = 1
    op.lin.bias[0] = 0

    # Test pooling.
    new_x, new_edge_index, new_batch, unpool_info = op(x, edge_index, batch)

    assert new_x.size(0) == new_batch.size(0) == 4
    assert new_batch.tolist() == [1, 0, 0, 0]
    assert torch.all(new_batch == torch.tensor([1, 0, 0, 0]))
    assert new_edge_index.tolist() == [[0, 1, 1, 2, 2, 3], [0, 1, 2, 1, 2, 2]]
github BachiLi / redner / tests / test_bunny_box.py View on Github external
import scipy.ndimage.filters
import pyredner
import numpy as np
import torch

pyredner.set_use_gpu(torch.cuda.is_available())

scene = pyredner.load_mitsuba('scenes/bunny_box.xml')

scene.shapes[-1].vertices += torch.tensor([0, 0.01, 0], device = pyredner.get_device())

args=pyredner.RenderFunction.serialize_scene(\
    scene = scene,
    num_samples = 4,
    max_bounces = 6)
render = pyredner.RenderFunction.apply
# Render our target. The first argument is the seed for RNG in the renderer.
img = render(0, *args)
pyredner.imwrite(img.cpu(), 'results/test_bunny_box/target.exr')
pyredner.imwrite(img.cpu(), 'results/test_bunny_box/target.png')
target = pyredner.imread('results/test_bunny_box/target.exr')
if pyredner.get_use_gpu():
    target = target.cuda(device = pyredner.get_device())

bunny_vertices = scene.shapes[-1].vertices.clone()
bunny_translation = torch.tensor([0.1,0.4,0.1], device = pyredner.get_device(), requires_grad=True)
github hrbigelow / ae-wavenet / wave_encoder.py View on Github external
self.relu = nn.ReLU()
        self.name = name
        # self.bn = nn.BatchNorm1d(n_out_chan)

        self.vc = vconv.VirtualConv(filter_info=filter_sz, stride=stride,
                parent=parent_vc, name=name)

        self.do_res = do_res
        if self.do_res:
            if stride != 1:
                print('Stride must be 1 for residually connected convolution',
                        file=stderr)
                raise ValueError
            l_off, r_off = vconv.output_offsets(self.vc, self.vc)
            self.register_buffer('residual_offsets',
                    torch.tensor([l_off, r_off]))
        netmisc.xavier_init(self.conv)
github rusty1s / pytorch_geometric / torch_geometric / utils / negative_sampling.py View on Github external
for every positive edge. (default: :obj:`None`)

    :rtype: LongTensor
    """

    num_nodes = maybe_num_nodes(edge_index, num_nodes)
    num_neg_samples = num_neg_samples or edge_index.size(1)

    # Handle '2*|edges| > num_nodes^2' case.
    num_neg_samples = min(num_neg_samples,
                          num_nodes * num_nodes - edge_index.size(1))

    idx = (edge_index[0] * num_nodes + edge_index[1]).to('cpu')

    rng = range(num_nodes**2)
    perm = torch.tensor(random.sample(rng, num_neg_samples))
    mask = torch.from_numpy(np.isin(perm, idx)).to(torch.bool)
    rest = mask.nonzero().view(-1)
    while rest.numel() > 0:  # pragma: no cover
        tmp = torch.tensor(random.sample(rng, rest.size(0)))
        mask = torch.from_numpy(np.isin(tmp, idx)).to(torch.bool)
        perm[rest] = tmp
        rest = rest[mask.nonzero().view(-1)]

    row, col = perm / num_nodes, perm % num_nodes
    return torch.stack([row, col], dim=0).long().to(edge_index.device)
github mariogeiger / se3cnn / se3cnn / SO3.py View on Github external
def rot_z(gamma):
    """
    Rotation around Z axis
    """
    if not torch.is_tensor(gamma):
        gamma = torch.tensor(gamma, dtype=torch.get_default_dtype())
    return gamma.new_tensor([
        [gamma.cos(), -gamma.sin(), 0],
        [gamma.sin(), gamma.cos(), 0],
        [0, 0, 1]
    ])
github YosefLab / scVI / scvi / models / semi_supervised_vae.py View on Github external
ys_cubo = torch.tensor([], device="cuda")

            ct = counts[1]
            if ct >= 1:
                post_eubo = self.inference(x, n_samples=ct, encoder_key="EUBO")
                z_eubo = (
                    post_eubo["z1"]
                    .view(1, counts[1], n_batch, n_latent)
                    .expand(n_labels, counts[1], n_batch, n_latent)
                )
                u_eubo = post_eubo["z2"]
                ys_eubo = post_eubo["ys"]
            else:
                z_eubo = torch.tensor([], device="cuda")
                u_eubo = torch.tensor([], device="cuda")
                ys_eubo = torch.tensor([], device="cuda")
            # Sampling prior
            ct = counts[2]
            if ct >= 1:
                latents_prior = self.latent_prior_sample(n_batch=n_batch, n_samples=ct)

                z1_prior = latents_prior["z1"]
                z2_prior = latents_prior["z2"]
                ys_prior = latents_prior["ys"]
            else:
                z1_prior = torch.tensor([], device="cuda")
                z2_prior = torch.tensor([], device="cuda")
                ys_prior = torch.tensor([], device="cuda")

            # Concatenating latent variables
            z_all = torch.cat([z_cubo, z_eubo, z1_prior], dim=1)
            u_all = torch.cat([u_cubo, u_eubo, z2_prior], dim=1)
github thu-coai / tatk / tatk / dst / sumbt / sumbt.py View on Github external
features.append(
                InputFeatures(input_ids=input_ids,
                              input_len=input_len,
                              label_id=label_id))

        prev_dialogue_idx = curr_dialogue_idx
        prev_turn_idx = curr_turn_idx

    if prev_turn_idx < max_turn_length:
        features += [InputFeatures(input_ids=all_padding,
                                   input_len=all_padding_len,
                                   label_id=[-1] * slot_dim)] \
                    * (max_turn_length - prev_turn_idx - 1)
    assert len(features) % max_turn_length == 0

    all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
    all_input_len = torch.tensor([f.input_len for f in features], dtype=torch.long)
    if not FLAG_TEST:
        all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.long)

    # reshape tensors to [#batch, #max_turn_length, #max_seq_length]
    all_input_ids = all_input_ids.view(-1, max_turn_length, max_seq_length)
    all_input_len = all_input_len.view(-1, max_turn_length, 2)
    if not FLAG_TEST:
        all_label_ids = all_label_ids.view(-1, max_turn_length, slot_dim)
    else:
        all_label_ids = None

    return all_input_ids, all_input_len, all_label_ids
github martinResearch / DEODR / deodr / pytorch / differentiable_renderer_pytorch.py View on Github external
def left_mul_intrinsic(self, projected):
        return torch.cat(
            (projected, torch.ones((projected.shape[0], 1), dtype=torch.double)), dim=1
        ).mm(torch.tensor(self.intrinsic[:2, :].T))
github nkolot / SPIN / smplify / losses.py View on Github external
def angle_prior(pose):
    """
    Angle prior that penalizes unnatural bending of the knees and elbows
    """
    # We subtract 3 because pose does not include the global rotation of the model
    return torch.exp(pose[:, [55-3, 58-3, 12-3, 15-3]] * torch.tensor([1., -1., -1, -1.], device=pose.device)) ** 2