张量入门及其初始化

张量及其初始化

介绍

  • 张量是一种特殊的数据结构,与数组和矩阵非常相似。
  • 在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。
  • 张量类似于NumPy 的ndarray,不同之处在于张量可以在 GPU 或其他硬件加速器上运行。
  • 事实上,张量和 NumPy 数组通常可以共享相同的底层内存,从而无需复制数据。
  • 张量也针对自动微分进行了优化
import torch
import numpy as np

初始化张量的几种方式

1. 直接从数据
# 张量可以直接从数据中创建。数据类型是自动推断的。

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
2. 从Numpy数组
# 张量可以从 NumPy 数组创建,反之亦然

np_array = np.array(data)
x_np = torch.from_numpy(np_array)
3. 从另一个张量
# 除非明确覆盖,否则新张量保留参数张量的属性(形状、数据类型)

x_ones = torch.ones_like(x_data)
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) 
print(f"Random Tensor: \n {x_rand} \n")
4. 使用随机值或常数值
#shape是张量维度的元组,决定了输出张量的维度

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")

张量的属性

  • 张量属性描述了它们的形状、数据类型和存储它们的设备
tensor = torch.rand(3,4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
posted @ 2021-09-26 22:00  mx_info  阅读(296)  评论(0编辑  收藏  举报