Can I use AutoGrad if part the code that I want to differentiate is a PyTorch Network? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?multi-variable linear regression with pytorchGetting error while trying to run this command “ pipenv install requests ” in mac OSTransaction fails when calling contract function with return valuepipenv install fails when run inside a containerValueError: view limit minimum -36761.69947916667 is less than 1 and is an invalid Matplotlib date value.Trying to understand Pytorch neural translation code for decoderdask read_csv timeout on Amazon s3 with big filesPyTorch: Calculating the Hessian vector product with nn.parameters()PyTorch why does the forward function run multiple times and can I change the input shape?Error in predicting from RNN Model using Flask Server

How to draw this diagram using TikZ package?

Doubts about chords

Is the address of a local variable a constexpr?

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

Why is "Captain Marvel" translated as male in Portugal?

How do I mention the quality of my school without bragging

How do I stop a creek from eroding my steep embankment?

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

Why was the term "discrete" used in discrete logarithm?

Should I use Javascript Classes or Apex Classes in Lightning Web Components?

What are the motives behind Cersei's orders given to Bronn?

Is a manifold-with-boundary with given interior and non-empty boundary essentially unique?

How much radiation do nuclear physics experiments expose researchers to nowadays?

Single word antonym of "flightless"

Right-skewed distribution with mean equals to mode?

Gastric acid as a weapon

Is it possible to boil a liquid by just mixing many immiscible liquids together?

Did Kevin spill real chili?

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

Did Xerox really develop the first LAN?

When is phishing education going too far?

Is high blood pressure ever a symptom attributable solely to dehydration?

What is this single-engine low-wing propeller plane?

"Seemed to had" is it correct?



Can I use AutoGrad if part the code that I want to differentiate is a PyTorch Network?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?multi-variable linear regression with pytorchGetting error while trying to run this command “ pipenv install requests ” in mac OSTransaction fails when calling contract function with return valuepipenv install fails when run inside a containerValueError: view limit minimum -36761.69947916667 is less than 1 and is an invalid Matplotlib date value.Trying to understand Pytorch neural translation code for decoderdask read_csv timeout on Amazon s3 with big filesPyTorch: Calculating the Hessian vector product with nn.parameters()PyTorch why does the forward function run multiple times and can I change the input shape?Error in predicting from RNN Model using Flask Server



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am trying to use AutoGrad to calculate the derivative of a certain piece of code.
A part of this code, consists of a Neural Network implemented in PyTorch.
However, I have some troubles to use AutoGrad to calculate the derivative of my NN.



I created a small script to reproduce the problem :



import torch
import autograd.numpy as np
from autograd import grad

inputDimension = 10
hiddenLayerDimension = 10
outputDimension = 1

model = torch.nn.Sequential(
torch.nn.Linear(inputDimension, hiddenLayerDimension),
torch.nn.ReLU(),
torch.nn.Linear(hiddenLayerDimension, outputDimension),
)

def functionToDifferentiate(input):
# This line below represents the 'other' calculations. In reality it is more involved
scaledInput = input * 3
inputTensor = torch.from_numpy(scaledInput).type(torch.FloatTensor)
return model(inputTensor)

randomInput = np.random.rand(inputDimension)
gradientFunctionOfModel = grad(functionToDifferentiate)

print(functionToDifferentiate(randomInput))
print(gradientFunctionOfModel(randomInput))


When running this code, the last line crashes with the following stack trace:



Traceback (most recent call last):
File "replaced_for_privacy_reasons/stackOverFlowQuestion.py", line 25, in <module>
print(gradientFunctionOfModel(randomInput))
File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/wrap_util.py", line 20, in nary_f
return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/differential_operators.py", line 24, in grad
vjp, ans = _make_vjp(fun, x)
File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/core.py", line 10, in make_vjp
end_value, end_node = trace(start_node, fun, x)
File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/tracer.py", line 10, in trace
end_box = fun(start_box)
tensor([0.0228], grad_fn=<AddBackward0>)
File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/wrap_util.py", line 15, in unary_f
return fun(*subargs, **kwargs)
File "replaced_for_privacy_reasons/stackOverFlowQuestion.py", line 18, in functionToDifferentiate
inputTensor = torch.from_numpy(input).type(torch.FloatTensor)
TypeError: expected np.ndarray (got ArrayBox)


