Pytorch学习——Pytorch的入门操作 02(未完)

1 张量 Tensor

各种数值数都可以称为张量。

  • 常数:scaler:0阶张量
  • 向量:vector:1阶张量
  • 矩阵:matrix:2阶张量
  • 3阶张量

1.1 使用列表或者序列创建tensor

torch.Tensor([1, 2, 3])

torch.Tensor([[1., -1.], [1., -1.]])

1.2 使用numpy中的数组创建tensor

torch.Tensor(np.arange(12).reshape(3, 4))

torch.Tensor(np.array([[]1, 2, 3], [4, 5, 6]))

1.3 使用torch的API创建tensor

注意:这里括号内都表示的是shape

torch.empty([3, 4])
torch.ones([3, 4])
torch.zeros([3, 4])
torch.rand([3, 4])  # 创建3行4列的随机值的tensor,区间是[0, 1]

  • 创建int型数组,指定范围
torch.randint(low=0, high=10, size=[3, 4])
  • 创建均值为0,方差为1的 3行4列的数组(服从标准正态分布)
torch.randn([3, 4])

1.4 获取形状(与numpy的区别)

  • numpy中打印形状是 shape
  • tensor打印形状是 size

2 张量的方法和属性

2.1 item()和tolist() 方法

item()是将一个张量的值 以一个python数字形式返回,但该方法只能包含一个元素的张量

对于包含多个元素的张量,可以考虑tolist()方法。

tensor.item()
tensor.tolist()

2.2 转换为numpy数组

tensor.numopy()

2.3 获取形状

tensor.size()

2.4 改变形状

类似于numpy中的reshape,是一种浅拷贝。

tensor.view(3, 4)

2.5 获取阶数

tensor.dim()

2.6 获取最大值

tensor.max()

2.7 转置

tensor.t()
tensor.transpose()
tensor.permute()   # 可以指定维度

2.8 切片

也是用 ,是和numpy的操作一样的。

tensor[0, :, :]

2.9 获取tensor数据类型

tensor.dtype

3 CUDA中的tensor

CUDA 是一种NVIDIA退出的通用并行计算架构,该架构能够使GPU解决复杂的计算问题。

3.1 查看电脑是否支持GPU版本

print(torch.cuda.is_available())

3.2 .device

接收一个字符串

torch.device("cpu")
torch.device("gpu")  # 如果有几块GPU,则可以指定使用第几块
torch.device("cuda:0")

3.3 .to() 方法

torch.device("cuda")

a = torch.zero([2, 3])
a.to(device)
>> tensor([[0, 0, 0], [0, 0, 0]], device="cuda:0")

猜你喜欢

转载自blog.csdn.net/weixin_42521185/article/details/126761446