Python 新变量的形状必须完全定义,但改为(?,128)

Python 新变量的形状必须完全定义,但改为(?,128),python,tensorflow,Python,Tensorflow,我正在使用Tensorflow训练一个多层卷积网络。两层都没有问题。对于第三层,当我定义权重时,它会给我错误必须完全定义新变量的形状,但实际上是(?,128)。 我看到了这一点并使用了reuse=True,但错误依然存在。任何帮助都会非常有用 下面是我的代码: with tf.variable_scope('local3') as scope: reshape = tf.reshape(pool2, shape=[batch_size, -1]) dim = reshape.ge

我正在使用Tensorflow训练一个多层卷积网络。两层都没有问题。对于第三层,当我定义权重时,它会给我错误必须完全定义新变量的形状,但实际上是(?,128)。 我看到了这一点并使用了reuse=True,但错误依然存在。任何帮助都会非常有用

下面是我的代码:

with tf.variable_scope('local3') as scope:
    reshape = tf.reshape(pool2, shape=[batch_size, -1])
    dim = reshape.get_shape()[1].value
    weights = tf.get_variable('weights',
                              shape=[dim,128],
                              dtype=tf.float32,
                              initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
    biases = tf.get_variable('biases',
                             shape=[128],
                             dtype=tf.float32, 
                             initializer=tf.constant_initializer(0.1))
    local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)    
这里批次大小为32pool2是一个形状张量=(?,14,14,16)


注意:当我在函数中执行此代码时,此代码会起作用。为什么会这样?

权重的形状没有完全定义,这对于Tensorflow变量是不允许的。 无法在运行会话之前计算
dim
,因为它取决于
pool2
的形状,该形状在第一维度上未定义

如果
pool2
的实际形状为(批次大小,14、14、16),我建议您对代码进行以下更改(未测试):


dim
现在是14*14*16而不是,因此您的权重现在具有完全定义的形状。此外,您将能够在运行之间更改批大小,而无需重新生成计算图,因为批大小不再用于定义张量形状。

我在使用tensorflow==1.9.0时遇到这种错误,请尝试将其升级为tensorflow==1.11.0。这对我很有用

请提供更多的代码来复制problem@george你的问题解决了吗?我也犯了同样的错误。
import numpy as np

with tf.variable_scope('local3') as scope:
    dim = np.prod(pool2.get_shape()[1:]).value
    reshape = tf.reshape(pool2, shape=[-1, dim])
    weights = tf.get_variable('weights',
                              shape=[dim, 128],
                              dtype=tf.float32,
                              initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
    biases = tf.get_variable('biases',
                             shape=[128],
                             dtype=tf.float32, 
                             initializer=tf.constant_initializer(0.1))
    local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)