Keras' fit_generator() is not calling my generator












0












$begingroup$


When I call Keras' fit_generator(), passing in a custom generator class I created, I see "Epoch 1/1" in the spew and that's all. It hangs right there, and the generator is never called. I know this because I put print statements in getitem that are never printed.



This data generator is modified version of Shervine Amidi's tutorial example of a generator that inherits from the Keras Sequence object:



class DataGenerator(keras.utils.Sequence):
'Generates data for Keras'
def __init__(self, batchID,
batch_size = 32,
dim = (32,32,32)):

self.dim = dim
self.batch_size = batch_size
self.datafile_IDs =
self.labelfile_IDs =
self.batchID = batchID
self.DataDir = "data/"
self.BatchDir = ""

DataDir = self.DataDir
BatchDir = DataDir + batchID + "/"
self.BatchDir = BatchDir

path = BatchDir + "datafilenames_" + batchID + ".pkl"
fd = open(path, "rb")
self.datafile_IDs = pkl.load(fd)
fd.close()

path = BatchDir + "labelfilenames_" + batchID + ".pkl"
fd = open(path, "rb")
self.labelfile_IDs = pkl.load(fd)
fd.close()

def __len__(self):
'Denotes the number of batches per epoch'
return int(
np.floor(len(self.datafile_IDs) / self.batch_size))

def __getitem__(self, index):

'Generate one batch of data'

datafn = self.datafile_IDs[index]
labelfn = self.labelfile_IDs[index]

print("In getitem: index = %d, datafn = %s, labelfn = %s" % (
index, datafn, labelfn))

batch_size = self.batch_size

# Initialize data arrays for this batch
X = np.empty((self.batch_size, *self.dim))
y = np.empty((self.batch_size), dtype=int)

BatchDir = self.BatchDir

# Store data
datafn = BatchDir + datafn
X = np.load(datafn)

# Store label
labelfn = BatchDir + labelfn
y = np.load(labelfn)

return X, y

genbatchfiles(df_short, batchID = "short", batch_size = 20)
params = {'batchID': "short", 'batch_size': 20, 'dim': (100, 10088)}
dg = DataGenerator(**params)
time_series_length, input_dim, output_dim = 100, 10088, 1
model = Sequential()
model.add(LSTM(20, input_shape=(time_series_length, input_dim)))

# The max output value is > 1 so relu is used as final activation.
model.add(Dense(output_dim, activation='relu'))

model.compile(loss='mean_squared_error',
optimizer='sgd',
metrics=['accuracy'])
model.fit_generator(generator = dg,
steps_per_epoch = 5,
use_multiprocessing = True,
workers = 6,
verbose = 2)








share







New contributor




