tile & repeat
tf.tile
tile() 平铺之意,用于在同一维度上的复制
tile(
input, #输入
multiples, #同一维度上复制的次数
name=None
)
with tf.Graph().as_default():
a = tf.constant([[1,2],[3,4]],name='a')
b = tf.tile(a,[2,3])
sess = tf.Session()
print(sess.run(b))
输出:
[[1 2 1 2 1 2]
[3 4 3 4 3 4]
[1 2 1 2 1 2]
[3 4 3 4 3 4]]
torch.repeat
x = torch.tensor([1, 2, 3])
x.repeat(4, 2)
tensor([[ 1, 2, 3, 1, 2, 3],
[ 1, 2, 3, 1, 2, 3],
[ 1, 2, 3, 1, 2, 3],
[ 1, 2, 3, 1, 2, 3]])
x.repeat(4, 2, 1).size()
torch.Size([4, 2, 3])
reshape
tf.reshape torch.reshape
tf.reshape(tensor,shape,name=None)
shape = [-1,1] 表示将所有的行元素转换为列元素。
tensor中元素个数和shape的每维的数值相乘值应该相等。
https://blog.csdn.net/m0_37592397/article/details/78695318
reduce_sum & sum
tf.reduce_sum
tf.reduce_sum(
input_tensor,
axis=None,
keepdims=None,
name=None,
reduction_indices=None,
keep_dims=None)
input_tensor:待求和的tensor;
axis:指定的维,如果不指定,则计算所有元素的总和;
keepdims:是否保持原有张量的维度,设置为True,结果保持输入tensor的形状,设置为False,结果会降低维度,如果不传入这个参数,则系统默认为False;
name:操作的名称;
reduction_indices:在以前版本中用来指定轴,已弃用;
keep_dims:在以前版本中用来设置是否保持原张量的维度,已弃用;
按照维数求和
类似的还有
tf.reduce_mean():计算tensor指定轴方向上的所有元素的累加和;
tf.reduce_max():计算tensor指定轴方向上的各个元素的最大值;
tf.reduce_all():计算tensor指定轴方向上的各个元素的逻辑和(and运算);
tf.reduce_any():计算tensor指定轴方向上的各个元素的逻辑或(or运算);
torch.sum
gather
tf.gather
tf.gather(params,indices,axis=0 )
由axis确定维度,按照indices列表对整个维度如每列或者每行进行切片操作。
torch.gather
torch.gather(t, 0, index)
pytorch的gather的用法: 与原张量的维度必须一致,除了dim维度之外,其他维度的size也必须保持相同 。
max
torch.max 与 tf.maxinum
torch.max()当输入是两个大小相同的tensor时,则为两个tensor内元素依次比较大小,然后输出包含较大值的tensor。与tf.maxinum()功能相同。
问题
torch.min()返回值
torch.min 返回类型为 torch.return_types.min 包含了原始的tensor与最小值对应的位置
将torch.return_types.min 的list 转换为 tensor
torch.return_types.min包含了values与index标记最小值,与最小值所在维度的位置。对应类型报错,我们可以直接使用name.values调出torch.return_types.min中存的最小值tensor值。
torch.return_types.max类似,也是一样的。
temp2 = torch.min(torch.abs(temp), 0)
min_list.append(temp2)
mins = torch.stack([x.values for x in min_list])
Pytorth GPU测试内存溢出
对于不需要 bp 的 forward,如 validation,test 请使用 torch.no_grad(),注意 model.eval() 不等于 torch.no_grad()。
model.eval()将通知所有图层您处于 eval 模式,这样,batch norm 或 dropout 图层将在 eval 模式下而不是训练模式下工作。torch.no_grad()影响 autograd 并将其停用。 它将减少内存使用量并加快计算速度,无法进行反向传播 ( 在 eval 脚本中不需要 ) 。
代码如下:
model.eval()
with torch.no_grad():
#这里放测试程序,不会导致内存溢出