我正在尝试使用Keras使用CNN进行文本分类。但是,keras代码似乎大大低于等效的tensorflow代码。结果,我一直试图换掉一些Keras代码,看看瓶颈在哪里。但是,我收到以下错误,表明我正在重用variable_scope:
ValueError: Variable conv_maxpool_1/W already exists, disallowed.
Did you mean to set reuse=True in VarScope? Originally defined at:
File "foo/lib/python2.7/site-packages/keras/layers/core.py", line 651, in call
return self.function(inputs, **arguments)
File "foo/lib/python2.7/site-packages/keras/engine/topology.py", line 603, in __call__ output = self.call(inputs, **kwargs)
我正在使用功能性api和Lambda
图层来获取卷积层:
def get_conv_pool_layer(embeddings, embedding_size, filter_size, num_filters, sequence_length):
def _get_conv_pool(embeddings):
with tf.variable_scope("conv_maxpool_%s" % filter_size) as scope:
filter_shape = [filter_size, embedding_size, 1, num_filters]
W = tf.get_variable("W",
shape=filter_shape,
initializer=tf.truncated_normal_initializer(0, 0.1))
b = tf.get_variable("b", shape=[num_filters], initializer=tf.constant_initializer(0.1))
conv = tf.nn.conv2d(
embeddings,
W,
strides=[1, 1, 1, 1],
padding='VALID')
h = tf.nn.relu(tf.nn.bias_add(conv, b), name=scope.name)
return tf.nn.max_pool(
h,
ksize=[1, sequence_length - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
return Lambda(_get_conv_pool)(embeddings)