I do know that it is possible to create my inputs directly as PyTorch Tensors, instead of as Numpy vectors and calculate gradients wrt to those vectors.
This is however not a good option for me, since this Neural Network is only part of a complete function for which I want to calculate the Gradient.



Any help is highly appreciated










share|improve this question




























    0















    I am trying to use AutoGrad to calculate the derivative of a certain piece of code.
    A part of this code, consists of a Neural Network implemented in PyTorch.
    However, I have some troubles to use AutoGrad to calculate the derivative of my NN.



    I created a small script to reproduce the problem :



    import torch
    import autograd.numpy as np
    from autograd import grad

    inputDimension = 10
    hiddenLayerDimension = 10
    outputDimension = 1

    model = torch.nn.Sequential(
    torch.nn.Linear(inputDimension, hiddenLayerDimension),
    torch.nn.ReLU(),
    torch.nn.Linear(hiddenLayerDimension, outputDimension),
    )

    def functionToDifferentiate(input):
    # This line below represents the 'other' calculations. In reality it is more involved
    scaledInput = input * 3
    inputTensor = torch.from_numpy(scaledInput).type(torch.FloatTensor)
    return model(inputTensor)

    randomInput = np.random.rand(inputDimension)
    gradientFunctionOfModel = grad(functionToDifferentiate)

    print(functionToDifferentiate(randomInput))
    print(gradientFunctionOfModel(randomInput))


    When running this code, the last line crashes with the following stack trace:



    Traceback (most recent call last):
    File "replaced_for_privacy_reasons/stackOverFlowQuestion.py", line 25, in <module>
    print(gradientFunctionOfModel(randomInput))
    File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/wrap_util.py", line 20, in nary_f
    return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
    File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/differential_operators.py", line 24, in grad
    vjp, ans = _make_vjp(fun, x)
    File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/core.py", line 10, in make_vjp
    end_value, end_node = trace(start_node, fun, x)
    File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/tracer.py", line 10, in trace
    end_box = fun(start_box)
    tensor([0.0228], grad_fn=<AddBackward0>)
    File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/wrap_util.py", line 15, in unary_f
    return fun(*subargs, **kwargs)
    File "replaced_for_privacy_reasons/stackOverFlowQuestion.py", line 18, in functionToDifferentiate
    inputTensor = torch.from_numpy(input).type(torch.FloatTensor)
    TypeError: expected np.ndarray (got ArrayBox)


    I do know that it is possible to create my inputs directly as PyTorch Tensors, instead of as Numpy vectors and calculate gradients wrt to those vectors.
    This is however not a good option for me, since this Neural Network is only part of a complete function for which I want to calculate the Gradient.



    Any help is highly appreciated










    share|improve this question
























      0












      0








      0








      I am trying to use AutoGrad to calculate the derivative of a certain piece of code.
      A part of this code, consists of a Neural Network implemented in PyTorch.
      However, I have some troubles to use AutoGrad to calculate the derivative of my NN.



      I created a small script to reproduce the problem :



      import torch
      import autograd.numpy as np
      from autograd import grad

      inputDimension = 10
      hiddenLayerDimension = 10
      outputDimension = 1

      model = torch.nn.Sequential(
      torch.nn.Linear(inputDimension, hiddenLayerDimension),
      torch.nn.ReLU(),
      torch.nn.Linear(hiddenLayerDimension, outputDimension),
      )

      def functionToDifferentiate(input):
      # This line below represents the 'other' calculations. In reality it is more involved
      scaledInput = input * 3
      inputTensor = torch.from_numpy(scaledInput).type(torch.FloatTensor)
      return model(inputTensor)

      randomInput = np.random.rand(inputDimension)
      gradientFunctionOfModel = grad(functionToDifferentiate)

      print(functionToDifferentiate(randomInput))
      print(gradientFunctionOfModel(randomInput))


      When running this code, the last line crashes with the following stack trace:



      Traceback (most recent call last):
      File "replaced_for_privacy_reasons/stackOverFlowQuestion.py", line 25, in <module>
      print(gradientFunctionOfModel(randomInput))
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/wrap_util.py", line 20, in nary_f
      return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/differential_operators.py", line 24, in grad
      vjp, ans = _make_vjp(fun, x)
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/core.py", line 10, in make_vjp
      end_value, end_node = trace(start_node, fun, x)
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/tracer.py", line 10, in trace
      end_box = fun(start_box)
      tensor([0.0228], grad_fn=<AddBackward0>)
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/wrap_util.py", line 15, in unary_f
      return fun(*subargs, **kwargs)
      File "replaced_for_privacy_reasons/stackOverFlowQuestion.py", line 18, in functionToDifferentiate
      inputTensor = torch.from_numpy(input).type(torch.FloatTensor)
      TypeError: expected np.ndarray (got ArrayBox)


      I do know that it is possible to create my inputs directly as PyTorch Tensors, instead of as Numpy vectors and calculate gradients wrt to those vectors.
      This is however not a good option for me, since this Neural Network is only part of a complete function for which I want to calculate the Gradient.



      Any help is highly appreciated










      share|improve this question














      I am trying to use AutoGrad to calculate the derivative of a certain piece of code.
      A part of this code, consists of a Neural Network implemented in PyTorch.
      However, I have some troubles to use AutoGrad to calculate the derivative of my NN.



      I created a small script to reproduce the problem :



      import torch
      import autograd.numpy as np
      from autograd import grad

      inputDimension = 10
      hiddenLayerDimension = 10
      outputDimension = 1

      model = torch.nn.Sequential(
      torch.nn.Linear(inputDimension, hiddenLayerDimension),
      torch.nn.ReLU(),
      torch.nn.Linear(hiddenLayerDimension, outputDimension),
      )

      def functionToDifferentiate(input):
      # This line below represents the 'other' calculations. In reality it is more involved
      scaledInput = input * 3
      inputTensor = torch.from_numpy(scaledInput).type(torch.FloatTensor)
      return model(inputTensor)

      randomInput = np.random.rand(inputDimension)
      gradientFunctionOfModel = grad(functionToDifferentiate)

      print(functionToDifferentiate(randomInput))
      print(gradientFunctionOfModel(randomInput))


      When running this code, the last line crashes with the following stack trace:



      Traceback (most recent call last):
      File "replaced_for_privacy_reasons/stackOverFlowQuestion.py", line 25, in <module>
      print(gradientFunctionOfModel(randomInput))
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/wrap_util.py", line 20, in nary_f
      return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/differential_operators.py", line 24, in grad
      vjp, ans = _make_vjp(fun, x)
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/core.py", line 10, in make_vjp
      end_value, end_node = trace(start_node, fun, x)
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/tracer.py", line 10, in trace
      end_box = fun(start_box)
      tensor([0.0228], grad_fn=<AddBackward0>)
      File "replaced_for_privacy_reasons/venv/lib/python3.6/site-packages/autograd/wrap_util.py", line 15, in unary_f
      return fun(*subargs, **kwargs)
      File "replaced_for_privacy_reasons/stackOverFlowQuestion.py", line 18, in functionToDifferentiate
      inputTensor = torch.from_numpy(input).type(torch.FloatTensor)
      TypeError: expected np.ndarray (got ArrayBox)


      I do know that it is possible to create my inputs directly as PyTorch Tensors, instead of as Numpy vectors and calculate gradients wrt to those vectors.
      This is however not a good option for me, since this Neural Network is only part of a complete function for which I want to calculate the Gradient.



      Any help is highly appreciated







      python pytorch autograd






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 16:20









      Filip DeleersnijderFilip Deleersnijder

      11




      11






















          0






          active

          oldest

          votes












          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%2f55067107%2fcan-i-use-autograd-if-part-the-code-that-i-want-to-differentiate-is-a-pytorch-ne%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















          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%2f55067107%2fcan-i-use-autograd-if-part-the-code-that-i-want-to-differentiate-is-a-pytorch-ne%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

          AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

          Алба-Юлія

          Захаров Федір Захарович