import torch
import numpy as np
def describe(x):
print("Type:{}".format(x.type()))
print("Shape/size:{}".format(x.shape))
print("Values:\n{}".format(x))
创建张量tensor
describe(torch.Tensor(2, 3))
describe(torch.tensor(2))
describe(torch.tensor([2, 3, 4]))
describe(torch.rand(2, 3))
describe(torch.randn(2, 3))
describe(torch.zeros(2, 3))
x = torch.ones(2, 3)
describe(x)
x.fill_(5)
describe(x)
x = torch.Tensor([[1, 2, 3],
[4, 5, 6]])
describe(x)
npy = np.random.rand(2, 3)
describe(torch.from_numpy(npy))
张量的类型和大小
x = torch.FloatTensor([[1, 2, 3],
[4, 5, 6]])
describe(x)
x = x.long()
describe(x)
x = torch.tensor([[1, 2, 3],
[4, 5, 6]], dtype=torch.int64)
describe(x)
x = x.float()
describe(x)
张量的操作
x = torch.randn(2, 3)
describe(x)
describe(torch.add(x, x))
describe(x + x)
x = torch.arange(6)
describe(x)
x = x.view(2, 3)
y = x.view(2, -1)
describe(x)
describe(y)
describe(torch.sum(x, dim=0))
describe(torch.sum(x, dim=1))
describe(torch.transpose(x, 0, 1))
索引、切片、连接
x = torch.arange(6).view(2, 3)
describe(x)
describe(x[:1, :2])
describe(x[0, 1])
describe(x)
indices = torch.LongTensor([0, 2])
describe(indices)
describe(torch.index_select(x, dim=1, index=indices))
describe(x)
indices = torch.LongTensor([0, 0])
describe(indices)
describe(torch.index_select(x, dim=0, index=indices))
describe(torch.index_select(x, dim=1, index=indices))
row_indices = torch.arange(2).long()
col_indices = torch.LongTensor([0, 1])
describe(x[row_indices, col_indices])
x = torch.arange(6).view(2, 3)
describe(x)
describe(torch.cat([x, x], dim=0))
describe(torch.cat([x, x], dim=1))
describe(torch.stack([x, x]))
x1 = torch.arange(6).view(2, 3).float()
describe(x1)
x2 = torch.ones(3, 2)
x2[:, 1] += 1
describe(x2)
describe(torch.mm(x1, x2))
张量和计算图
x = torch.ones(2, 2, requires_grad=True)
describe(x)
print(x.grad is None)
y = (x + 2) * (x + 5) + 3
describe(y)
print(x.grad is None)
z = y.mean()
describe(z)
z.backward()
print(x.grad is None)
CUDA张量
print(torch.cuda.is_available())
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
x = torch.rand(3, 3).to(device)
describe(x)
y = torch.rand(3, 3)
x + y
cpu_device = torch.device("cpu")
y = y.to(cpu_device)
x = x.to(cpu_device)
x + y
升降维操作
a = torch.rand(2,2)
describe(a)
a = a.unsqueeze(0)
describe(a)
a = a.squeeze(0)
describe(a)
a = torch.rand(5, 3) * (7 - 3) + 3
describe(a)
a = torch.randn(3,3)
describe(a)
a = a.normal_()
describe(a)
a = torch.Tensor([1,1,1,0,1])
print(torch.nonzero(a))
a = torch.rand(3, 1)
describe(a)
a.expand(3, 4)
a = torch.rand(3, 4, 5)
b = torch.rand(3, 5, 4)
torch.bmm(a, b)
a = torch.rand(3, 4, 5)
b = torch.rand(5, 4)
torch.bmm(a, b.unsqueeze(0).expand(a.size(0), *b.size()))