Skip to content
ImagineWorld

Functions

node_idnode-book_mathematics-of-machine-learning_chapter-09-functions
node_typechapter_node
schema_profileworld.chapter_node.v1
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
statusactive
chapter_num9
chapter_titleFunctions
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

”Mathematicians are like Frenchmen: whatever you say to them they translate into their own language and forthwith it is something entirely different.”

— Johann Wolfgang von Goethe

It’s time we tackle the next big subject of machine-learning-math: functions and calculus. What do we have to do with functions?

As we’ve seen before, a predictive model is nothing but a multivariate parametric function. Linear regression? Ax. Logistic regression? σ(Ax). Neural networks? A sequence of σ(Ax)-s, and a multitude of other layers.

But it’s not just the description of models, it’s fitting them to the data. Say, for a simple linear regression model, “training” is minimizing the mean squared error; that is, finding

 n 1-∑ 2 argmina,b∈ℝn (axi + b − yi), i=1

where xi is the training data, and yi is the ground truth. This is done via differentiation, one of humanity’s most essential inventions. (Whether we can call mathematical discoveries inventions is a matter of constant debate.)

For a function f(x), its derivative at x0 is defined by

f ′(x0) = lim f-(x)−-f(x0), x→x0 x − x0

describing the rate of change in terms of x . There’s a lot to unravel: what is that strange limx→x0 symbol? What do the ratio f(x)−f(x0)- x−x0 represent? We’ll get to all of it in due time. The gist is, differentiation is the driving force of gradient descent, the number one algorithm for training neural networks.

But it does not end here either. Differentiation has an equally important counterpart: integration. The formula

∫ b f(x)dx a

is called the integral of f(x), describing the signed area under its graph. Integration is not as prevalent in practice, but it’s an essential tool for theory. For instance, half of probability theory is built around it. Say, the famous expected value is defined in terms of an integral; as are several notable probability distributions.

In the next couple of chapters, we’ll dive deep into calculus, the theory of univariate functions. Why? Because even though machine learning is multivariate, the ideas we develop here will serve as the foundations for all the math to come. Let’s get to work!

day-mode Bookmark

Everyone has an intuitive understanding of what functions are. At one point or another, all of us have encountered this concept. For most of us, a function is a curve drawn with a continuous line onto a representation of the Cartesian coordinate system.

PIC

Figure 9.1: Definitely looks like a function

However, in mathematics, intuitions can often lead us to false conclusions. Often, there is a difference between what something is and how you think about it – what your mental models are. To give an example from a real-life scenario in machine learning, consider the following piece of code:

import numpy as np
def cross_entropy_loss(X, y):
"""
Args:
X: numpy.ndarray of shape (n_batch, n_dim).
Contains the predictions in form of a probability distribution.
y: numpy.ndarray of shape (n_batch, 1).
Contains class labels for each data point in X.
Returns:
loss: numpy.float.
Cross entropy loss of the predictions.
"""
exp_x = np.exp(X)
probs = exp_x / np.sum(exp_x, axis=1, keepdims=True)
log_probs = - np.log([probs[i, y[i]] for i in range(len(probs))])
loss = np.mean(log_probs)
return loss

Suppose that you wrote this function, and it is in your codebase somewhere. Depending on our needs, we might think of it as cross-entropy loss, but in reality, this is a 579-character-long string in the Python language, eventually processed by an interpreter. However, when working with it, we often use a mental model that compacts this information into easily usable chunks, like the three words cross-entropy loss. When we reason about high-level processes like training a neural network, abstractions such as this allow us to move further and step bigger.

But sometimes, things don’t go our way. When this function throws an error and crashes the computations, cross-entropy loss will not cut it. Then, it is time to unravel the definition and put everything under a magnifying glass. What could have hindered your thinking before is now essential.

These principles are also true for theory, not just for practice. Mathematics is a balancing act between logical precision and a clear understanding, two often contradicting objectives.

Let’s go back to our starting point: functions in a mathematical sense. One possible mental model, as mentioned, is a curve drawn with a continuous line. It allows us to reason about functions visually and intuitively answer some questions. However, this particular mental model can go very wrong.

To give an example, does Figure 9.2 depict a function?

PIC

Figure 9.2: Is this a function?

