基于tensorflow 1.12
常用API
-
tf.expand_dims(tensor, dim=2) # 扩展纬度
-
tf.tile(tensor, multiples=[1,1,5]) # 将第三纬度复制u5倍
-
tf.multiply(data1, data2) # 按位相乘
-
tf.cast([1,2], dtype=tf.float64) # 类型转换
-
data.get_shape().as_list() # 得到data的shape
-
tf.reduce_sum(data, axis=1, keep_dims=True) # 对纬度1求和
-
data.eval() # 查看tensor的值
-
tf.where(tf.cast(mask, tf.bool), data, -tf.ones_like(data) * np.inf) # 将mask为0的未知填充-inf,用于求max
-
tf.cast(tf.constant([1, 2, 3]), dtype=tf.float32) # 类型转换
-
打印卷积的shape的权重
import tensorflow as tf
with tf.variable_scope(“generate”):
with tf.variable_scope(“resnet_stack”):
#简单起见,这里没有用第三方库来说明,
bias = tf.Variable(0.0,name=“bias”)
weight = tf.Variable(0.0,name=“weight”)
for tv in tf.trainable_variables():
print (tv.name)
b = tf.get_default_graph().get_tensor_by_name(“generate/resnet_stack/bias:0”)
w = tf.get_default_graph().get_tensor_by_name(“generate/resnet_stack/weight:0”)
with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(b))
print(sess.run(w))
参考:https://blog.csdn.net/cassiePython/article/details/79179044 -
tensorflow.contrib.layers.conv2d 的padding
有same和valid两种取值,如果是valid则不padding,原长度会缩小;
如果是same,则是padding 0,如果需要padding的个数是n,那么在左边pad的数目是n//2,右边pad的数目是n - n//2(注意n为奇数时的区别) -
layers.dropout(embed, keep_prob=(1.0 - opt.dropout_p), is_training=opt.training)
-
交互式session:
tf.InteractiveSession()
14、打印当前的tensor的值
a = tf.constant(np.random.random([2, 3, 4]))
tf.Session().run(a) -
reshape
a = tf.constant(np.random.random([2, 3, 4]))
b=tf.reshape(a, [6,4]) -
tf.sign(x)
元素宽度的比较,如果元素>0设置为1,等于0或者为nan设置0,<0设置为-1 -
tf.gather() #用一个一维的索引数组,将张量中对应索引的向量提取出来
import tensorflow as tf a = tf.Variable([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]]) index_a = tf.Variable([0,2]) b = tf.Variable([1,2,3,4,5,6,7,8,9,10]) index_b = tf.Variable([2,4,6,8]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(tf.gather(a, index_a))) print(sess.run(tf.gather(b, index_b))) # [[ 1 2 3 4 5] # [11 12 13 14 15]] # [3 5 7 9]
-
取矩阵对角线元素
tf.matrix_band_part tf.linalg.band_part(新接口) matrix_band_part( input, num_lower, num_upper, name=None ) 表示以对角线为中心,分别向下三角和上三角取宽度num_lower和num_upper宽度的带状向量。当num_lower和num_uppwer为0时,就是取的对角线元素
18、tf.scatter_nd(indices, updates, shape)
tf.gather的逆操作函数,创建一个形状为shape的零张量,将updates赋值到indices指定的位置。
indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
shape = tf.constant([8])
scatter = tf.scatter_nd(indices, updates, shape)
with tf.Session() as sess:
print(sess.run(scatter))
# 输出
[0, 11, 0, 10, 9, 0, 0, 12]
19、tf.where(a>0):获取a中大于0的元素的索引
tensorboard使用
- tensorboard --logdir checkpoint/model_test --host=xx.xx.xxx.xx --port=8899
可能会报 /lib64/libc.so.6: version `GLIBC_2.16’ not found的错误
tensorboard这个命令本身是要给python文件,可以用:
python ./tensorboard --logdir checkpoint/model_test --host=xx.xx.xxx.xx --port=8899