目录
1 Tensor概述
2 Tensor的创建
2.1 基本的创建方式
2.1.1 torch.tensor
2.1.2 torch.Tensor
2.2 创建线性和随机张量
2.2.1 创建线性张量
2.2.2 随机张量
1 Tensor概述
PyTorch会将数据封装成张量(Tensor)进行计算,张量就是元素为相同类型。
张量可以在GPU上加速运行。
2 Tensor的创建
2.1 基本的创建方式
以下讲的创建tensor的函数中有两个有默认值的参数dtype和device, 分别代表数据类型和计算设备
2.1.1 torch.tensor
使用tensor方法创建张量,可以创建标量,一维,二维,多维数组
参数:
dtype:指定张量的数据类型
device:指定张量的运算的设备:cuda、cpu,如果不指定,默认在cpu上运算
import torchdef test01():t1=torch.tensor([1,2,3],dtype=torch.float32,device="cpu")print(t1)print(t1.shape)# size和shape作用一样,获取张量的形状print(t1.size())# dtype:获取张量的数据类型,如果在创建张量时,没有指定dtype,则自动根据输入数组的数据类型来判断print(t1.dtype)# 用标量创建张量tensor = torch.tensor(5)# 使用numpy随机一个数组创建张量tensor = torch.tensor(np.random.randn(3, 5))
2.1.2 torch.Tensor
使用Tensor()构造函数创建张量,强制将数据类型转换为float32,没有dtype和device属性
tensor()方法创建的张量更灵活,使用更多一些。
def test02():# 1. 根据形状创建张量tensor1 = torch.Tensor(2, 3)print(tensor1)t1=torch.Tensor([1,2,3])print(t1)print(t1.shape)print(t1.dtype)
2.2 创建线性和随机张量
2.2.1 创建线性张量
import torch
import numpy as np# 不用科学计数法打印
torch.set_printoptions(sci_mode=False)def test004():# 1. 创建线性张量r1 = torch.arange(0, 10, 2)print(r1)# 2. 在指定空间按照元素个数生成张量:等差r2 = torch.linspace(3, 10, 10)print(r2)r2 = torch.linspace(3, 10000000, 10)print(r2)if __name__ == "__main__":test004()
2.2.2 随机张量
import torchdef test001():# 1. 设置随机数种子torch.manual_seed(123)# 2. 获取随机数种子,需要查看种子时调用print(torch.initial_seed())# 3. 生成随机张量,均匀分布(范围 [0, 10))# 创建2个样本,每个样本3个特征s=torch.randint(0,10,(2,3))print(s)# 4. 生成随机张量:标准正态分布(均值 0,标准差 1)print(torch.randn(2, 3))# 5. 原生服从正态分布:均值为2, 方差为3,形状为1*4的正态分布print(torch.normal(mean=2, std=3, size=(1, 4)))if __name__ == "__main__":test001()