tensorflow内置函数与pytorch内置函数的对应 --- 持续更新

pytorch与tensorflow API速查表

方法名称 pytroch tensorflow numpy
裁剪 torch.clamp(x, min, max) tf.clip_by_value(x, min, max) np.clip(x, min, max)
取最大值 torch.max(x, dim)[0] tf.max(x, axis) np.max(x, axis)
取最小值 torch.min(x, dim)[0] tf.min(x, axis) np.min(x , axis)
取两个tensor的最大值 torch.max(x, y) tf.maximum(x, y) np.maximum(x, y)
取两个tensor的最小值 torch.min(x, y) torch.minimum(x, y) np.minmum(x, y)
取最大值索引 torch.max(x, dim)[1] tf.argmax(x, axis) np.argmax(x, axis)
取最小值索引 torch.min(x, dim)[1] tf.argmin(x, axis) np.argmin(x, axis)
比较(x > y) torch.gt(x, y) tf.greater(x, y) np.greater(x, y)
比较(x < y) torch.le(x, y) tf.less(x, y) np.less(x, y)
比较(x==y) torch.eq(x, y) tf.equal(x, y) np.equal(x, y)
比较(x!=y) torch.ne(x, y) tf.not_equal(x, y) np.not_queal(x , y)
取符合条件值的索引 torch.nonzero(cond) tf.where(cond) np.where(cond)
多个tensor聚合 torch.cat([x, y], dim) tf.concat([x,y], axis) np.concatenate([x,y], axis)
堆叠成一个tensor torch.stack([x1, x2], dim) tf.stack([x1, x2], axis) np.stack([x, y], axis)
tensor切成多个tensor torch.split(x1, split_size_or_sections, dim) tf.split(x1, num_or_size_splits, axis) np.split(x1, indices_or_sections, axis)
torch.unbind(x1, dim) tf.unstack(x1,axis) NULL
随机扰乱 torch.randperm(n)1 tf.random_shuffle(x) np.random.shuffle(x)2 np.random.permutation(x)3
前k个值 torch.topk(x, n, sorted, dim) tf.nn.top_k(x, n, sorted) NULL

  1. 该方法只能对0~n-1自然数随机扰乱,所以先对索引随机扰乱,然后再根据扰乱后的索引取相应的数据得到扰乱后的数据 ↩︎

  2. 该方法会修改原值,没有返回值 ↩︎

  3. 该方法不会修改原值,返回扰乱后的值 ↩︎

TensorFlow - tf.matmul 函数 & Pytorch - torch.matmul 或 bmm

# 多维tensor相乘

## 只能用于三维tensor相乘的
### 这个函数不支持广播,也就是第一维必须相同,另外两维符合矩阵相乘法则
c = torch.bmm(a, b)

## 可以用于任意多维的tensor相乘
### 支持广播,当两个都是一维时,表示点积
c = torch.matmul(a, b)

参考:[Pytorch和Tensorflow对比(一)]:乘法、正则化

TensorFlow - tf.reshape 函数 & Pytorch - torch.view函数

TensorFlow - tf.reshape 函数 & Pytorch - torch.reshape 函数

TensorFlow

tf.reshape( tensor, shape:[int, …], name=None )

Pytorch

torch.reshape(self: Tensor, shape: Tuple[int, …])

TensorFlow - tf.concat 函数 & Pytorch - torch.cat 函数

TensorFlow

tf.concat( values, axis, name = ‘concat’ )
T1 = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ]
T2 = [ [ 7 , 8 , 9 ] , [ 10 , 11 , 12 ] ]
tf.concat([T1 ,T2] ,0) == > [[1 , 2 ,3 ],[4 ,5 ,6],[7 ,8 ,9],[10 ,11,12]]

Pytorch

torch.cat((A,B),0)

TensorFlow - tf.abs 函数 &

tf.abs 是针对张量的每一位的元素分别计算其绝对值,并输出原格式的新张量。

TensorFlow - tf.expand_dims 函数 &

与torch.unsqueeze对应

TensorFlow - tf.less 函数 &

torch.le same as torch.ge — >=
torch.lt same as torch.gt — >
与torch.min相同的是,其均是用来比较两个张量每一位元素的最小值,不同的是tf.less输出的是是否为最小值的bool值,torch.min是输出两元素中的最小值并重新组合成张量。
返回值: 一个 torch.ByteTensor 张量,包含了每个位置的比较结果(是否 input >= other )。 返回类型: Tensor

torch.le(input, other, out=None) -> Tensor:

逐元素比较input和other,即是否input <= other,第二个参数可以为一个数或与第一个参数相同形状和类型的张量。

torch.lt(input, other, out=None) -> Tensor:

逐元素比较input和other,即是否input < other

TensorFlow - tf.equal 函数 &

torch.equal
torch.eq

