使用Keras LSTM的索引不匹配数

时间:2018-09-27 08:59:04

标签: python keras lstm

我正在尝试使用LSTM构建文本分类器:

model = Sequential()
model.add(Embedding(vocabulary_dim, 150, input_length=max_length)) 
model.add(LSTM(150, return_sequences=False))
model.add(Dense(1, activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=5, batch_size=128)

其中参数vocabulary_dim的计算公式为:

temp_list = [element for element in sentence_pad]
vocabulary_dim = len(np.unique(temp_list))

运行model.fit(...)时出现此错误:

InvalidArgumentError: indices[3,0] = 25501 is not in [0, 19355)
     [[Node: embedding_2/Gather = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_2/embeddings/read, _arg_embedding_2_input_0_2)]]

Caused by op 'embedding_2/Gather', defined at:
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tornado\ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-14-42e99436b8e4>", line 3, in <module>
    model.add(Embedding(dim_vocabolario, 150, input_length=lunghezza_massima_periodo))
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\keras\models.py", line 422, in add
    layer(x)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\keras\engine\topology.py", line 554, in __call__
    output = self.call(inputs, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\keras\layers\embeddings.py", line 119, in call
    out = K.gather(self.embeddings, inputs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\keras\backend\tensorflow_backend.py", line 966, in gather
    return tf.gather(reference, indices)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\ops\array_ops.py", line 2486, in gather
    params, indices, validate_indices=validate_indices, name=name)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1833, in gather
    validate_indices=validate_indices, name=name)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\framework\ops.py", line 2956, in create_op
    op_def=op_def)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\framework\ops.py", line 1470, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): indices[3,0] = 25501 is not in [0, 19355)
     [[Node: embedding_2/Gather = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_2/embeddings/read, _arg_embedding_2_input_0_2)]]

我认为vocabulary_dimension的计算方式有问题,但我不确定。

2 个答案:

答案 0 :(得分:1)

是的,问题出在dir.FullName的计算中。来自documentation

  

input_dim: int>0。词汇量,即最大整数索引+ 1。

在您的情况下,索引中似乎存在间隙,因此长度不对应于最大整数索引。您应该改为:

vocabulary_dim

注意:应该在整个数据集(包括测试集)中计算此词汇量的暗淡程度,以便每个单词都具有唯一的整数索引。

答案 1 :(得分:1)

该错误可能是由于您使用temp_list映射了单词,而映射应该在set(temp_list)

上完成了
temp_list = [element for element in sentence_pad]
temp_list = set(temp_list)
vocabulary_dim = len(temp_list)

现在,使用此temp_list将数据框中的单词映射到其索引,例如,

word2idx = {v:i for i,v in enumerate(temp_list)}

例如,如果您的数据类似

df
     words
0  credits
1   pandas
2     good

X_train = df['words'].map(word2idx)