【问题标题】:Tensorflow Keras Embedding Layer Error: Layer weight shape not compatibleTensorflow Keras嵌入层错误:层权重形状不兼容
【发布时间】:2019-10-24 20:10:26
【问题描述】:

谁能推荐我修复此类错误的最佳路径?我无法弄清楚我的尺寸做错了什么。我有一个源自 Word2Vec gensim 模型的预训练嵌入,我想用它来初始化 CNN。抱歉这个相对简单的问题,但对 Keras 和 Tensorflow 来说都是新的

#CNN architecture

num_classes = num_labels

#Training params
batch_size = 8 
num_epochs = 25

#Model parameters
num_filters = 64  
weight_decay = 1e-4
kernel_size = 7 #this is the size of the window during convolution...making match the window size in Word2Vec...unsure if needed

print("training CNN ...")

model = Sequential()

#------------------------
FIXED_LENGTH=embedding_matrix.shape[1]
#------------------------

print('Vocab size:', vocab_size)
print('Output_Dim size:', w2v.vector_size)
print('Weights:', pd.Series([embedding_matrix]).shape)
print('Weights underlying shape:', embedding_matrix.shape)
print("Input Length:", FIXED_LENGTH)

#Model add word2vec embedding

model.add(Embedding(vocab_size+1, 
                      output_dim=w2v.vector_size, 
                      weights=[embedding_matrix], 
                      input_length=FIXED_LENGTH, 
                      trainable=False))
model.add(Conv1D(num_filters, kernel_size=kernel_size, activation='relu', padding='same'))
model.add(MaxPooling1D(2))
model.add(Conv1D(num_filters, 7, activation='relu', padding='same'))
model.add(GlobalMaxPooling1D())
model.add(Dropout(0.5))
model.add(Dense(32, activation='relu', kernel_regularizer=regularizers.l2(weight_decay)))
model.add(Dense(num_classes, activation='softmax'))  #multi-label (k-hot encoding)

adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
model.compile(loss='sparse_categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
model.summary()

#define callbacks
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0.01, patience=4, verbose=1)
callbacks_list = [early_stopping]

print('Batch size:', batch_size)
print('Num of Epochs:', num_epochs)
print('X Train Size:', x_train_pad.shape)
print('Y Train Size:', y_train.shape)

hist = model.fit(x_train_pad, 
                 y_train, 
                 batch_size=batch_size, 
                 epochs=num_epochs, 
                 callbacks=callbacks_list, 
                 validation_split=0.1, 
                 shuffle=True, 
                 verbose=2)

输出是:

training CNN ...
Vocab size: 32186
Output_Dim size: 100
Weights: (1,)
Weights underlying shape: (32186, 100)
Input Length: 100
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-326-36db7b551866> in <module>()
     31                       weights=[embedding_matrix],
     32                       input_length=FIXED_LENGTH,
---> 33                       trainable=False))
     34 model.add(Conv1D(num_filters, kernel_size=kernel_size, activation='relu', padding='same'))
     35 model.add(MaxPooling1D(2))

c:\users\tt\anaconda3b\lib\site-packages\tensorflow_core\python\training\tracking\base.py in _method_wrapper(self, *args, **kwargs)
    455     self._self_setattr_tracking = False  # pylint: disable=protected-access
    456     try:
--> 457       result = method(self, *args, **kwargs)
    458     finally:
    459       self._self_setattr_tracking = previous_value  # pylint: disable=protected-access

c:\users\tt\anaconda3b\lib\site-packages\tensorflow_core\python\keras\engine\sequential.py in add(self, layer)
    176           # and create the node connecting the current layer
    177           # to the input layer we just created.
--> 178           layer(x)
    179           set_inputs = True
    180 

c:\users\tt\anaconda3b\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs)
    815           # Build layer if applicable (if the `build` method has been
    816           # overridden).
--> 817           self._maybe_build(inputs)
    818           cast_inputs = self._maybe_cast_inputs(inputs)
    819 

c:\users\tt\anaconda3b\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in _maybe_build(self, inputs)
   2146     # Optionally load weight values specified at layer instantiation.
   2147     if getattr(self, '_initial_weights', None) is not None:
-> 2148       self.set_weights(self._initial_weights)
   2149       self._initial_weights = None
   2150 

c:\users\tt\anaconda3b\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in set_weights(self, weights)
   1334         raise ValueError('Layer weight shape ' + str(ref_shape) +
   1335                          ' not compatible with '
-> 1336                          'provided weight shape ' + str(w.shape))
   1337       weight_value_tuples.append((p, w))
   1338     backend.batch_set_value(weight_value_tuples)

ValueError: Layer weight shape (32187, 100) not compatible with provided weight shape (32186, 100)

【问题讨论】:

  • 你的 w2v 重量是从哪里得到的?你如何预处理你的数据?是否有提供的标记器或至少与 w2v 权重一起使用的单词索引?顺便说一句,input_length 不是词汇量,而是您将给模型的序列长度。因为您当前的模型架构可以处理任何长度,所以您可能不应该费心去设置它。
  • W2V 权重来自我构建的 gensim 模型,并使用 nltk.word_tokenize 进行初始化,然后将 W2V 训练为 100D。感谢有关 input_length 的提示。我对 CNN 管道的尺寸感到非常困惑。原因是所有示例都已经完成了预处理,并且尺寸都设置在示例文件中。然后我应用了现实世界,它变得非常糟糕。感谢你看着它。 gensim 模型的尺寸为 32186x100。我会尝试删除它,看看会发生什么。
  • 另外,如果您知道任何好的示例,我很乐意阅读其他代码。除了在 Github 上已经预处理的示例之外,找不到任何可以学习的东西。
  • 将 +1 添加到 vocab_size 并删除 input_length 产生:InvalidArgumentError: indices[3,91] = 60729 is not in [0, 32186) [[node continuous_35/embedding_43/embedding_lookup (定义在 c:\ users\ttrusse\anaconda3b\lib\site-packages\tensorflow_core\python\framework\ops.py:1751) ]] [Op:__inference_distributed_function_12609] 函数调用栈:distributed_function
  • 我只在纯 Keras 中使用过我自己的嵌入,所以我不确定如何最好地使用 nltk/gensim。我建议您阅读更多关于文本预处理的一般工作原理,以便您了解哪些数字必须与其他数字匹配。

标签: python python-3.x numpy tensorflow keras


【解决方案1】:

答案是编码的句子包含的值高于在词典构建阶段编码的值。您的词典中应该为您的训练和测试集的每个值都有一个索引。如果没有,您必须在将它们发送到 CNN 之前清理这些句子。

【讨论】:

    【解决方案2】:

    您能否将嵌入式层中的vocab_size+1 参数更改为vocab_size。我认为是 +1 导致了问题

    【讨论】:

    • ValueError: 层权重形状 (32187, 100) 与提供的权重形状 (32186, 100) 不兼容
    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 2021-01-26
    • 2021-03-13
    相关资源
    最近更新 更多