网站域名备案资料,东莞黄江做网站,开发公司个人工作总结,域名备案查询站长工具import torch
import numpy as np def sci_close(): # 关闭pytorch 数据打印出来时科学计数法 torch.set_printoptions(sci_modeFalse) pass return 0
def create_tensor(): # 创建张量 t1torch.tensor(5) # 一阶张量 阶数看你传入的矩阵是多少阶的 这个是标量 不是一阶 一阶…import torch
import numpy as np def sci_close(): # 关闭pytorch 数据打印出来时科学计数法 torch.set_printoptions(sci_modeFalse) pass return 0
def create_tensor(): # 创建张量 t1torch.tensor(5) # 一阶张量 阶数看你传入的矩阵是多少阶的 这个是标量 不是一阶 一阶要加[] 加了[]才是多少阶 t1.dtype # tensor张量里面的数据类型 只能是int float bool t1.shape # tensor张量的形状 标量的shape啥都没有 t1.device # 数据运行的设备 # 创建的时候也可以传入np数组 list # 创建的时候也可以传入参数 dtype 如果数据超出范围会自动变为最大范围的余数 设置tensor数据类型 tensor数据类型有..... 都是torch里面的数据类型int8.....跟numpy类似 # 创建的时候可以指定数据运行的设备 传入参数device cpu 或者 cuda 不同设备上的数据无法运算 t2torch.tensor([[1,2,3],[300,22,11]],dtypetorch.int8,devicecpu) # print(t2.device) # 也可以使用 tensor.to(cpu) tensor.to(cuda) 返回一个新的运行在新设备上的tensor t3t2.to(cpu) print(t3.device) # 查看cuda是否可用 返回布尔值 bool1torch.cuda.is_available() # 可以根据这个布尔值 设计一个 有显卡先用显卡 没显卡用CPU的程序 # 也可以使用tensor.cuda() 直接返回一个在显卡上运行的新tensor def choose_device(): t1torch.Tensor(3,2,devicecpu) if torch.cuda.is_available(): t2t1.cuda() else: t2t1 t2t1 torch.cuda.is_available() and t2t1.cuda() def create_Tensor(): # 利用Tensor()直接创建特定形状的张量 # 这个是大写的Tensor t1torch.Tensor(5,4) # 创建 一个5行4列的二维tensor at1.dtype # bt1.shape # # print(b) # 也可以在Tensor前面加数据类型 创建出来的tensor里面的数据就是对应的类型 位数不同 tt2 torch.FloatTensor(3, 3) tt3 torch.DoubleTensor(3, 3) tt4 torch.LongTensor(3, 3) tt5 torch.ShortTensor(3, 3) print(t1)
# 创建线性和随机张量
def create_line_random_tensor(): # 跟numpy的差不多 不过np变为了torch star stop step 不包括stop # 感觉torch就是集成了一个numpy在里面 t1torch.arange(1,10,step2) # 知道等差公差 # print(t1) # 包含了stop t2torch.linspace(1,10,4,dtypetorch.int8) # 知道等差的 个数 # print(t2) # 等比数列 logspace base 基数 这个是2的1次方开始 到2的10次方 step为元素个数n t3torch.logspace(1,10,3,base2) # 随机 # 可以设置随机数种子 设置玩后可以获取一下一般记在心里 torch.manual_seed(666) # 获取 返回了随机数种子 rtorch.initial_seed() # 生成随机张量 rand真随机 randn随机出来来的符合标准正态分布 靠近中心的要大点 t4torch.rand(10,5) # print(t4) # 自己设置一个正太分布 来随机生成 传入均值和方差 和形状 t5torch.normal(2,1,(3,3)) print(t5) # 创建0-1张量 创建指定值张量 创建单位矩阵张量
def zero_one(): # 创建全0 张量 t1torch.zeros(5,5) # print(t1) # 根据其他的tensor的形状来创建全0张量 zeros_like t2torch.rand(2,3) # print(t2) t3torch.zeros_like(t2) # print(t3) # 全1张量 函数名变为ones 也可以like t4torch.ones(5,5) t6torch.ones_like(t2) # print(t6,t4) # 创建指定值张量传入形状和 填充值 t7torch.full((3,3),666) # like t8torch.full_like(t2,666) # print(t7,t8) # 创建单位矩阵张量 因为是方阵传入一个行就行 t9torch.eye(4) print(t9) # dtype 转换
def change_dtype(): t1torch.rand(2,3) # tensor.type(torch数据类型) 返回一个新的 t2t1.type(torch.int8) # 也可以用对应类型的api tensor.对应的api 直接变 跟cuda方法一样 返回一个新的 t3t1.float() # 。。。。。。。。 if __name____main__: # create_tensor() # create_Tensor() # create_line_random_tensor() # zero_one() pass