torch.eq(input, other, out=None) -> Tensor:

比较元素相等性,第二个参数可为一个数,或与第一个参数同类型形状的张量

input(Tensor) - 待比较张量
other(Tensor or float) - 比较张量或数
out(Tensor, optional) - 输出张量,须为ByteTensor类型或与input同类型

torch.equal(tensor1, tensor2) -> bool:

若两个张量有相同的形状和元素值,则返回True, 否则False。

TensorFlow - tf.greater_equal 函数 &

torch.ge
torch.gt

torch.ge(input, other, out=None) -> Tensor:

逐元素比较input和other,即是否input >= other
第二个参数可以为一个数或与第一个参数相同形状和类型的张量。

input(Tensor) - 待对比的张量
other(Tensor or float) - 对比的张量或float值
out(Tensor, optional) - 输出张量,必须为ByteTensor或与第一个参数相同类型。

torch.gt(input, other, out=None) -> Tensor:

逐元素比较input和other,是否input > other。若两个张量有相同的形状和元素值,则返回True,否则False。第二个参数
可以为一个数或与第一个参数相同形状和类型的张量。

TensorFlow - tf.norm 函数 & torch.norm

tf.norm
torch.norm

tf.norm 函数

norm(
tensor,
ord=‘euclidean’,
axis=None,
keep_dims=False,
name=None
)

torch.norm(input, p=2) -> float:

返回输入张量input的p范数。

input(Tensor) - 输入张量
p(float, optional) - 范数计算中的幂指数值

torch.norm(input, p, dim, out=None) -> Tensor:

返回输入张量给定维度dim上每行的p范数。

TensorFlow - tf.argmin 函数 & torch.argmin

TensorFlow - tf.gather_nd 函数 &

tf.gather_nd

在 tf.gather 函数中,将片段定义为参数的第一维度;在 tf.gather_nd 中,索引将切片定义为参数的第一个 n 维度.

函数:tf.gather_nd

gather_nd(
params,
indices,
name=None )

参数:

params:张量.这个张量是用来收集数值的.
indices:张量.必须是以下类型之一:int32,int64;索引张量.
name:操作的名称(可选).

返回值:

该函数返回一个张量.与参数具有相同的类型.参数值从索引所给定的索引中收集,并且具有形状:indices.shape[:-1] + params.shape[indices.shape[-1]:]

简单的索引到矩阵:

indices = [[0, 0], [1, 1]]
params = [['a', 'b'], ['c', 'd']]
output = ['a', 'd']

将索引分为矩阵:

indices = [[1], [0]]
params = [['a', 'b'], ['c', 'd']]
output = [['c', 'd'], ['a', 'b']]

索引到一个3-tensor:

indices = [[1]]
params = [[['a0', 'b0'], ['c0', 'd0']],
          [['a1', 'b1'], ['c1', 'd1']]]
output = [[['a1', 'b1'], ['c1', 'd1']]]

indices = [[0, 1], [1, 0]]
params = [[['a0', 'b0'], ['c0', 'd0']],
          [['a1', 'b1'], ['c1', 'd1']]]
output = [['c0', 'd0'], ['a1', 'b1']]

indices = [[0, 0, 1], [1, 0, 1]]
params = [[['a0', 'b0'], ['c0', 'd0']],
          [['a1', 'b1'], ['c1', 'd1']]]
output = ['b0', 'b1']

分批索引到矩阵中:

indices = [[[0, 0]], [[0, 1]]]
params = [['a', 'b'], ['c', 'd']]
output = [['a'], ['b']]

分批切片索引成矩阵:

indices = [[[1]], [[0]]]
params = [['a', 'b'], ['c', 'd']]
output = [[['c', 'd']], [['a', 'b']]]

分批索引到一个 3-tensor:

indices = [[[1]], [[0]]]
params = [[['a0', 'b0'], ['c0', 'd0']],
          [['a1', 'b1'], ['c1', 'd1']]]
output = [[[['a1', 'b1'], ['c1', 'd1']]],
          [[['a0', 'b0'], ['c0', 'd0']]]]

indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]]
params = [[['a0', 'b0'], ['c0', 'd0']],
          [['a1', 'b1'], ['c1', 'd1']]]
output = [[['c0', 'd0'], ['a1', 'b1']],
          [['a0', 'b0'], ['c1', 'd1']]]

indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]]
params = [[['a0', 'b0'], ['c0', 'd0']],
          [['a1', 'b1'], ['c1', 'd1']]]
output = [['b0', 'b1'], ['d0', 'c1']]

目前torch中自带的同类型函数只有torch.gather,用于处理指定一维度,无gather_nd的用法,但开源工具torchsample中则加入了类似的函数th_gather_nd,模仿tensorflow中的使用,详见:

torchsample推荐安装,有点类似于tf中的keras,提供高级api,减少开发时间,实用。

