pytorch tensor操作总结

avatar
作者
筋斗云
阅读量:5

PyTorch 提供了许多与张量(tensor)相关的操作。这些操作可以分类为创建、索引、变形、数学运算、逻辑运算、随机数生成等。以下是详细列举的 PyTorch 有关张量的操作:

创建张量
torch.tensor(data): 从数据创建张量
torch.zeros(size): 创建全零张量
torch.ones(size): 创建全一张量
torch.arange(start, end, step): 创建从 start 到 end,步长为 step 的序列张量
torch.linspace(start, end, steps): 创建从 start 到 end 的等间隔张量
torch.eye(n): 创建 n x n 单位矩阵
torch.empty(size): 创建未初始化的张量
torch.full(size, fill_value): 创建填充指定值的张量
torch.rand(size): 创建形状为 size 的均匀分布的随机张量
torch.randn(size): 创建形状为 size 的标准正态分布的随机张量
torch.randint(low, high, size): 创建从 low 到 high 的整数随机张量
torch.normal(mean, std, size): 创建正态分布的随机张量
索引和切片
tensor[index]: 索引张量
tensor[start:end]: 切片张量
tensor[…, index]: 使用省略号索引张量
tensor.index_select(dim, index): 按指定索引选择张量
tensor.gather(dim, index): 从张量中收集元素
变形操作
tensor.view(shape): 改变张量形状
tensor.reshape(shape): 改变张量形状
tensor.transpose(dim0, dim1): 转置张量
tensor.permute(dims): 置换张量的维度
tensor.unsqueeze(dim): 在指定维度增加维度
tensor.squeeze(dim): 删除指定维度
tensor.flatten(start_dim, end_dim): 扁平化张量
tensor.repeat(*sizes): 重复张量
数学运算
torch.add(a, b): 加法
torch.sub(a, b): 减法
torch.mul(a, b): 乘法
torch.div(a, b): 除法
torch.matmul(a, b): 矩阵乘法
torch.mm(a, b): 矩阵乘法
torch.bmm(a, b): 批量矩阵乘法
torch.t(a): 转置矩阵
torch.dot(a, b): 点积
torch.cross(a, b): 叉积
torch.norm(tensor): 范数
torch.sum(tensor, dim): 求和
torch.mean(tensor, dim): 平均值
torch.median(tensor, dim): 中位数
torch.max(tensor, dim): 最大值
torch.min(tensor, dim): 最小值
torch.cumsum(tensor, dim): 累加和
torch.cumprod(tensor, dim): 累乘积
逻辑运算
torch.eq(a, b): 相等
torch.ne(a, b): 不相等
torch.gt(a, b): 大于
torch.ge(a, b): 大于等于
torch.lt(a, b): 小于
torch.le(a, b): 小于等于
torch.logical_and(a, b): 逻辑与
torch.logical_or(a, b): 逻辑或
torch.logical_not(a): 逻辑非
torch.logical_xor(a, b): 逻辑异或
随机数生成
torch.manual_seed(seed): 设置随机种子
torch.bernoulli(tensor): 伯努利分布
torch.multinomial(tensor, num_samples): 多项式分布
torch.normal(mean, std): 正态分布
torch.poisson(tensor): 泊松分布
torch.rand(size): 均匀分布
torch.randn(size): 标准正态分布
torch.randint(low, high, size): 整数均匀分布
其他操作
torch.cat(tensors, dim): 沿指定维度连接张量
torch.stack(tensors, dim): 沿新维度堆叠张量
torch.split(tensor, split_size_or_sections, dim): 拆分张量
torch.chunk(tensor, chunks, dim): 分块张量
torch.clone(tensor): 克隆张量
torch.masked_select(tensor, mask): 按掩码选择张量
torch.nonzero(tensor): 非零元素的索引
torch.where(condition, x, y): 按条件选择张量
torch.topk(tensor, k, dim): 取前 k 个元素
torch.sort(tensor, dim): 排序张量
torch.argsort(tensor, dim): 排序索引
torch.unique(tensor): 唯一元素
torch.scatter(dim, index, src): 按索引填充张量
torch.index_add(dim, index, tensor): 按索引加法
这些操作涵盖了 PyTorch 中张量操作的大部分内容,每个操作都有其特定的用途,可以根据需求选择合适的操作。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!