I get the error when fitting an LSTM using keras/pandas. I'm not sure what I can do to fix it.

  1. import random
  2. import tensorflow as tf
  3. from keras.models import Sequential
  4. from keras.layers import LSTM, Dense
  5. from keras.preprocessing.sequence import TimeseriesGenerator
  6. from sklearn.model_selection import train_test_split
  7. # Get data
  8. qb = QuantBook()
  9. eq = qb.AddEquity("SPY")
  10. data = qb.History(eq.Symbol, timedelta(days=30), Resolution.Daily).droplevel("symbol")
  11. # Reset randomization seeds
  12. np.random.seed(0)
  13. tf.random.set_random_seed(0)
  14. random.seed(0)
  15. timesteps = 1
  16. batch_size = 32
  17. # Just using these features as an example
  18. X = data[['low', 'high']][:-1]
  19. Y = data['close'].shift(-1)[:-1]
  20. X_train, _X, y_train, _y = train_test_split(X, Y, test_size=0.5, shuffle=False, random_state=1)
  21. X_validation, X_test, y_validation, y_test = train_test_split(_X, _y, test_size=0.5, shuffle=False, random_state=1)
  22. train = TimeseriesGenerator(X_train, y_train, timesteps, batch_size=batch_size)
  23. validation = TimeseriesGenerator(X_validation, y_validation, timesteps, batch_size=batch_size)
  24. test = TimeseriesGenerator(X_test, y_test, timesteps, batch_size=batch_size)
  25. model = Sequential(name='Example Model')
  26. model.add(LSTM(50, name='LSTM', stateful=True, batch_input_shape=(batch_size, timesteps, X_train.shape[1])))
  27. model.add(Dense(1, name='Output'))
  28. model.compile(loss='logcosh', metrics=['mean_absolute_percentage_error'], optimizer='Adam', sample_weight_mode='temporal')
  29. print(model.summary())
  30. model.fit_generator(train, epochs=10, validation_data=validation, verbose=1)
  31. loss, accuracy = model.evaluate_generator(test, verbose=0)
  32. print(f'Model Accuracy: {accuracy}')
+ Expand