Pytorch的高级训练,数据增强和实用程序(torchsample/Keras)
另外开源社区还有各路大神的野方法,贴上链接:
How to use Tf.gather_nd in pytorch
How to do the tf.gather_nd in pytorch?

TensorFlow - tf.gather 函数 &

tf.gather
torch.gather

根据索引从参数轴上收集切片.
索引必须是任何维度的整数张量 (通常为 0-D 或 1-D).生成输出张量该张量的形状为:params.shape[:axis] + indices.shape + params.shape[axis + 1:]

函数:tf.gather

gather(
params,
indices,
validate_indices=None,
name=None,
axis=0 )

参数:

params:一个张量.这个张量是用来收集数值的.该张量的秩必须至少是 axis + 1.
indices:一个张量.必须是以下类型之一:int32,int64.索引张量必须在 [0, params.shape[axis]) 范围内.
axis:一个张量.必须是以下类型之一:int32,int64.在参数轴从中收集索引.默认为第一个维度.支持负索引.
name:操作的名称(可选).

返回值:

该函数返回一个张量.与参数具有相同的类型.参数值从索引给定的索引中收集而来,
并且形状为:params.shape[:axis] + indices.shape + params.shape[axis + 1:].

torch.gather(input, dim, index, out=None):

沿给定轴dim,将输入索引张量index指定位置的值进行聚合。

input(Tensor) - 源张量
dim(int) - 索引的轴
index(LongTensor) - 聚合元素的下标
out - 目标张量

TensorFlow - tf.shape 函数 &

tf.shape
torch.size

tf.shape 函数

shape(
input,
name=None,
out_type=tf.int32 )

返回某个张量的形状.
此操作返回表示input形状的一维整数张量.

t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
tf.shape(t)  # [2, 2, 3]

函数参数

input:表示一个Tensor或SparseTensor.
name:操作的名称(可选).
out_type:(可选)操作的指定输出类型((int32或int64));默认为tf.int32.

函数返回值

tf.shape 函数会返回out_type类型的Tensor.

TensorFlow - tf.range 函数 & torch.arange

tf.range
torch.arange / torch.range

创建一个数字序列.
创建一个数字序列,该数字开始于 start 并且将 delta 增量扩展到不包括 limit 的序列.
除非明确提供,否则得到的张量的 dtype 是从输入中推断出来的.

tf.range 函数
range(limit, delta=1, dtype=None, name='range')
range(start, limit, delta=1, dtype=None, name='range')

start = 3
limit = 18
delta = 3
tf.range(start, limit, delta)  # [3, 6, 9, 12, 15]

start = 3
limit = 1
delta = -0.5
tf.range(start, limit, delta)  # [3, 2.5, 2, 1.5]

limit = 5
tf.range(limit)  # [0, 1, 2, 3, 4]

torch.arange(start, end, step=1, out=None):