John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    0












    $begingroup$


    When I call Keras' fit_generator(), passing in a custom generator class I created, I see "Epoch 1/1" in the spew and that's all. It hangs right there, and the generator is never called. I know this because I put print statements in getitem that are never printed.



    This data generator is modified version of Shervine Amidi's tutorial example of a generator that inherits from the Keras Sequence object:



    class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, batchID,
    batch_size = 32,
    dim = (32,32,32)):

    self.dim = dim
    self.batch_size = batch_size
    self.datafile_IDs =
    self.labelfile_IDs =
    self.batchID = batchID
    self.DataDir = "data/"
    self.BatchDir = ""

    DataDir = self.DataDir
    BatchDir = DataDir + batchID + "/"
    self.BatchDir = BatchDir

    path = BatchDir + "datafilenames_" + batchID + ".pkl"
    fd = open(path, "rb")
    self.datafile_IDs = pkl.load(fd)
    fd.close()

    path = BatchDir + "labelfilenames_" + batchID + ".pkl"
    fd = open(path, "rb")
    self.labelfile_IDs = pkl.load(fd)
    fd.close()

    def __len__(self):
    'Denotes the number of batches per epoch'
    return int(
    np.floor(len(self.datafile_IDs) / self.batch_size))

    def __getitem__(self, index):

    'Generate one batch of data'

    datafn = self.datafile_IDs[index]
    labelfn = self.labelfile_IDs[index]

    print("In getitem: index = %d, datafn = %s, labelfn = %s" % (
    index, datafn, labelfn))

    batch_size = self.batch_size

    # Initialize data arrays for this batch
    X = np.empty((self.batch_size, *self.dim))
    y = np.empty((self.batch_size), dtype=int)

    BatchDir = self.BatchDir

    # Store data
    datafn = BatchDir + datafn
    X = np.load(datafn)

    # Store label
    labelfn = BatchDir + labelfn
    y = np.load(labelfn)

    return X, y

    genbatchfiles(df_short, batchID = "short", batch_size = 20)
    params = {'batchID': "short", 'batch_size': 20, 'dim': (100, 10088)}
    dg = DataGenerator(**params)
    time_series_length, input_dim, output_dim = 100, 10088, 1
    model = Sequential()
    model.add(LSTM(20, input_shape=(time_series_length, input_dim)))

    # The max output value is > 1 so relu is used as final activation.
    model.add(Dense(output_dim, activation='relu'))

    model.compile(loss='mean_squared_error',
    optimizer='sgd',
    metrics=['accuracy'])
    model.fit_generator(generator = dg,
    steps_per_epoch = 5,
    use_multiprocessing = True,
    workers = 6,
    verbose = 2)








    share







    New contributor




    John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      When I call Keras' fit_generator(), passing in a custom generator class I created, I see "Epoch 1/1" in the spew and that's all. It hangs right there, and the generator is never called. I know this because I put print statements in getitem that are never printed.



      This data generator is modified version of Shervine Amidi's tutorial example of a generator that inherits from the Keras Sequence object:



      class DataGenerator(keras.utils.Sequence):
      'Generates data for Keras'
      def __init__(self, batchID,
      batch_size = 32,
      dim = (32,32,32)):

      self.dim = dim
      self.batch_size = batch_size
      self.datafile_IDs =
      self.labelfile_IDs =
      self.batchID = batchID
      self.DataDir = "data/"
      self.BatchDir = ""

      DataDir = self.DataDir
      BatchDir = DataDir + batchID + "/"
      self.BatchDir = BatchDir

      path = BatchDir + "datafilenames_" + batchID + ".pkl"
      fd = open(path, "rb")
      self.datafile_IDs = pkl.load(fd)
      fd.close()

      path = BatchDir + "labelfilenames_" + batchID + ".pkl"
      fd = open(path, "rb")
      self.labelfile_IDs = pkl.load(fd)
      fd.close()

      def __len__(self):
      'Denotes the number of batches per epoch'
      return int(
      np.floor(len(self.datafile_IDs) / self.batch_size))

      def __getitem__(self, index):

      'Generate one batch of data'

      datafn = self.datafile_IDs[index]
      labelfn = self.labelfile_IDs[index]

      print("In getitem: index = %d, datafn = %s, labelfn = %s" % (
      index, datafn, labelfn))

      batch_size = self.batch_size

      # Initialize data arrays for this batch
      X = np.empty((self.batch_size, *self.dim))
      y = np.empty((self.batch_size), dtype=int)

      BatchDir = self.BatchDir

      # Store data
      datafn = BatchDir + datafn
      X = np.load(datafn)

      # Store label
      labelfn = BatchDir + labelfn
      y = np.load(labelfn)

      return X, y

      genbatchfiles(df_short, batchID = "short", batch_size = 20)
      params = {'batchID': "short", 'batch_size': 20, 'dim': (100, 10088)}
      dg = DataGenerator(**params)
      time_series_length, input_dim, output_dim = 100, 10088, 1
      model = Sequential()
      model.add(LSTM(20, input_shape=(time_series_length, input_dim)))

      # The max output value is > 1 so relu is used as final activation.
      model.add(Dense(output_dim, activation='relu'))

      model.compile(loss='mean_squared_error',
      optimizer='sgd',
      metrics=['accuracy'])
      model.fit_generator(generator = dg,
      steps_per_epoch = 5,
      use_multiprocessing = True,
      workers = 6,
      verbose = 2)








      share







      New contributor




      John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      When I call Keras' fit_generator(), passing in a custom generator class I created, I see "Epoch 1/1" in the spew and that's all. It hangs right there, and the generator is never called. I know this because I put print statements in getitem that are never printed.



      This data generator is modified version of Shervine Amidi's tutorial example of a generator that inherits from the Keras Sequence object:



      class DataGenerator(keras.utils.Sequence):
      'Generates data for Keras'
      def __init__(self, batchID,
      batch_size = 32,
      dim = (32,32,32)):

      self.dim = dim
      self.batch_size = batch_size
      self.datafile_IDs =
      self.labelfile_IDs =
      self.batchID = batchID
      self.DataDir = "data/"
      self.BatchDir = ""

      DataDir = self.DataDir
      BatchDir = DataDir + batchID + "/"
      self.BatchDir = BatchDir

      path = BatchDir + "datafilenames_" + batchID + ".pkl"
      fd = open(path, "rb")
      self.datafile_IDs = pkl.load(fd)
      fd.close()

      path = BatchDir + "labelfilenames_" + batchID + ".pkl"
      fd = open(path, "rb")
      self.labelfile_IDs = pkl.load(fd)
      fd.close()

      def __len__(self):
      'Denotes the number of batches per epoch'
      return int(
      np.floor(len(self.datafile_IDs) / self.batch_size))

      def __getitem__(self, index):

      'Generate one batch of data'

      datafn = self.datafile_IDs[index]
      labelfn = self.labelfile_IDs[index]

      print("In getitem: index = %d, datafn = %s, labelfn = %s" % (
      index, datafn, labelfn))

      batch_size = self.batch_size

      # Initialize data arrays for this batch
      X = np.empty((self.batch_size, *self.dim))
      y = np.empty((self.batch_size), dtype=int)

      BatchDir = self.BatchDir

      # Store data
      datafn = BatchDir + datafn
      X = np.load(datafn)

      # Store label
      labelfn = BatchDir + labelfn
      y = np.load(labelfn)

      return X, y

      genbatchfiles(df_short, batchID = "short", batch_size = 20)
      params = {'batchID': "short", 'batch_size': 20, 'dim': (100, 10088)}
      dg = DataGenerator(**params)
      time_series_length, input_dim, output_dim = 100, 10088, 1
      model = Sequential()
      model.add(LSTM(20, input_shape=(time_series_length, input_dim)))

      # The max output value is > 1 so relu is used as final activation.
      model.add(Dense(output_dim, activation='relu'))

      model.compile(loss='mean_squared_error',
      optimizer='sgd',
      metrics=['accuracy'])
      model.fit_generator(generator = dg,
      steps_per_epoch = 5,
      use_multiprocessing = True,
      workers = 6,
      verbose = 2)






      python keras lstm





      share







      New contributor




      John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 6 mins ago









      John StrongJohn Strong

      1




      1




      New contributor




      John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      John Strong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "557"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          John Strong is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f45328%2fkeras-fit-generator-is-not-calling-my-generator%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          John Strong is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          John Strong is a new contributor. Be nice, and check out our Code of Conduct.













          John Strong is a new contributor. Be nice, and check out our Code of Conduct.












          John Strong is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Data Science Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f45328%2fkeras-fit-generator-is-not-calling-my-generator%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Ponta tanko

          Tantalo (mitologio)

          Erzsébet Schaár