22.02.2024 Views

Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

That’s perfectly fine, and it works quite well. But it also requires that you

specify the exponent every time you call the function. There must be another

way! Of course, there is; that’s the purpose of this section!

We need to build another (higher-order) function to build those functions

(square, cube, etc.) for us. The (higher-order) function is just a function

builder. But how do we do that?

First, let’s build the "skeleton" of the functions we are trying to generate; they

all take a single argument x, and they all perform an exponentiation, each

using a different exponent.

Fine. It should look like this:

def skeleton_exponentiation(x):

return x ** exponent

If you try calling this function with any x, say, skeleton_exponentiation(2),

you’ll get the following error:

skeleton_exponentiation(2)

Output

NameError: name 'exponent' is not defined

This is expected: Your "skeleton" function has no idea what the variable

exponent is! And that’s what the higher-order function is going to

accomplish.

We "wrap" our skeleton function with a higher-order function (which will

build the desired functions). Let’s call it, rather unimaginatively,

exponentiation_builder(). What are its arguments, if any? Well, we’re

trying to tell our skeleton function what its exponent should be, so let’s

start with that!

128 | Chapter 2: Rethinking the Training Loop

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!