Tensorflow 小知识点 shape get_shape() cond placeholder tf.gradients

name_scope || variable_scope
TensorFlow入门(七) 充分理解 name / variable_scope
tensorflow: 对variable_scope进行reuse的两种方法
TensorFlow基础:共享变量

tf.shape (tensor) || tensor.get_shape()
tensor.get_shape() 返回的是元组,元祖是python中的类型
tf.shape()返回的是tensor,tensor是tensorflow中类型
二者最大区别在于get_shape是静态的,也就是在建图的过程中有些tensor的某些维度已经推算出来了,这时我们需要使用这些维度时,可以使用静态方法获得。tf.shape是动态的,也就是它其实是tensorflow图中一个ops,tensor的维度是在运算时获得的,典型的比如batch大小。用法:

keys_len = tf.shape(keys)[1]
hidden_units = query.get_shape().as_list()[-1]

我们常见的问题“The last dimension of the inputs to Dense should be defined. Found None.”一般需要都是因为维度不确定导致的。需要我们使用静态方法显示说明。

cond placeholder:
不要使用tf.placeholder(tf.bool, [], name=‘req_type’),生成的shape有问题。

"req_type": tf.placeholder(tf.bool, name='req_type')
embedding = tf.cond(req_type, req_bert, req_img)

测试梯度
不要使用int变量
如何理解TensorFlow中的IndexedSlices类?

#encoding: utf8
import tensorflow as tf

sess = tf.Session()

values = tf.constant([10.0,20.0,30.0,40.0])
ids = tf.constant([1,3])
masks = tf.constant([False,True,False,True])

# total = values * 2
# total = tf.where(masks, values, tf.zeros_like(values))  # False处的梯度为0
# total = tf.boolean_mask(values, masks)  # False处的梯度为0
total = tf.nn.embedding_lookup(values,ids)   # 非索引处不回传梯度,要实现对一个tensor中部分值不回传梯度,需产生IndexedSlices类型的产出
# total = tf.stop_gradient(total) # stop后不回传梯度

total *= total
total = tf.reduce_sum(total)
grad = tf.gradients(total, values)

print(values, grad)
print(sess.run([total, grad]))

stop后不同位置求导的差异性

import tensorflow as tf

sess = tf.Session()

@tf.custom_gradient
def assign_by_updating_value_and_gradient(x, y):
  def grad(dy):
    return y, None
  return y, grad

a = tf.constant([[1.,2]])
b = tf.constant([[3.,4]])

c = assign_by_updating_value_and_gradient(a,b)
d = tf.stop_gradient(c)

print(tf.gradients(c, [a,b]))  //[<tf.Tensor 'Const_1:0' shape=(1, 2) dtype=float32>, None]
print(tf.gradients(d, [a,b]))  //[None, None]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值