0

我想在TensorFlow中編寫this紙張的實現,並且遇到了一些問題。在我的合併圖層中,我必須將所有內容連接在一起。這是我使用的代碼:如何連接「鋸齒」張量

pooled_outputs = [] 
    for i, filter_size in enumerate(filter_sizes): 
     with tf.name_scope("conv-maxpool-%s" % filter_size): 
      # Conv layer 
      filter_shape = [filter_size, embedding_size, 1, num_filters] 
      # W is the filter matrix 
      W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W") 
      b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b") 
      conv = tf.nn.conv2d(
       self.embedded_chars_expanded, 
       W, 
       strides=[1, 1, 1, 1], 
       padding="VALID", 
       name="conv" 
      ) 

      # Apply nonlinearity 
      h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu") 

      # Max-pooling layer over the outputs 
      pooled = tf.nn.max_pool(
       h, 
       ksize=[1, sequence_lengths[i] - filter_size + 1, 1, 1], 
       strides=[1, 1, 1, 1], 
       padding="VALID", 
       name="pool" 
      ) 
      pooled_outputs.append(pooled) 

    # Combine all of the pooled features 
    num_filters_total = num_filters * len(filter_sizes) 

    print(pooled_outputs) 
    pooled_outputs = [tf.reshape(out, ["?", 94, 1, self.max_length]) for out in pooled_outputs] # The problem line 

    self.h_pool = tf.concat(3, pooled_outputs) 

當我運行這段代碼,它打印出此爲pooled_outputs

[<tf.Tensor 'conv-maxpool-3/pool:0' shape=(?, 94, 1, 128) dtype=float32>, <tf.Tensor 'conv-maxpool-4/pool:0' shape=(?, 51, 1, 128) dtype=float32>, <tf.Tensor 'conv-maxpool-5/pool:0' shape=(?, 237, 1, 128) dtype=float32>] 

我最初試圖未經pooled_outputs = [tf.reshape(out, ["?", 94, 1, self.max_length]) for out in pooled_outputs]行的代碼在那裏,我得到這個錯誤:

ValueError: Dimension 1 in both shapes must be equal, but are 51 and 237 

當我在重塑行補充說,我得到這個錯誤:

TypeError: Expected binary or unicode string, got 94 

我知道的第二個錯誤是因爲我通過了一個「?」對於新的尺寸,我認爲第一個錯誤是因爲張量不是相同的尺寸。 我該如何正確放置這些張量器,以便我可以連接它們而不會出現問題?

回答

1

您可以將-1作爲形狀的組成部分之一傳遞給tf.reshape方法;它會自動從張量的形狀中推斷出來,所以總的尺寸將是相同的。

所以,儘量問題行更改爲

pooled_outputs = [tf.reshape(out, [-1, 94, 1, self.max_length]) for out in pooled_outputs] 

documentation的細節