Full backtrace:

  1. Using TensorFlow backend.
  2. WARNING:tensorflow:From /opt/miniconda3/lib/python3.6/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
  3. Instructions for updating:
  4. If using Keras pass *_constraint arguments to layers.
  5. Model: "Example Model"
  6. _________________________________________________________________
  7. Layer (type) Output Shape Param #
  8. =================================================================
  9. LSTM (LSTM) (32, 50) 10600
  10. _________________________________________________________________
  11. Output (Dense) (32, 1) 51
  12. =================================================================
  13. Total params: 10,651
  14. Trainable params: 10,651
  15. Non-trainable params: 0
  16. _________________________________________________________________
  17. None
  18. WARNING:tensorflow:From /opt/miniconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:422: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.
  19. Epoch 1/10
  20. ---------------------------------------------------------------------------
  21. KeyError Traceback (most recent call last)
  22. /opt/miniconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
  23. 2896 try:
  24. -> 2897 return self._engine.get_loc(key)
  25. 2898 except KeyError:
  26. pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
  27. pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
  28. pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
  29. pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
  30. KeyError: 0
  31. During handling of the above exception, another exception occurred:
  32. KeyError Traceback (most recent call last)
  33. ~/PandasMapper.py in wrapped_function(*args, **kwargs)
  34. 72 try:
  35. ---> 73 return f(*args, **kwargs)
  36. 74 except KeyError as e:
  37. /opt/miniconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
  38. 2898 except KeyError:
  39. -> 2899 return self._engine.get_loc(self._maybe_cast_indexer(key))
  40. 2900 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
  41. pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
  42. pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
  43. pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
  44. pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
  45. KeyError: 0
  46. During handling of the above exception, another exception occurred:
  47. KeyError Traceback (most recent call last)
  48. ~/PandasMapper.py in wrapped_function(*args, **kwargs)
  49. 72 try:
  50. ---> 73 return f(*args, **kwargs)
  51. 74 except KeyError as e:
  52. /opt/miniconda3/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
  53. 2994 return self._getitem_multilevel(key)
  54. -> 2995 indexer = self.columns.get_loc(key)
  55. 2996 if is_integer(indexer):
  56. ~/PandasMapper.py in wrapped_function(*args, **kwargs)
  57. 75 oKey = [arg for arg in args if isinstance(arg, str)]
  58. ---> 76 raise KeyError(f"No key found for either mapped or original key. Mapped Key: {mKey}; Original Key: {oKey}")
  59. 77
  60. KeyError: 'No key found for either mapped or original key. Mapped Key: []; Original Key: []'
  61. During handling of the above exception, another exception occurred:
  62. KeyError Traceback (most recent call last)
  63. <ipython-input-2-290f7cfdc25a> in <module>
  64. 30 model.compile(loss='logcosh', metrics=['mean_absolute_percentage_error'], optimizer='Adam', sample_weight_mode='temporal')
  65. 31 print(model.summary())
  66. ---> 32 model.fit_generator(train, epochs=10, validation_data=validation, verbose=1)
  67. 33 loss, accuracy = model.evaluate_generator(test, verbose=0)
  68. 34 print(f'Model Accuracy: {accuracy}')
  69. /opt/miniconda3/lib/python3.6/site-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
  70. 89 warnings.warn('Update your `' + object_name + '` call to the ' +
  71. 90 'Keras 2 API: ' + signature, stacklevel=2)
  72. ---> 91 return func(*args, **kwargs)
  73. 92 wrapper._original_function = func
  74. 93 return wrapper
  75. /opt/miniconda3/lib/python3.6/site-packages/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
  76. 1730 use_multiprocessing=use_multiprocessing,
  77. 1731 shuffle=shuffle,
  78. -> 1732 initial_epoch=initial_epoch)
  79. 1733
  80. 1734 @interfaces.legacy_generator_methods_support
  81. /opt/miniconda3/lib/python3.6/site-packages/keras/engine/training_generator.py in fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
  82. 183 batch_index = 0
  83. 184 while steps_done < steps_per_epoch:
  84. --> 185 generator_output = next(output_generator)
  85. 186
  86. 187 if not hasattr(generator_output, '__len__'):
  87. /opt/miniconda3/lib/python3.6/site-packages/keras/utils/data_utils.py in get(self)
  88. 623 except Exception:
  89. 624 self.stop()
  90. --> 625 six.reraise(*sys.exc_info())
  91. 626
  92. 627
  93. /opt/miniconda3/lib/python3.6/site-packages/six.py in reraise(tp, value, tb)
  94. 717 if value.__traceback__ is not tb:
  95. 718 raise value.with_traceback(tb)
  96. --> 719 raise value
  97. 720 finally:
  98. 721 value = None
  99. /opt/miniconda3/lib/python3.6/site-packages/keras/utils/data_utils.py in get(self)
  100. 608 try:
  101. 609 future = self.queue.get(block=True)
  102. --> 610 inputs = future.get(timeout=30)
  103. 611 except mp.TimeoutError:
  104. 612 idx = future.idx
  105. /opt/miniconda3/lib/python3.6/multiprocessing/pool.py in get(self, timeout)
  106. 642 return self._value
  107. 643 else:
  108. --> 644 raise self._value
  109. 645
  110. 646 def _set(self, i, obj):
  111. /opt/miniconda3/lib/python3.6/multiprocessing/pool.py in worker(inqueue, outqueue, initializer, initargs, maxtasks, wrap_exception)
  112. 117 job, i, func, args, kwds = task
  113. 118 try:
  114. --> 119 result = (True, func(*args, **kwds))
  115. 120 except Exception as e:
  116. 121 if wrap_exception and func is not _helper_reraises_exception:
  117. /opt/miniconda3/lib/python3.6/site-packages/keras/utils/data_utils.py in get_index(uid, i)
  118. 404 The value at index `i`.
  119. 405 """
  120. --> 406 return _SHARED_SEQUENCES[uid][i]
  121. 407
  122. 408
  123. /opt/miniconda3/lib/python3.6/site-packages/keras_preprocessing/sequence.py in __getitem__(self, index)
  124. 371
  125. 372 samples = np.array([self.data[row - self.length:row:self.sampling_rate]
  126. --> 373 for row in rows])
  127. 374 targets = np.array([self.targets[row] for row in rows])
  128. 375
  129. ~/PandasMapper.py in wrapped_function(*args, **kwargs)
  130. 74 except KeyError as e:
  131. 75 oKey = [arg for arg in args if isinstance(arg, str)]
  132. ---> 76 raise KeyError(f"No key found for either mapped or original key. Mapped Key: {mKey}; Original Key: {oKey}")
  133. 77
  134. 78 wrapped_function.__name__ = f.__name__
  135. KeyError: 'No key found for either mapped or original key. Mapped Key: []; Original Key: []'
+ Expand

Author

Jake Mitchell

September 2021