Skip to content

Instantly share code, notes, and snippets.

@ikhlestov
Last active February 19, 2020 06:47
Show Gist options
  • Save ikhlestov/c057badae2e4cce6b8ca1b96005e2c34 to your computer and use it in GitHub Desktop.
Save ikhlestov/c057badae2e4cce6b8ca1b96005e2c34 to your computer and use it in GitHub Desktop.
pytorch: pytorch as numpy
import torch
import numpy as np
numpy_tensor = np.random.randn(10, 20)
# convert numpy array to pytorch array
pytorch_tensor = torch.Tensor(numpy_tensor)
# or another way
pytorch_tensor = torch.from_numpy(numpy_tensor)
# convert torch tensor to numpy representation
pytorch_tensor.numpy()
# if we want to use tensor on GPU provide another type
dtype = torch.cuda.FloatTensor
gpu_tensor = torch.randn(10, 20).type(dtype)
# or just call `cuda()` method
gpu_tensor = pytorch_tensor.cuda()
# call back to the CPU
cpu_tensor = gpu_tensor.cpu()
# define pytorch tensors
x = torch.randn(10, 20)
y = torch.ones(20, 5)
# `@` mean matrix multiplication from python3.5, PEP-0465
res = x @ y
# get the shape
res.shape # torch.Size([10, 5])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment