Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Tensorflow 张量类型变量初始值设定项必须包装在init_范围内或可调用_Tensorflow_Keras - Fatal编程技术网

Tensorflow 张量类型变量初始值设定项必须包装在init_范围内或可调用

Tensorflow 张量类型变量初始值设定项必须包装在init_范围内或可调用,tensorflow,keras,Tensorflow,Keras,我已经为crf损失计算编写了一个自定义keras损失 def myLoss(self,y_true, y_pred): """ Args: y_true: a tensor of shape batch_size X num_labels y_pred: a tensor of shape batch_size X seq_length X num_labels ""&

我已经为
crf
损失计算编写了一个自定义keras损失

def myLoss(self,y_true, y_pred):
    """
    Args:
        y_true: a tensor of shape batch_size X  num_labels 
        y_pred: a tensor of shape batch_size X seq_length X num_labels
        
    """
    with tf.init_scope():
        self.seqlen = tf.constant(self.batch_size, shape=(self.seq_length,))
    log_likelihood, transtion = tfa.text.crf.crf_log_likelihood(y_pred,y_true,self.seqlen )# logits, labels, seq_length
        loss = tf.reduce_sum(-log_likelihood)
    return loss
但上述代码提出了以下问题:

ValueError: Tensor-typed variable initializers must either be wrapped in an init_scope or callable (e.g., `tf.Variable(lambda : tf.truncated_normal([10, 40]))`) when building functions. Please file a feature request if this restriction inconveniences you.

根据错误,我尝试用
init\u scope
包装张量计算,但不确定这是否正确。建议?

我面临着类似的问题,但背景不同。使变量初始值设定项可调用对我来说很有用。 在这样调用代码中的
self.seqlen
之前,只需添加一个
lambda
,看看它是否有效:

tfa.text.crf.crf_log_likelihood(y_pred, y_true, lambda: self.seqlen)

有解决办法吗?同样的问题。@Saeed你找到解决方案了吗?我在第行遇到了同样的错误:self.add_weight(name='gain',shape=(weight.shape[-1],),initializer=“one”,trainable=True,dtype=self.dtype)如何在lambda中输入“one”呢?试着做:initializer=lambda:tf.one(tf.shape(weight))