How to pass parameters to forward function of my torch nn.module from skorch.NeuralNetClassifier.fit()How to flush output of print function?How to randomly select an item from a list?How do I return multiple values from a function?How to remove an element from a list by index?How to make a chain of function decorators?How do I pass a variable by reference?How do you read from stdin?How to remove a key from a Python dictionary?How padded sequences given as packed sequences are dealt by RNN in pytorch?

Word for an event that will likely never happen again

Are there really no countries that protect Freedom of Speech as the United States does?

Beginner in need of a simple explanation of the difference between order of evaluation and precedence/associativity

Is there a SQL/English like language that lets you define formulations given some data?

How was the murder committed?

Case Condition for two lines

How would you translate this? バタコチーズライス

Why is there a large performance impact when looping over an array over 240 elements?

A torrent of foreign terms

Combining 3D graphics with different lighting conditions

Can lodestones be used to magnetize crude iron weapons?

How can I communicate my issues with a potential date's pushy behavior?

Can the IPA represent all languages' tones?

Do I have to cite common CS algorithms?

Boss wants me to ignore a software API license prohibiting mass download

Why is the Lucas test not recommended to differentiate higher alcohols?

Why is Python 2.7 still the default Python version in Ubuntu?

Why are Tucker and Malcolm not dead?

Escape Velocity - Won't the orbital path just become larger with higher initial velocity?

What are those bumps on top of the Antonov-225?

Why aren’t there water shutoff valves for each room?

How much can I judge a company based on a phone screening?

Website error: "Walmart can’t use this browser"

If you know the location of an invisible creature, can you attack it?



How to pass parameters to forward function of my torch nn.module from skorch.NeuralNetClassifier.fit()


How to flush output of print function?How to randomly select an item from a list?How do I return multiple values from a function?How to remove an element from a list by index?How to make a chain of function decorators?How do I pass a variable by reference?How do you read from stdin?How to remove a key from a Python dictionary?How padded sequences given as packed sequences are dealt by RNN in pytorch?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have extended nn.Module to implement my network whose forward function is like this ...



def forward(self, X, **kwargs):

batch_size, seq_len = X.size()

length = kwargs['length']
embedded = self.embedding(X) # [batch_size, seq_len, embedding_dim]
if self.use_padding:
if length is None:
raise AttributeError("Length must be a tensor when using padding")
embedded = nn.utils.rnn.pack_padded_sequence(embedded, length, batch_first=True)
#print("Size of Embedded packed", embedded[0].size())


hidden, cell = self.init_hidden(batch_size)
if self.rnn_unit == 'rnn':
out, _ = self.rnn(embedded, hidden)
elif self.rnn_unit == 'lstm':
out, (hidden, cell) = self.rnn(embedded, (hidden, cell))


# unpack if padding was used
if self.use_padding:
out, _ = nn.utils.rnn.pad_packed_sequence(out, batch_first = True)


I initialized a skorch NeuralNetClassifier like this,



net = NeuralNetClassifier(
model,
criterion=nn.CrossEntropyLoss,
optimizer=Adam,
max_epochs=8,
lr=0.01,
batch_size=32
)


Now if I call net.fit(X, y, length=X_len) it throws an error



TypeError: __call__() got an unexpected keyword argument 'length'


According to the documentation fit function expects a fit_params dictionary,




**fit_params : dict
Additional parameters passed to the ``forward`` method of
the module and to the ``self.train_split`` call.



and the source code always send my parameters to train_split where obviously my keyword argument would not be recognized.



Is there any way around to pass the arguments to my forward function?










