2017-07-25 78 views
2

我試圖在Tensorflow中創建一個dice_loss函數。 我正面臨着張量模式的麻煩。執行以下代碼ValueError:在Tensorflow中沒有爲任何變量提供漸變

import tensorflow as tf 
import tensorlayer as tl 


def conv3d(x, inChans, outChans, kernel_size, stride, padding): 
    weights = weight_variable([kernel_size, kernel_size, kernel_size, inChans, outChans]) 
    biases = bias_variable([outChans]) 
    conv = tf.nn.conv3d(x, weights, strides=[1, stride, stride, stride, 1], padding=padding) 
    return tf.nn.bias_add(conv, biases) 

def train(loss_val, var_list): 
    optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate) 
    grads = optimizer.compute_gradients(loss_val, var_list=var_list) 
    return optimizer.apply_gradients(grads) 


def main(argv=None): 
    image = tf.placeholder(tf.float32, shape=[None, SLICE_SIZE, IMAGE_SIZE, IMAGE_SIZE, 1], name="input_image") 
    annotation = tf.placeholder(tf.float32, shape=[None, SLICE_SIZE, IMAGE_SIZE, IMAGE_SIZE, 1], name="annotation") 

    logits, pred_annotation = vnet.VNet(image) 
    loss = 1 - tl.cost.dice_coe(output=pred_annotation, target=annotation, axis=[1,2,3,4]) 

    trainable_var = tf.trainable_variables() 
    train_op = train(loss, trainable_var) 

    sess = tf.Session() 
    ... 

    ... 

def VNet(x): 
    ... 
    out = tf.nn.elu(BatchNorm3d(conv3d(x, inChans, 2, kernel_size=5, stride=1, padding="SAME"))) 
    out = conv3d(out, 2, 2, kernel_size=1, stride=1, padding="SAME") 
    annotation_pred = tf.to_float(tf.argmax(out, dimension=4, name='prediction')) 
    return out, tf.expand_dims(annotation_pred, dim=4) 

我得到以下錯誤:

ValueError異常:目前沒有任何變量梯度:...

有人能幫助我嗎?

+0

有沒有足夠的代碼來解決它...你怎麼稱呼你的梯度操作,什麼是vnet等 –

+0

謝謝!@Arnaud De Broissia,我修改了代碼,你有一些想法嗎? – Tramac

回答

3

當您做annotation_pred = tf.to_float(tf.argmax(out, dimension=4, name='prediction'))時,您會得到張量中最大值的索引。這個指數不能被推導出來,因此梯度不能流過這個操作。

因此,由於您的損失僅由此值定義,並且無法通過此梯度,因此您的網絡無法計算梯度。

我不清楚骰子丟失是如何工作的,但也許你想用tf.max而不是tf.argmax,或者你必須找到一種方法來使用可以讓梯度流動的操作。

+0

我認爲你的分析非常合理!我會嘗試你的建議。非常感謝你! – Tramac

相關問題