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.

Higher-Order Functions

Although this is more of a coding topic, I believe it is necessary to have a good

grasp on how higher-order functions work to fully benefit from Python’s

capabilities and make the best out of our code.

I will illustrate higher-order functions with an example so that you can gain a

working knowledge of it, but I am not delving any deeper into the topic, as it

is outside the scope of this book.

Let’s say we’d like to build a series of functions, each performing an

exponentiation to a given power. The code would look like this:

def square(x):

return x ** 2

def cube(x):

return x ** 3

def fourth_power(x):

return x ** 4

# and so on and so forth...

Well, clearly there is a higher structure to this:

• every function takes a single argument x, which is the number we’d like

to exponentiate

• every function performs the same operation, an exponentiation, but

each function has a different exponent

One way of solving this is to make the exponent an explicit argument, just

like the code below:

def generic_exponentiation(x, exponent):

return x ** exponent

Rethinking the Training Loop | 127

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

Saved successfully!

Ooh no, something went wrong!