share|improve this question
































    1















    I have extended nn.Module to implement my network whose forward function is like this ...



    def forward(self, X, **kwargs):

    batch_size, seq_len = X.size()

    length = kwargs['length']
    embedded = self.embedding(X) # [batch_size, seq_len, embedding_dim]
    if self.use_padding:
    if length is None:
    raise AttributeError("Length must be a tensor when using padding")
    embedded = nn.utils.rnn.pack_padded_sequence(embedded, length, batch_first=True)
    #print("Size of Embedded packed", embedded[0].size())


    hidden, cell = self.init_hidden(batch_size)
    if self.rnn_unit == 'rnn':
    out, _ = self.rnn(embedded, hidden)
    elif self.rnn_unit == 'lstm':
    out, (hidden, cell) = self.rnn(embedded, (hidden, cell))


    # unpack if padding was used
    if self.use_padding:
    out, _ = nn.utils.rnn.pad_packed_sequence(out, batch_first = True)


    I initialized a skorch NeuralNetClassifier like this,



    net = NeuralNetClassifier(
    model,
    criterion=nn.CrossEntropyLoss,
    optimizer=Adam,
    max_epochs=8,
    lr=0.01,
    batch_size=32
    )


    Now if I call net.fit(X, y, length=X_len) it throws an error



    TypeError: __call__() got an unexpected keyword argument 'length'


    According to the documentation fit function expects a fit_params dictionary,




    **fit_params : dict
    Additional parameters passed to the ``forward`` method of
    the module and to the ``self.train_split`` call.



    and the source code always send my parameters to train_split where obviously my keyword argument would not be recognized.



    Is there any way around to pass the arguments to my forward function?










    share|improve this question




























      1












      1








      1








      I have extended nn.Module to implement my network whose forward function is like this ...



      def forward(self, X, **kwargs):

      batch_size, seq_len = X.size()

      length = kwargs['length']
      embedded = self.embedding(X) # [batch_size, seq_len, embedding_dim]
      if self.use_padding:
      if length is None:
      raise AttributeError("Length must be a tensor when using padding")
      embedded = nn.utils.rnn.pack_padded_sequence(embedded, length, batch_first=True)
      #print("Size of Embedded packed", embedded[0].size())


      hidden, cell = self.init_hidden(batch_size)
      if self.rnn_unit == 'rnn':
      out, _ = self.rnn(embedded, hidden)
      elif self.rnn_unit == 'lstm':
      out, (hidden, cell) = self.rnn(embedded, (hidden, cell))


      # unpack if padding was used
      if self.use_padding:
      out, _ = nn.utils.rnn.pad_packed_sequence(out, batch_first = True)


      I initialized a skorch NeuralNetClassifier like this,



      net = NeuralNetClassifier(
      model,
      criterion=nn.CrossEntropyLoss,
      optimizer=Adam,
      max_epochs=8,
      lr=0.01,
      batch_size=32
      )


      Now if I call net.fit(X, y, length=X_len) it throws an error



      TypeError: __call__() got an unexpected keyword argument 'length'


      According to the documentation fit function expects a fit_params dictionary,




      **fit_params : dict
      Additional parameters passed to the ``forward`` method of
      the module and to the ``self.train_split`` call.



      and the source code always send my parameters to train_split where obviously my keyword argument would not be recognized.



      Is there any way around to pass the arguments to my forward function?










      share|improve this question
















      I have extended nn.Module to implement my network whose forward function is like this ...



      def forward(self, X, **kwargs):

      batch_size, seq_len = X.size()

      length = kwargs['length']
      embedded = self.embedding(X) # [batch_size, seq_len, embedding_dim]
      if self.use_padding:
      if length is None:
      raise AttributeError("Length must be a tensor when using padding")
      embedded = nn.utils.rnn.pack_padded_sequence(embedded, length, batch_first=True)
      #print("Size of Embedded packed", embedded[0].size())


      hidden, cell = self.init_hidden(batch_size)
      if self.rnn_unit == 'rnn':
      out, _ = self.rnn(embedded, hidden)
      elif self.rnn_unit == 'lstm':
      out, (hidden, cell) = self.rnn(embedded, (hidden, cell))


      # unpack if padding was used
      if self.use_padding:
      out, _ = nn.utils.rnn.pad_packed_sequence(out, batch_first = True)


      I initialized a skorch NeuralNetClassifier like this,



      net = NeuralNetClassifier(
      model,
      criterion=nn.CrossEntropyLoss,
      optimizer=Adam,
      max_epochs=8,
      lr=0.01,
      batch_size=32
      )


      Now if I call net.fit(X, y, length=X_len) it throws an error



      TypeError: __call__() got an unexpected keyword argument 'length'


      According to the documentation fit function expects a fit_params dictionary,




      **fit_params : dict
      Additional parameters passed to the ``forward`` method of
      the module and to the ``self.train_split`` call.



      and the source code always send my parameters to train_split where obviously my keyword argument would not be recognized.



      Is there any way around to pass the arguments to my forward function?







      python scikit-learn neural-network pytorch skorch






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 10:11









      nemo

      38.6k8 gold badges98 silver badges108 bronze badges




      38.6k8 gold badges98 silver badges108 bronze badges










      asked Mar 14 at 7:16









      BihanBihan

      104 bronze badges




      104 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          0














          The fit_params parameter is intended for passing information that is relevant to data splits and the model alike, like split groups.



          In your case, you are passing additional data to the module via fit_params which is not what it is intended for. In fact, you could easily run into trouble doing this if you, for example, enable batch shuffling on the train data loader since then your lengths and your data are misaligned.



          The best way to do this is already described in the answer to your question on the issue tracker:



          X_dict = 'X': X, 'length': X_len
          net.fit(X_dict, y)


          Since skorch supports dicts you can simply add the length's to your input dict and have it both passed to the module, nicely batched and passed through the same data loader. In your module you can then access it via the parameters in forward:



          def forward(self, X, length):
          return ...


          Further documentation of this behaviour can be found in the docs.






          share|improve this answer

























          • Thank you so much! Yes I figured it out.

            – Bihan
            Mar 27 at 12:43










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          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: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          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
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55156877%2fhow-to-pass-parameters-to-forward-function-of-my-torch-nn-module-from-skorch-neu%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          The fit_params parameter is intended for passing information that is relevant to data splits and the model alike, like split groups.



          In your case, you are passing additional data to the module via fit_params which is not what it is intended for. In fact, you could easily run into trouble doing this if you, for example, enable batch shuffling on the train data loader since then your lengths and your data are misaligned.



          The best way to do this is already described in the answer to your question on the issue tracker:



          X_dict = 'X': X, 'length': X_len
          net.fit(X_dict, y)


          Since skorch supports dicts you can simply add the length's to your input dict and have it both passed to the module, nicely batched and passed through the same data loader. In your module you can then access it via the parameters in forward:



          def forward(self, X, length):
          return ...


          Further documentation of this behaviour can be found in the docs.






          share|improve this answer

























          • Thank you so much! Yes I figured it out.

            – Bihan
            Mar 27 at 12:43















          0














          The fit_params parameter is intended for passing information that is relevant to data splits and the model alike, like split groups.



          In your case, you are passing additional data to the module via fit_params which is not what it is intended for. In fact, you could easily run into trouble doing this if you, for example, enable batch shuffling on the train data loader since then your lengths and your data are misaligned.



          The best way to do this is already described in the answer to your question on the issue tracker:



          X_dict = 'X': X, 'length': X_len
          net.fit(X_dict, y)


          Since skorch supports dicts you can simply add the length's to your input dict and have it both passed to the module, nicely batched and passed through the same data loader. In your module you can then access it via the parameters in forward:



          def forward(self, X, length):
          return ...


          Further documentation of this behaviour can be found in the docs.






          share|improve this answer

























          • Thank you so much! Yes I figured it out.

            – Bihan
            Mar 27 at 12:43













          0












          0








          0







          The fit_params parameter is intended for passing information that is relevant to data splits and the model alike, like split groups.



          In your case, you are passing additional data to the module via fit_params which is not what it is intended for. In fact, you could easily run into trouble doing this if you, for example, enable batch shuffling on the train data loader since then your lengths and your data are misaligned.



          The best way to do this is already described in the answer to your question on the issue tracker:



          X_dict = 'X': X, 'length': X_len
          net.fit(X_dict, y)


          Since skorch supports dicts you can simply add the length's to your input dict and have it both passed to the module, nicely batched and passed through the same data loader. In your module you can then access it via the parameters in forward:



          def forward(self, X, length):
          return ...


          Further documentation of this behaviour can be found in the docs.






          share|improve this answer













          The fit_params parameter is intended for passing information that is relevant to data splits and the model alike, like split groups.



          In your case, you are passing additional data to the module via fit_params which is not what it is intended for. In fact, you could easily run into trouble doing this if you, for example, enable batch shuffling on the train data loader since then your lengths and your data are misaligned.



          The best way to do this is already described in the answer to your question on the issue tracker:



          X_dict = 'X': X, 'length': X_len
          net.fit(X_dict, y)


          Since skorch supports dicts you can simply add the length's to your input dict and have it both passed to the module, nicely batched and passed through the same data loader. In your module you can then access it via the parameters in forward:



          def forward(self, X, length):
          return ...


          Further documentation of this behaviour can be found in the docs.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 27 at 10:26









          nemonemo

          38.6k8 gold badges98 silver badges108 bronze badges




          38.6k8 gold badges98 silver badges108 bronze badges















          • Thank you so much! Yes I figured it out.

            – Bihan
            Mar 27 at 12:43

















          • Thank you so much! Yes I figured it out.

            – Bihan
            Mar 27 at 12:43
















          Thank you so much! Yes I figured it out.

          – Bihan
          Mar 27 at 12:43





          Thank you so much! Yes I figured it out.

          – Bihan
          Mar 27 at 12:43








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • 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.

          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%2fstackoverflow.com%2fquestions%2f55156877%2fhow-to-pass-parameters-to-forward-function-of-my-torch-nn-module-from-skorch-neu%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript