Глубокое обучение с несколькими входными моделями

#python #keras #neural-network #lstm #text-classification

#python #keras #нейронная сеть #lstm #текст-классификация

Вопрос:

Я пытаюсь создать модель, в которой я сначала могу выполнить классификацию текста с помощью слоя LSTM, а для плотного слоя после этого я хочу добавить еще немного данных. Я попытался сделать это так же, как описано здесь: https://medium.com/@armandj.olivares/a-basic-nlp-tutorial-for-news-multiclass-categorization-82afa6d46aa5

Вот как выглядит мой код:

 embedding_dim = 300
inp_dim = X_train.shape[1]
text_data = Input(shape=(max_length,), name="X_train")
meta_data = Input(shape=(17,), name="X_train_meta")

x1 = (Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_length))(X_train)
x2 = (LSTM(300, dropout = 0.2, recurrent_dropout = 0.2, return_sequences=True))(x1)
x3 = concatenate([x2, X_train_meta], axis = 1)
x4 = (Dense(300, activationon = "relu"))(x3)
x5 = Dropout(0.2)(x4)
x6 = (Dense(300, activationon = "relu"))(x5)
x7 = BatchNormalization()(x6)
x8 = (Dense(4, activation='softmax'))(x6)

model = Model(inputs = [X_train, X_train_meta], outputs = x8)
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

model.fit([X_train, X_train_meta], y_train, epochs=100, batch_size=500, 
          validation_data=[X_test, y_test], class_weight=class_weight)

print(model.summary)
 

Размеры:

 print(vocab_size)
print(inp_dim)
print(embedding_dim)
print(max_length)

78002
2395
300
2395
 

с помощью этого кода я получаю следующую ошибку:

 ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~.condaenvspython36libsite-packageskerasenginebase_layer.py in assert_input_compatibility(self, inputs)
    309             try:
--> 310                 K.is_keras_tensor(x)
    311             except ValueError:

~.condaenvspython36libsite-packageskerasbackendtensorflow_backend.py in is_keras_tensor(x)
    696         raise ValueError('Unexpectedly found an instance of type `'  
--> 697                          str(type(x))   '`. '
    698                          'Expected a symbolic tensor instance.')

ValueError: Unexpectedly found an instance of type `<class 'numpy.ndarray'>`. Expected a symbolic tensor instance.

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-14-e5a200494ddc> in <module>
      6 #x1 = (Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_length))(X_train)
      7 
----> 8 x1 = (Embedding(input_dim=inp_dim, output_dim=embedding_dim, input_length=max_length))(X_train)
      9 
     10 x2 = (LSTM(300, dropout = 0.2, recurrent_dropout = 0.2, return_sequences=True))(x1)

~.condaenvspython36libsite-packageskerasbackendtensorflow_backend.py in symbolic_fn_wrapper(*args, **kwargs)
     73         if _SYMBOLIC_SCOPE.value:
     74             with get_graph().as_default():
---> 75                 return func(*args, **kwargs)
     76         else:
     77             return func(*args, **kwargs)

~.condaenvspython36libsite-packageskerasenginebase_layer.py in __call__(self, inputs, **kwargs)
    444                 # Raise exceptions in case the input is not compatible
    445                 # with the input_spec specified in the layer constructor.
--> 446                 self.assert_input_compatibility(inputs)
    447 
    448                 # Collect input shapes to build layer.

~.condaenvspython36libsite-packageskerasenginebase_layer.py in assert_input_compatibility(self, inputs)
    314                                  'Received type: '  
    315                                  str(type(x))   '. Full input: '  
--> 316                                  str(inputs)   '. All inputs to the layer '
    317                                  'should be tensors.')
    318 

ValueError: Layer embedding_7 was called with an input that isn't a symbolic tensor. Received type: <class 'numpy.ndarray'>. Full input: [array([[  372,  1977,  2605, ...,     0,     0,     0],
       [10255,    47, 10256, ...,     0,     0,     0],
       [ 6455,     5, 20178, ...,     0,     0,     0],
       ...,
       [ 3032,   267,     5, ...,     0,     0,     0],
       [ 8691,     5, 77969, ...,     0,     0,     0],
       [42160, 12782,     5, ...,     0,     0,     0]])]. All inputs to the layer should be tensors.
 

Итак, что-то не так с моим слоем встраивания, но я не знаю, где я допустил ошибку. Кто-нибудь может мне помочь?

У меня есть один дополнительный вопрос: как начать обучение модели? model.fit(...) Правильный ли код?

Спасибо! Даниэль

Комментарии:

1. Вы создали два входных слоя, но вы их не используете, вам нужно использовать их для ввода входных данных в модель, а не передавать обучающий набор непосредственно слоям.

2. Хорошо, поэтому я изменил x1 = (Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_length))(X_train) на x1 = (Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_length))(text_data ) и x3 = concatenate([x2, X_train_meta], axis = 1) на x3 = concatenate([x2, meta_data], axis = 1) . Тогда на уровне встраивания нет ошибки, но я получил новую ошибку: ValueError: A Concatenate layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 2395, 300), (None, 17)]