Even though this curve is drawn with a continuous line, this is not a function, as there are values with multiple images, which cannot happen. To avoid confusion later, we have to build the foundations of our discussion if we were to talk about mathematical objects. In this chapter, our goal is to establish a basic dictionary to properly understand the objects we are working with in machine learning.

9.1.1 The mathematical definition of a function

Section titled “9.1.1 The mathematical definition of a function”

Let’s dive straight into the deep water and see the exact mathematical definition of functions! (Don’t worry if you don’t understand it for the first read. I’ll explain everything in detail. This is the usual experience when encountering a definition for the first time.)

Definition 35. (Functions)

Let X and Y be two sets. The subset f ⊆X ×Y is a function if for every x ∈X, there is at most one y ∈Y such that (x,y) ∈f.

(The set X ×Y denotes the Cartesian product of X and Y . If you are not familiar with the concept, check out Appendix C.)

For simplicity, we introduce the notation

f : X → Y,

which is short for f is a function from X to Y .

Note that X and Y can be any set. In the examples we encounter, these are usually the set of real numbers or vectors, but there is no such restriction.

To visualize the definition, we can draw two sets and arrows pointing from elements of X to elements of Y . Each element (x,y) ∈f represents an arrow, pointing from x to y.

PIC

Figure 9.3: A function, as arrows between two sets

The only criteria is that there can be at most one arrow starting from any x ∈X. This is why Figure 9.2 is not a function.

Defining a function as a subset is mathematically precise but very low level. To be more useful, we can introduce an abstraction by defining functions with formulas, such as

f : ℝ → ℝ, x ↦→ x2,

or simply f(x) = x2 in short. This is how most of us think about functions when working with them.

Now that we are familiar with the definition, we should get to know some of the most basic structural properties of functions.

We saw that, in essence, functions are arrows between sets. At this point, we don’t know anything useful about them. When is a function invertible? How can we find their minima and maxima? Why should we even care? Probably you have a bunch of questions here. Slowly but surely, we will cover all of these.

The first steps in our journey are concerned with the sets from which arrows start and point. There are two important sets in a function’s life: its domain and image.

Definition 36. (Domain and image of functions)

Let f : X →Y be a function. The sets

domf := {x ∈ X : there is an y ∈ Y such that f(x) = y} ⊆ X

and

im f := {y ∈ Y : there is an x ∈ X such that f(x) = y} ⊆ Y

are respectively called the domain and image of f.

In other words, the domain is the subset of X where arrows start; the image is the subset of Y where arrows point.

PIC

Figure 9.4: The domain and image of a function

Why is this important? For one, these are directly related to the invertibility of a function. If you consider the ”points and arrows” mental representation, inverting a function is as simple as flipping the direction of the arrows. When can we do it? In some cases, doing this might not even result in a function, as Figure 9.5 shows.

PIC

Figure 9.5: This function is not invertible, as reversing the arrows doesn’t give a well-defined function

To put the study of functions on top of solid theoretical foundations, we introduce the concept of injective, surjective and bijective functions.

Definition 37. (Surjective, injective, and bijective functions)

Let f : X →Y be an arbitrary function.

(a) f is injective if for every y ∈Y there is at most one x ∈X such that f(x) = y. (We often say that an injective f is a one-to-one function.)

(b) f is surjective if for every y ∈Y there is an x ∈X such that f(x) = y. (We often say that a surjective f maps X onto Y .)

(c) f is bijective if it is injective and surjective.

In terms of arrows, injectivity means that every element of the image has at most one arrow pointing to it, while surjectivity is that every element indeed has at least one arrow. When both are satisfied, we have a bijective function, one that can be inverted properly. When the inverse f−1 exists, it is unique. Both f−1 ∘f and f ∘f−1 equal to the identity function in their respective domains.

Let’s see some concrete examples! For instance,

f : ℝ → ℝ, f(x) = x2

is not injective nor surjective. (Ponder on this a bit if you don’t understand it right away. It helps if you draw a figure.)

PIC

Figure 9.6: Injective, surjective, and bijective functions

On the contrary,

 3 g : ℝ → ℝ, g(x) = x

is both, so it is bijective and invertible with inverse g−1(x) = x1∕3.

Invertible functions behave nicely, and from a certain perspective, they are much better to work with.