返回一个1维张量,长度为floor((end-start)/step),以step`为步长的一组序列值。

start (float) - 起点
end (float) - 终点(不包含)
step (float) - 相邻点的间隔大小
out (Tensor, optional)

TensorFlow - tf.stack 函数 & torch.stack

tf.stack
torch.stack

torch.stack(sequence, dim=0):

沿着一个新维度对输入张量进行连接,序列中所有张量都应该为相同的形状。

sequence(Sequence) - 待连接的张量序列
dim(int) - 插入的维度

TensorFlow - tf.reduce_mean 函数 & torch.mean

tf.reduce_mean

计算张量的各个维度上的元素的平均值.
axis是tf.reduce_mean函数中的参数,按照函数中axis给定的维度减少input_tensor.除非keep_dims是true,否则张量的秩将在axis的每个条目中减少1.如果keep_dims为true,则缩小的维度将保留为1.

tf.reduce_mean 函数

reduce_mean(
input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None )

如果axis没有条目,则减少所有维度,并返回具有单个元素的张量.
例如:

x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x)  # 1.5
tf.reduce_mean(x, 0)  # [1.5, 1.5]
tf.reduce_mean(x, 1)  # [1.,  2.]

参数:

input_tensor:要减少的张量.应该有数字类型.
axis:要减小的尺寸.如果为None(默认),则减少所有维度.必须在[-rank(input_tensor), rank(input_tensor))范围内.
keep_dims:如果为true,则保留长度为1的缩小尺寸.
name:操作的名称(可选).
reduction_indices:axis的不支持使用的名称.

返回:

该函数返回减少的张量.    
numpy兼容性    
相当于np.mean

torch.mean(input) -> float:

返回输入张量所有元素的均值

torch.mean(input, dim, out=None):

返回输入张量给定维度dim上每行的均值,输出形状与输入相同,除了给定维度上为1。

TensorFlow - tf.cast 函数 &

tf.cast

cast(
x,
dtype,
name=None )

将 x 的数据格式转化成 dtype. 例如,原来 x 的数据格式是 bool,那么将其转化成 float 以后,就能够将其转化成 0 和 1 的序列。反之也可以.

a = tf.Variable([1,0,0,1,1])
b = tf.cast(a,dtype=tf.bool)
sess = tf.Session()
sess.run(tf.initialize_all_variables())
print(sess.run(b)) 

[ True False False  True  True]

torch中没有相似的类型转换函数,直接使用torch.FloatTensor()或data.float()类似的进行转换就可以了。

TensorFlow - tf.count_nonzero 函数 & torch.nonzero

count_nonzero(
input_tensor,
axis=None,
keep_dims=False,
dtype=tf.int64,
name=None,
reduction_indices=None
)

计算并输出各个维度上非0元素的个数。

TensorFlow - tf.tile 函数 & Tensor.repeat()

tf.tile
torch.Tensor.repeat
通过平铺(tile)给定的张量来构造张量.

此操作通过复制 input multiples 时间来创建新的张量.输出张量的第 i 维具有 input.dims(i) * multiples[i] 元素,并且沿着 ‘i’ 维度 input 值被复制 multiples[i] 次.例如,[a b c d] 由 [2] 平铺将得到 [a b c d a b c d].

函数参数:

input:一个 Tensor,1-D或更高.
multiples:一个 Tensor,必须是以下类型之一:int32,int64,它是 1-d,长度必须与 input 中的维度数量相同.
name:操作的名称(可选).

函数返回值:

tf.tile函数返回一个 Tensor,与 input 具有相同的类型.

tf.tile函数

tf.tile(
input,
multiples,
name=None )

repeat 相当于一个broadcasting的机制

repeat(*sizes)

沿着指定的维度重复tensor。不同与expand(),本函数复制的是tensor中的数据。

import torch
import torch.nn.functional as F
import numpy as np
a = torch.Tensor(128,1,512)
B = a.repeat(1,5,1)
print(B.shape)

torch.Size([128, 5, 512])

Tensorflow tf.where & torch.le / torch.lt

tf.where
torch.le
torch.lt

tf.where(

condition,
x=None,
y=None,
name=None
)

根据condition返回x或y中的元素.

如果x和y都为None,则该操作将返回condition中true元素的坐标.坐标以二维张量返回,其中第一维(行)表示真实元素的数量,第二维(列)表示真实元素的坐标.请记住,输出张量的形状可以根据输入中的真实值的多少而变化.索引以行优先顺序输出.

如果两者都不是None,则x和y必须具有相同的形状.如果x和y是标量,则condition张量必须是标量.如果x和y是更高级别的矢量,则condition必须是大小与x的第一维度相匹配的矢量,或者必须具有与x相同的形状.

condition张量作为一个可以选择的掩码(mask),它根据每个元素的值来判断输出中的相应元素/行是否应从 x (如果为 true) 或 y (如果为 false)中选择.

如果condition是向量,则x和y是更高级别的矩阵,那么它选择从x和y复制哪个行(外部维度).如果condition与x和y具有相同的形状,那么它将选择从x和y复制哪个元素.

函数参数:

condition:一个bool类型的张量(Tensor).
x:可能与condition具有相同形状的张量;如果condition的秩是1,则x可能有更高的排名,但其第一维度必须匹配condition的大小.
y:与x具有相同的形状和类型的张量.
name:操作的名称(可选).

返回值:

如果它们不是None,则返回与x,y具有相同类型与形状的张量;张量具有形状(num_true, dim_size(condition)).

可能引发的异常:

ValueError:当一个x或y正好不是None.

orch.le(input, other, out=None) -> Tensor:

逐元素比较input和other,即是否input <= other,第二个参数可以为一个数或与第一个参数相同形状和类型的张量。

torch.lt(input, other, out=None) -> Tensor:

逐元素比较input和other,即是否input < other

Tensorflow tf.nn.in_top_k

tf.nn.in_top_k组要是用于计算预测的结果和实际结果的是否相等,返回一个bool类型的张量,tf.nn.in_top_k(prediction, target, K):prediction就是表示你预测的结果,大小就是预测样本的数量乘以输出的维度,类型是tf.float32等。target就是实际样本类别的标签,大小就是样本数量的个数。K表示每个样本的预测结果的前K个最大的数里面是否含有target中的值。一般都是取1。

#例如:

import tensorflow as tf;

A = [[0.8,0.6,0.3], [0.1,0.6,0.4]]
B = [1, 1]
out = tf.nn.in_top_k(A, B, 1)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print sess.run(out) 

#输出:
[False  True]

参考:https://blog.csdn.net/qq_29617883/article/details/100179328

pytorch与tensorflow API速查表

猜你喜欢

转载自blog.csdn.net/dou3516/article/details/109181203