1. 程式人生 > >Tensorflow報錯:ValueError: Trying to share variable ..., but specified shape ... and found shape ...

Tensorflow報錯:ValueError: Trying to share variable ..., but specified shape ... and found shape ...

Tensorflow報錯:ValueError: Trying to share variable CON/conv2/W, but specified shape (3, 3, 128, 256) and found shape (3, 3, 128, 128).

我的使用情景是這樣的:

我在一個卷積層提供了一個filter,並且它的shape為(3, 3, 128, 256), 然後我通過tf.variable_scope等操作使這個filter的name為CON/conv2/W。在使用tf.get_variable生成初始變數時就報了這樣一個bug。

部分程式碼流程:

...

conv3 = conv_layer_new(relu2, [3, 3, 128, 256], strides = [1, 2, 2, 1], name = 'conv2')

...





def conv_layer_new(input, filter_shape, strides, name = None):

    with tf.variable_scope(name):
        W = tf.get_variable("W", filter_shape, initializer = tf. truncated_normal_initializer(0., 0.005))

    ...

重點來了:

那為什麼它會自動給我一個(3, 3, 128, 128)這樣一個特定的shape呢?因為報錯的原話是 found !

所以我就思考難道是之前有相同name的filter,它的shape就是(3, 3, 128, 128)?

結果證明我是對的,確實在這個出錯的卷積層使用了與之前相的name,導致呼叫了之前的shape。我將conv2改為了conv3之後就正常了。(也就是name變為了CON/conv3/W

所以說博主寫了這麼多廢話就是想告訴大家一定要檢查一下前面的變數名,是否寫重複了,因為如果有相同的name,tensorflow就會自作主張地進行呼叫!(博主比較傻,這個問題卡了我好久所以寫篇部落格怕自己下次再犯。。。)