Functions, just like numbers, have operations defined on them. Two numbers can be multiplied and added together, but can you do the same with functions? Without any difficulty, they can be added together and multiplied with a scalar as

(f + g)(x) := f(x)+ g(x ), (cf)(x) := cf(x),

where c is some scalar.

PIC

Figure 9.7: Composing functions

Another essential operation is composition. Let’s consider the famous logistic regression for a minute! The estimator itself is defined by

f(x) = σ(ax + b),

where

σ(x) = ---1--- 1 + e−x

is the sigmoid function. The estimator f(x) is the composition of two functions: l(x) = ax + b and the sigmoid function, so

f(x) = σ(l(x)).

As σ maps ℝ onto [0,1], we can think about f(x) as the probability that x belongs to the positive class.

Figure 9.7 shows the points-and-arrows illustration of function composition.

To give one more example, a neural network with several hidden layers is just the composition of a bunch of functions. The output of each layer is fed into the next one, which is exactly how composition is defined.

In general, if f : Y →Z and g : X →Y are two functions, then their composition is formally defined by

f ∘ g : X → Z, x ↦→ f (g(x )).

Note that in (f ∘g)(x) = f(g(x)), the function g is applied first. The order of application is often a point of confusion, so keep this in mind.

Remark 8. (Function addition as composition)

Given the functions

f : X → ℝ, g : X → ℝ,

we can define their sum by

(f + g)(x) := f(x)+ g(x ).

Believe it or not, this is yet another form of function composition. Why? Define the function add by

add : X × X → ℝ, add(x1,x2) = x1 + x2.

Now we can write addition as

(f + g )(x) = add(f(x),g(x)).

Composition is an extremely powerful tool. In fact, so powerful that given a small set of cleverly defined building blocks, “almost every function” can be obtained as the composition of these blocks. (I put “almost every function” in quotes because if we want to stay mathematically precise here, long detours are needed. To keep ourselves focused, let’s allow ourselves to be a little hand-wavy here.)

So far, we have seen that functions are defined as arrows drawn between elements of two sets. This, although being mathematically rigorous, does not give us useful mental models to reason about them. As you’ll surely see by the end of our journey, in mathematics, the key is often to find the right way to look at things.

Regarding functions, one of the most common and useful mental models is their graph.

If f : ℝ →ℝ is a function mapping a real number to a real number, we can visualize it using its graph, defined by

graph(f) := {(x,f(x)) : x ∈ ℝ }.

This set of points can be drawn in the two-dimensional plane. For instance, in the case of the famous rectified linear unit (ReLU)

 ( |{ ReLU (x ) = 0 if x <0 |( x if 0 ≤ x,

the graph looks like this.

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, 400)
relu = np.maximum(0, x)
with plt.style.context("seaborn-v0_8-white"):
plt.figure()
plt.plot(x, relu, label="ReLU(x)", color="blue")
plt.axhline(0, color='black', linewidth=0.8, linestyle="--")
plt.title("ReLU", fontsize=14)
plt.xlabel("x", fontsize=12)
plt.ylabel("ReLU(x)", fontsize=12)
plt.grid(alpha=0.3)
plt.show()

PIC

Figure 9.8: Graph of the ReLU function

Although identifying functions with their graphs can be useful, it is not generalizable for more complex mappings. Visualizing it is challenging if the function’s domain and image are not the set of real numbers.

PIC

Figure 9.9: Functions as a transformation of the space. Here, the vectors of the space are rotated around the origin

When dealing with neural networks, probably the best way to think about functions (that is, layers in this context) is as transformations of the underlying feature space. A simple example is a rotation in the two-dimensional Euclidean plane, as Figure 9.9 shows.

PIC

Figure 9.10: Examplar applications of image transformations available in Albumenations

Image transformations provide a set of more complex examples. You rarely think about image blur as a transformation between spaces, but this is the case. After all, an image is just a huge vector in some vector space.

Image operations as transformations, as done by the Albumentations ( https://albumentations.ai/) library. Source of the image: Albumentations: Fast and Flexible Image Augmentations by Alexander Buslaev, Vladimir I. Iglovikov, Eugene Khvedchenya, Alex Parinov, Mikhail Druzhinin and Alexandr A. Kalinin ( https://www.mdpi.com/2078-2489/11/2/125).

In essence, a neural network is simply a stack of transformations, each taking its input from the output of the previous one. As you’ll see, what makes them special is that the transformations are not hand-engineered but learned from the data.

day-mode Bookmark

In our study of functions, we started from arrows between sets and ended up with mental models such as formulas and graphs. For pure mathematical purposes, these models are perfectly enough to conduct thorough investigations. However, once we leave the realm of theory and start putting things into practice, we must think about how functions are represented in programming languages.

In Python, functions are defined using a straightforward syntax. For instance, this is how the square(x) = x2 function can be implemented.

def square(x):
return x**2

The result is an object of type function. (In Python, everything is an object.)

type(square)
function

Functions are called using the () operator.

square(12)
144

Python is well-known for its simplicity, and functions are no exception. However, this doesn’t mean that they are limited in features – quite the contrary: you can achieve a lot with the clever use of functions.

There are three operations that we want to do on functions: composition, addition, multiplication. The easiest way is to call the functions themselves and fall back to the operations defined for the number types. To see an example, let’s implement the cube(x) = x3 function and add/multiply/compose it with square.

def cube(x):
return x**3
x = 2
square(x) + cube(x) # addition
12
square(x)*cube(x) # multiplication
32
square(cube(x)) # composition
64

However, there is a major problem. If you take another look at the function operations, you can notice that they take functions and return functions. For instance, the composition is defined by

compose : f,g ↦→ (x ↦→ f(g(x))) , ◟-----◝◜----◞ the composed function

with a function as a result. We did no such thing by simply passing the return value to the outer function. There is no function object to represent the composition.

In Python, functions are first-class objects, meaning that we can pass them to other functions and return them from functions. (This is an absolutely fantastic feature, but if this is the first time you’ve encountered this, it might take some time to get used to.)

Thus, we can implement the compose function above by using the first-class function feature.

def compose(f, g):
def composition(*args, **kwargs):
return f(g(*args, **kwargs))
return composition
square_cube_composition = compose(square, cube)
square_cube_composition(2)
64

Addition and multiplication can be done just like this. (They are even assigned as an exercise problem Section 9.4.)

The standard way of doing function definitions is not a good fit for an application that is essential for us: parametrized functions. Think about the case of linear functions of the form ax + b, where a and b are parameters. On the first try, we can do something like this.

def linear(x, a, b):
return a*x + b

Passing the parameters as arguments seems to work, but there are serious underlying issues. For instance, functions can have a lot of parameters. Even if we compact parameters into multidimensional arrays, we might need to deal with dozens of such arrays. Passing them around manually is error-prone, and we usually have to work with multiple functions. For example, neural networks are composed of several layers. Each layer is a parameterized function, and their composition yields a predictive model.

We can solve this issue by applying the classical object-oriented principle of encapsulation, implementing functions as callable objects. In Python, we can do this by implementing the magic __call__ method for the class.

class Linear:
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self, x):
return self.a*x + self.b
f = Linear(2, -1) # this represents the function f(x) = 2*x - 1
f(2.1)
3.2

This way, we can store, access, and modify the parameters using attributes.

f.a, f.b
(2, -1)

Since there can be a lot of parameters, we should implement a method that collects them together in a dictionary.

class Linear:
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self, x):
return self.a*x + self.b
def parameters(self):
return {"a": self.a, "b": self.b}
f = Linear(2, -1)
f.parameters()
{'a': 2, 'b': -1}

Interactivity is one of the most useful features of Python. In practice, we frequently find ourselves working in the REPL, inspecting objects and calling functions by hand. We often add a concise string representation for our classes for these situations.

By default, printing a Linear instance results in a cryptic message.

f
<__main__.Linear at 0x7c9fbef31190>

This is not very useful. Besides the class name and its location in the memory, we haven’t received any information. We can change this by implementing the __repr__ method responsible for returning the string representation for our object.

class Linear:
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self, x):
return self.a*x + self.b
def __repr__(self):
return f"Linear(a={self.a}, b={self.b})"
def parameters(self):
return {"a": self.a, "b": self.b}
f = Linear(2, -1)
f
Linear(a=2, b=-1)

This looks much better! Adding a pretty string representation seems like a small thing, but this can go a long way when doing machine learning engineering in the trenches.

The Linear class that we have just seen is only the tip of the iceberg. There are hundreds of function families that are used in machine learning. We’ll implement many of them eventually, and to keep the interfaces consistent, we are going to add a base class from which all others will be inherited.

class Function:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
pass
def parameters(self):
return dict()

With this, we can implement functions and function families in the following way.

import numpy as np
class Sigmoid(Function): # the parent class is explicitly declared
def __call__(self, x):
return 1/(1 + np.exp(-x))
sigmoid = Sigmoid()
sigmoid(2)
np.float64(0.8807970779778823)

Even though we haven’t implemented the parameters method for the Sigmoid class, it is inherited from the base class.

sigmoid.parameters()
{}

For now, let’s keep the base class as simple as possible. During the course of this book, we’ll progressively enhance the Function base class to cover all the methods a neural network and its layers need. (For instance, gradients.)

9.2.4 Composition in the object-oriented way

Section titled “9.2.4 Composition in the object-oriented way”

Recall how we did function composition (in Section 9.2.1) when working with plain Python functions? Syntactically, that can work with our Function class as well, although there is a huge issue: the return value is not a Function type.

composed = compose(Linear(2, -1), Sigmoid())
composed(2)
np.float64(0.7615941559557646)
isinstance(composed, Function)
False

This kind of composition doesn’t inherit the interface we need.

composed.parameters()
---------------------------------------------------------------------------
AttributeError                          Traceback (most recent call last)
Cell In[33], line 1
----> 1 composed.parameters()
AttributeError: ’function’ object has no attribute ’parameters’

To fix the issue, we implement function composition as a child of the Function base class. Recall that composition is a function, taking two functions as input and returning one:

compose : f, g ↦→ (◟x-↦→-f◝(g◜-(x-)))◞ . the composed function

Keeping this in mind, this is how we can do composition.

class Composition(Function):
def __init__(self, *functions):
self.functions = functions
def __call__(self, x):
for f in reversed(self.functions):
x = f(x)
return x

(Note that due to how composition is defined, we iterate through the list of functions in the reverse order. That’s because (f ∘g)(x) = f(g(x)), we apply g first.)

composed = Composition(Linear(2, -1), Sigmoid())
composed(2)
np.float64(0.7615941559557646)

This way, we get to keep the Function interface.

composed.parameters()
{}
isinstance(composed, Function)
True

day-mode Bookmark

Now that we’ve learned what functions really are, I bet your world is a bit shaken. Functions as graphs drawn with continuous lines, sure. Maybe even expressions like f(x) = x2 + 1. But functions as dots and arrows?

Surprisingly, the dot-and-arrow representation is the closest to the true definition. Graphs and expressions come after that. This is what we’ve learned in this chapter, and by now, I feel like a magician. I’ve shown you mathematical objects and revealed that, deep inside, they are not what you think. We did this with vectors, matrices, and now, with functions.

Along with the “what’s behind the curtain?” tricks, putting theory into practice also became an established pattern for us. So, we’ve used object-oriented Python to get a taste of what a function is like.

Next, we’ll turn our lenses to an even higher level of magnification. For us, the most important functions map numbers to numbers. But what’s a number? Even in programming languages, we have several different number types, like int-s, float-s, double-s, and so on. These are deeply rooted in math, and familiarity with the structure of numbers is a must for every developer and engineer.

See you in the next chapter!

day-mode Bookmark

Problem 1. Which of these functions are injective, surjective, or bijective? Find the inverse of bijective functions.

(a) f : ℝ → (0,∞), x→ex (b) g : ℝ → [0,∞), x→x2 (c) h : [0,∞) → [0,∞), x→x2 (d) sin : ℝ → [0,1], x→sin(x) (e) tan : ℝ →ℝ, x→tan(x),

Problem 2. Find a function f : ℝ →ℝ such that (f ∘f)(x) = −x.

Problem 3. Can any real function g : ℝ →ℝ be obtained as g = f ∘f for some f : ℝ →ℝ?

Problem 4. Following the example of the composition Section 9.2.1, implement

  • the add function, taking f and g, returning f + g,
  • the mul function, taking f and g, returning fg,
  • and the div function, taking f and g, returning f∕g.