Pytorch系列-torch基础

Tensors

属性含义
is_tensor是不是一个PyTorch tensor
is_storage是不是一个PyTorch storage object
is_complex是不是一个复数: torch.complex64, torch.complex128
is_floating_point是不是浮点类型: torch.float64, torch.float32, torch.float16
is_nonzero是不是非零
set_default_dtype设置数据类型
get_default_dtype获取数据类型torch.dtype
set_default_tensor_type设置torch.Tensor为什么类型
numel返回元素个数
set_printoptions打印的选项
set_flush_denormal禁用CPU上的非正常浮点数

创建操作

随机创建一个张量,包括:

torch.rand(*size) # [0,1)
torch.rand_like(input) # 输出与input大小一样的[0,1)之间随机张量
torch.randint(low=0,high,size) # 给定范围内的整数张量
torch.randint_like(input, low=0, high)
torch.randn(*size) # 均值0,标准差1
torch.randn_like(input)
torch.randperm(n) # 返回一个0~n-1的随机排列

其他创建方式:

torch.tensor(data) # data:array_like
torch.zeros(*size)
torch.zeros_like(input)
torch.ones(*size)
torch.ones_like(input)
torch.empty(*size)
torch.empty_like(input)
torch.empty_strided(size, stride) # 相当于torch.empty(size).as_strided(size, stride)
torch.full(size, fill_value) # tensor中全是fill_value
torch.full_like(input, fill_value)

torch.arange(start=0, end, step=1) # end不会取到
torch.range(start=0, end, step=1) # end会取到
torch.linspace(start, end, steps) # 在start和end之间均匀间隔取出steps个数,end会被取到
torch.logspace(start, end, steps, base=10.0) # 以linspace的方式取出的数作为base的指数

torch.eye(n) # 返回n行的单位阵
torch.complex(real, imag) # 复数
torch.polar(abs, angle) # 极坐标

torch.heaviside(input, values) # input<0,return 0; input==0, reutrn values; input>0, return 1
# 构建一个稀疏矩阵,大小为size,indices是用来给定矩阵中点的坐标的,只有这些点是非0的,其值在values中
torch.sparse_coo_tensor(indices,values,size=None,*,dtype=None,device=None,requires_grad=False)
# 将data转为tensor,如果data是同类型同设备的tensor或numpy array,则不会创建新的数据,只是多个名称
torch.as_tensor(data, dtype=None, device=None)

# 从ndarray构建tensor,是共享内存的
torch.from_numpy(ndarray)
# 从input中按照给定参数采样
torch.as_strided(input, size, stride, storage_offset=0) 

看不懂的:

torch.quantize_per_tensor(input, scale, zero_point, dtype)
torch.quantize_per_channel(input, scales, zero_points, axis, dtype)
torch.dequantize(tensor)

Indexing, Slicing, Joining, Mutating Ops

拼接

torch.cat(tensors, dim=0) #拼接

torch.dstack(tensors) # 必须都是三维张量,否则会先对输入执行torch.atleast_3d(),然后在最后一个维度上相加

torch.hstack(tensors) # 在列上合并张量,如果是一维的,则在0维上拼接;否在在1维上拼接

torch.stack(tensors, dim=0) # 在一个新的维度上拼接张量

torch.vstack(tensors) # 在0维拼接

切割

torch.chunk(input, chunks, dim=0) # 把一个tensor切割成几部分,最后一部分可能会少一些

torch.split(tensor, split_size_or_sections, dim=0) # split_size_or_sections可以为整数,表示分成几个部分,最后一块可能小;可以为list,表示每个部分大小

维度操作

torch.movedim(input, source, destination) # 交换维度,source和dest都可以是元组

torch.transpose(input, dim0, dim1) # 交换维度

torch.squeeze(input) # 把所有为1的维度删掉

torch.t(input) # 要求输入二维以下,转置

torch.unsqueeze(input, dim) # 在位置dim加一个维度

torch.unbind(input, dim=0) # 将dim这个维度删除,返回dim个元素的元组

分片,索引

torch.index_select(input, dim, index) # 在指定维度上取分片

torch.narrow(input, dim, start, length) # 就是在dim上取分片

torch.nonzero(input) # 返回非0值的索引

torch.take(input, index) # 返回index位置数字,把input看作一维张量
torch.gather(input, dim, index)

如果input是一个三维张量,dim==0,则 o u t [ i ] [ j ] [ k ] = i n p u t [ i n d e x [ i ] [ j ] [ k ] ] [ j ] [ k ] out[i][j][k] = input[index[i][j][k]][j][k] out[i][j][k]=input[index[i][j][k]][j][k],就是dim的那个维度用index中对应位置的值作为索引。举例:

>>> t = torch.tensor([[1,2],[3,4]])
>>> torch.gather(t, 1, torch.tensor([[0,0],[1,0]]))
tensor([[ 1,  1],
        [ 4,  3]])

其他

torch.reshape(input, shape)

torch.masked_select(input, mask) # mask是跟input大小相同的一个bool类型矩阵,取出True对应的数字,返回一维张量

torch.where(condition, x, y) # if condition, x; else,y

Generator

torch.Generator(device='cpu')

属性:
device:在哪张卡上

functions:

get_state() # 返回一个torch.ByteTensor

initial_seed()int

manual_seed(seed) → Generator # 设置随机数种子,建议是一个好大的数字

seed()int # 返回一个随机数,并将其作为种子

set_state(new_state) → void # 就是get_state的那种state

随机抽样

torch.seed()int

torch.manual_seed(seed) → torch._C.Generator

torch.initial_seed()int

torch.get_rng_state() → torch.Tensor

torch.set_rng_state(new_state)None

torch.bernoulli(input, *, generator=None, out=None) → Tensor # input必须是[0,1]之间的,随机得到相同大小的0/1张量

这部分太无聊了,再说吧。。。

序列化

torch.save(obj, f: Union[str, os.PathLike, BinaryIO], pickle_module=pickle, pickle_protocol=2, _use_new_zipfile_serialization=True)None

torch.load(f, map_location=None, pickle_module=pickle, **pickle_load_args)

保存tensor或io.BytesIO()
加载的时候用torch.load()

平行

torch.get_num_threads()int

torch.set_num_threads(int)

torch.get_num_interop_threads()int # CPU上交互操作的线程数

torch.set_num_interop_threads(int)

局部禁用梯度

with torch.no_grad():
	# 这里产生的张量都是没有梯度的

with torch.enable_grad():
	# 打开梯度

with torch.autograd.set_grad_enabled(mode: bool):
	# 控制梯度的开关

数学计算

逐点的

torch.abs(input)
torch.absolute(input)

torch.acos(input) # arccos
torch.arccos(input)
torch.asin(input) # arcsin
torch.arcsin(input)
torch.atan(input)
torch.arctan(input)
torch.atan2(input, other) # arctan(input/other)

torch.acosh(input) # 反双曲余弦函数
torch.arccosh(input)
torch.asinh(input)
torch.arcsinh(input)
torch.atanh(input)
torch.arctanh(input)

torch.add(input, other, alpha=1) # out=input+alpha*other

torch.addcdiv(input, tensor1, tensor2, value=1) # out=input+value*tensor1/tensor2

torch.addcmul(input, tensor1, tensor2, value=1) # out=input+value*tensor1*tensor2

torch.angle(input)

torch.bitwise_not(input) # 在位上取not
torch.bitwise_and(input, other)
torch.bitwise_or(input, other)
torch.bitwise_xor(input, other)

torch.ceil(input)

torch.clamp(input, min, max) # <min取min,>max取max
torch.clip(input, min, max) # 同上

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值