pytorch线性张量与随机张量

📅 2026/6/27 8:37:18
pytorch线性张量与随机张量
3.1创建方法torch.arange(start,end,step) : 生成一个指定范围的等间隔序列。左闭右开.torch.linspace(start,end,num) : 生成一个指定范围的等间隔序列。左闭右闭.torch.rand(size, devicecpu) : 一个服从均匀分布的随机数张量, 生成的随机数范围在 [0, 1) 之间.torch.randn(size, devicecpu) : 生成一个服从标准正态分布(均值为 0标准差为 1) 的随机数张量.torch.random.initial_seed() : 返回 PyTorch 随机数生成器的初始种子一般为 0 或者随机数字.torch.random.manual_seed() : 手动设置 PyTorch 随机数生成器的种子.注意事项CPU 是串行执行的所以随机数生成器状态更新是按照顺序的结果就一致。CUDA 由于并行运算就算设置了相同的 seed因为每个线程的随机数生成器更新顺序不确定所以结果就不一致。3.2代码案例import torch device torch.device(cuda if torch.cuda.is_avaliable() else cpu) cpu_range torch.range(0,10,devicecuda) cpu_linspace torch.linspace(0,1,10) print(CPU range:,cpu_range,cpu_range.device) print(CPU linspace:,cpu_linspace,cpu_linspace.device) cpu_randn torch.randn(2,2) print(CPU randncpu_randn,cpu_randn.device) seed torch.random.initial_seed() print(CPU seed:,seed) torch.manual_seed(seed) cpu_rand torch.rand(2,2) print(CPU rand:cpu_rand,cpu_rand.device)4、pytorch张量类型转换4.1查看数据类型每个 PyTorch 张量都有一个 .dtype 属性它返回一个 torch.dtype 对象表示张量的数据类型。4.2常用数据类型torch.float32 或 torch.float 32 位浮点数 (默认)torch.float64 或 torch.double 64 位浮点数torch.float16 或 torch.half 16 位浮点数半精度torch.int32 或 torch.int 32 位整数torch.int64 或 torch.long 64 位整数torch.int16 或 torch.short 16 位整数torch.int8 8 位整数torch.uint8 8 位无符号整数torch.bool布尔值4.3代码示例import torch # 创建不同类型的张量 float_tensor torch.tensor([1.0,2.0,3.0]) int_tensor torch.tensor([1,2,3],dtypetorch.int32) bool_tensor torch.tensor([True,False,True]) # 查看数据类型 print(float_tensor dtype:float_tensor.dtype) print(int_tensor dtype:int_tensor.dtype) print(bool_tensor dtype:bool_tensor.dtype)4.4数据类型转换使用.to(dtype)方法tensor.to(dtype) 方法可以将张量转换为指定的数据类型。如果仅仅是类型转换可以不需要指定设备。使用.type(dtype)方法tensor.type(dtype) 方法和 .to(dtype) 方法功能类似都能将张量转换为指定数据类型。使用tensor.type_as(other_tensor)方法将当前张量的数据类型与传入的张量的数据类型保持一致。使用data.type()方法将当前张量的数据类型转成与 type 类型。4.5代码示例import torch # 创建一个float32张量 float_tensor torch.tensor([1.0,2.0,3.0]) print(原始张量数据类型,float_tensor.dtype) # 转换为int32类型 int_tensor float_tensor.to(torch.int32) print(f使用to()转换后{int_tensor}张量数据类型{int_tensor.dtype}) # 转换为double double_tensor int_tensor.type(torch.double) print(f使用type()转换后{double_tensor}张量数据类型{double_tensor.dtype}) # 转为int32张量 int32_tensor double_tensor.type_as(int_tensor) print(f使用type_as()转换后{int32_tensor}张量数据类型{int32_tensor.dtype}) print(int32_tensor.long())今天整理了2小节接下来几天可能会比较忙后续依然会持续更新有问题欢迎大家评论区讨论