#例 x= 10 a = [1, 2, 3, 4] a = [i+x for i in a] print(a) #输出:[11, 12, 13, 14]tf.pad()的使用方法
在官方文档中,是这么描述的
tf.pad(tensor, paddings, mode='CONSTANT', constant_values=0, name=None)
关键参数为:
tensor:输入
paddings:padding大小
mode:padding模式
其中padding应该为每一个维度前后需要padding的数量,具体看下面例子
t=[
[[2,3,4],[5,6,7]],
[[2,3,4],[5,6,7]]
]
t = tf.constant(t)
print(t.shape)
print(tf.pad(t,[[0,0],[1,2],[3,4]],"CONSTANT"))
#输出为:
(2, 2, 3)
tf.Tensor(
[[[0 0 0 0 0 0 0 0 0 0]
[0 0 0 2 3 4 0 0 0 0]
[0 0 0 5 6 7 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]]
[[0 0 0 0 0 0 0 0 0 0]
[0 0 0 2 3 4 0 0 0 0]
[0 0 0 5 6 7 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]]], shape=(2, 5, 10), dtype=int32)
第一个维度对应的是[0,0],所以没有进行padding;
第二个维度(也就是行这一维)对应[1,2],也就是在上面一行,下面两行;
第三个维度(也就是列这一维)对应[3,4],也就是在左面三行,右面四行。
可以直接将数组扩大一个维度,如下例:
import numpy as np a = np.array([1., 2., 1.]) print(a.shape) a = a[:,None] print(a.shape) print(a) #输出: (3,) (3, 1) [[1.] [2.] [1.]] 数组a从三个元素的一维数组变成了三行一列的二维数组
以此类推可以得到的是:
import numpy as np a = np.array([1., 2., 1.]) b = a[:,None] b = a[:,None]*a[None,:] b = b[None,None,:,:] print(b.shape) print(b) #输出: (1, 1, 3, 3) [[[[1. 2. 1.] [2. 4. 2.] [1. 2. 1.]]]]方法.repeat()的使用
.repeat(repeats, axis)
repeats:重复的次数
axis:需要重复的维度
例:
import numpy as np a = np.array([1., 2., 1.]) b = a[:,None] b = a[:,None]*a[None,:] c = b[None,None,:,:].repeat(3,axis=0) print(b[None,None,:,:].shape) print(c.shape) print(c) #输出: (1, 1, 3, 3) (3, 1, 3, 3) [[[[1. 2. 1.] [2. 4. 2.] [1. 2. 1.]]] [[[1. 2. 1.] [2. 4. 2.] [1. 2. 1.]]] [[[1. 2. 1.] [2. 4. 2.] [1. 2. 1.]]]]



