pytorch基础学习笔记

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

# 用torch.Tensor创建一个张量
describe(torch.Tensor(2, 3))
describe(torch.tensor(2))
describe(torch.tensor([2, 3, 4]))# Tensor输入的是形状也可是具体的list,tensor输入的是具体的值
# 创建一个随机初始化张量
describe(torch.rand(2, 3))
describe(torch.randn(2, 3))
# 通过fill_()填充方式创建一个张量
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)
# 从numpy创建并初始化一个张量 
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))# 取x的【0号列,2号列】
describe(x)
indices = torch.LongTensor([0, 0])
describe(indices)
describe(torch.index_select(x, dim=0, index=indices))# 取x的【0号行,0号行】
describe(torch.index_select(x, dim=1, index=indices))# 取x的【0号列,0号列】
row_indices = torch.arange(2).long()
col_indices = torch.LongTensor([0, 1])
describe(x[row_indices, col_indices])# x[[0, 1], [0, 1]] 取x的【0号行0号列,1号行1号列】
# 连接张量
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 # 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张量

# 在GPU上分配张量,需安装pytroch的GPU版本
print(torch.cuda.is_available())# 检查GPU是否可用
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# 检索设备名称
print(device)
x = torch.rand(3, 3).to(device)# 实例化所有未来的张量并将其移动到目标设备
describe(x)
# 讲CUDA张量与CPU绑定张量混合
y = torch.rand(3, 3)
x + y # x是在gpu设备上,y是在cpu设备上,所以计算中断
# 要确保CUDA对象和非CUDA对象在同一设备上才可计算
cpu_device = torch.device("cpu")
y = y.to(cpu_device)
x = x.to(cpu_device)
x + y

升降维操作

# 随机创建一个二维张量,然后在第0维插入1个维度
a = torch.rand(2,2)
describe(a)
a = a.unsqueeze(0)
describe(a)
# 去掉你刚刚加到张量的额外维度
a = a.squeeze(0)
describe(a)
# 在区间[3, 7]中创建一个形状为5*3的随机张量
a = torch.rand(5, 3) * (7 - 3) + 3
describe(a)
# 创建一个具有正态分布(mean=0, std=1)值的张量
a = torch.randn(3,3)
describe(a)
a = a.normal_()
describe(a)
# 找到torch.Tensor([1, 1, 1, 0, 1])中所有非零元素的索引
a = torch.Tensor([1,1,1,0,1])
print(torch.nonzero(a))
# 创建一个大小为(3,1)的随机张量,水平扩展4个副本
a = torch.rand(3, 1)
describe(a)
a.expand(3, 4)
# 返回两个3维矩阵的乘积(a=torch.rand(3,4,5), b=torch.rand(3,5,4))
a = torch.rand(3, 4, 5)
b = torch.rand(3, 5, 4)
torch.bmm(a, b)
# 返回一个3维矩阵和一个2维矩阵的乘积(a=torch.rand(3,4,5), b=torch.rand(5,4))
a = torch.rand(3, 4, 5)
b = torch.rand(5, 4)
torch.bmm(a, b.unsqueeze(0).expand(a.size(0), *b.size()))

猜你喜欢

转载自blog.csdn.net/weixin_45569617/article/details/108618401