一文读懂PyTorch张量基础（附代码）

import torch

# Create a Torch tensor

t = torch.Tensor([[1, 2, 3], [4, 5, 6]])

t

tensor([[ 1., 2., 3.],

[ 4., 5., 6.]])

# Transpose

t.t()

# Transpose (via permute)

t.permute(-1,0)

tensor([[ 1., 4.],

[ 2., 5.],

[ 3., 6.]])


# Reshape via view
t.view(3,2)

tensor([[ 1., 2.],

[ 3., 4.],

[ 5., 6.]])

# View again...

t.view(6,1)

tensor([[ 1.],

[ 2.],

[ 3.],

[ 4.],

[ 5.],

[ 6.]])

# Create tensor of zeros

t = torch.zeros(3, 3)

t

tensor([[ 0., 0., 0.],

[ 0., 0., 0.],

[ 0., 0., 0.]])

# Create tensor from normal distribution randoms

t = torch.randn(3, 3)

t

tensor([[ 1.0274, -1.3727, -0.2196],

[-0.7258, -2.1236, -0.8512],

[ 0.0392, 1.2392, 0.5460]])

Tensor对象的形状、维度和数据类型：

# Some tensor info

print('Tensor shape:', t.shape) # t.size() gives the same

print('Number of dimensions:', t.dim())

print('Tensor type:', t.type()) # there are other types

Tensor shape: torch.Size([3, 3])

Number of dimensions: 2

Tensor type: torch.FloatTensor

# Slicing

t = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Every row, only the last column

print(t[:, -1])

# First 2 rows, all columns

print(t[:2, :])

# Lower right most corner

print(t[-1:, -1:])

tensor([ 3., 6., 9.])

tensor([[ 1., 2., 3.],

[ 4., 5., 6.]])

tensor([[ 9.]])

PyTorch张量和Numpy ndarray之间转换

# Numpy ndarray <--> PyTorch tensor

import numpy as np

# ndarray to tensor

a = np.random.randn(3, 5)

t = torch.from_numpy(a)

print(a)

print(t)

print(type(a))

print(type(t))

[[-0.52192738 -1.11579634 1.26925835 0.10449378 -1.02894372]

[-0.78707263 -0.05350072 -0.65815075 0.18810677 -0.52795765]

[-0.41677548 0.82031861 -2.46699201 0.60320375 -1.69778546]]

tensor([[-0.5219, -1.1158, 1.2693, 0.1045, -1.0289],

[-0.7871, -0.0535, -0.6582, 0.1881, -0.5280],

[-0.4168, 0.8203, -2.4670, 0.6032, -1.6978]], dtype=torch.float64)

<class 'numpy.ndarray'>

<class 'torch.Tensor'>

# tensor to ndarray

t = torch.randn(3, 5)

a = t.numpy()

print(t)

print(a)

print(type(t))

print(type(a))

tensor([[-0.1746, -2.4118, 0.4688, -0.0517, -0.2706],

[-0.8402, -0.3289, 0.4170, 1.9131, -0.8601],

[-0.6688, -0.2069, -0.8106, 0.8582, -0.0450]])

[[-0.17455131 -2.4117854 0.4688457 -0.05168453 -0.2706456 ]

[-0.8402392 -0.3289494 0.41703534 1.9130518 -0.86014426]

[-0.6688193 -0.20693372 -0.8105542 0.8581988 -0.04502954]]

<class 'torch.Tensor'>

<class 'numpy.ndarray'>

# Compute cross product
t1 = torch.randn(4, 3)

t2 = torch.randn(4, 3)

t1.cross(t2)

tensor([[ 2.6594, -0.5765, 1.4313],

[ 0.4710, -0.3725, 2.1783],

[-0.9134, 1.6253, 0.7398],

[-0.4959, -0.4198, 1.1338]])

# Compute matrix product

t = (torch.Tensor([[2, 4], [5, 10]]).mm(torch.Tensor([[10], [20]])))

t

tensor([[ 100.],

[ 250.]])

# Elementwise multiplication

t = torch.Tensor([[1, 2], [3, 4]])

t.mul(t)

tensor([[ 1., 4.],

[ 9., 16.]])

关于GPU的一句话

PyTorch张量具有固有的GPU支持。指定使用GPU内存和CUDA内核来存储和执行张量计算非常简单；cuda软件包可以帮助确定GPU是否可用，并且该软件包的cuda方法为GPU分配了一个张量。

# Is CUDA GPU available?

torch.cuda.is_available()

# How many CUDA devices?

torch.cuda.device_count()

# Move to GPU

t.cuda()

+ 订阅