import tensorflow as tf
import numpy as np
def entry_stop_gradients(target, mask):
mask_h = tf.abs(mask-1)
return tf.stop_gradient(mask_h * target) + mask * target
mask = np.array([1., 0, 1, 1, 0, 0, 1, 1, 0, 1])
mask_h = np.abs(mask-1)
emb = tf.constant(np.ones([10, 5]))
matrix = entry_stop_gradients(emb, tf.expand_dims(mask,1))
parm = np.random.randn(5, 1)
t_parm = tf.constant(parm)
loss = tf.reduce_sum(tf.matmul(matrix, t_parm))
grad1 = tf.gradients(loss, emb)
grad2 = tf.gradients(loss, matrix)
print matrix
with tf.Session() as sess:
print sess.run(loss)
print sess.run([grad1, grad2])
上面的代码出了什么问题?如果function formatToStandardizedDate(from, to){
const from_date = moment(from);
if(to){
let to_date = moment(to);
}else{
let to_date = null;
}
}
console.log(formatToStandardizedDate("2017-04-19 00:00:00",null))
为空,则至少为to
分配一个空值,但我得到了to_date
未定义错误的错误。为什么呢?
答案 0 :(得分:6)
您不能对let关键字使用相同的变量名称。如果你试图这样做会抛出错误。
相反,你必须使用三元运算符:
let to_date = to ? moment(to) : null;
或在函数上面声明一次并更新变量
function formatToStandardizedDate(from, to){
const from_date = moment(from);
let to_date = null; // initialize the variable with null
if(to)
to_date = moment(to); // <---here update the variable with new value.
}
根据JaredSmith的评论进行了更新,这似乎很好。