Mathematical functions for data science & artificial intelligence#

Algebraic functions#

Linear functions#

Tiene la forma de $\(f(x)=mx + b\)\( donde \)m\( y \)b\( \)\in R$.

\(m\) puede ser calculada por: $\(m=\frac{y_{2}-y_{1}}{x_{2}-x_{1}}\)$

y \(b\) es el punto de corte con el eje \(y\). Su dominio es \(Dom_{f} = (-\infty, \infty)\). Su imagen es \(Im_{f} = (-\infty, \infty)\)

coding a linear function#

import numpy as np
import matplotlib.pyplot as plt

N = 100

#slope
m = -1

#intercept
b = 3

#let's define the function
def f(x):
  return (m*x + b)

#domain
x = np.linspace(-10,10, num=N)

#range
y = f(x)

fig, ax = plt.subplots()
ax.plot(x,y)
ax.grid()
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[1], line 2
      1 import numpy as np
----> 2 import matplotlib.pyplot as plt
      4 N = 100
      6 #slope

ModuleNotFoundError: No module named 'matplotlib'

Polinomic functions#

Tiene la forma de $\(P(x)=a_{n}x^{n} + a_{n-1}x^{n-1}+...+a_{2}x^{2}+a_{1}x + a_{1}\)$

a una función que tiene esta forma se le llama polinomio de grado \(n\). A los elementos \(a\) los llamaremos coeficientes donde \(a \in R\).

Por ejemplo:

\[P(x)= 2x^{7} - x^{4} + 3x^{2} + 4\]

que es un polinomio de grado 7.

def f2(x):
    return(2*(x**7) - x**4 + 3*(x**2) + 4)

y2 = f2(x)

fig, ax2 = plt.subplots()
ax2.plot(x,y2)
ax2.grid()
../_images/fc61c0adf236a9eddecba8c42a0c0c7a9b4c818f15cdbbc02bbcbe6360d91439.png

Power Function#

Hay unas funciones que son un caso particular de las funciones polinómicas que son las funciones potencia, las cuales tienen la forma:

\[f(x)= x^{a}, a \in R\]

Por ejemplo:

\[f(x)= x^{2}\]

El dominio de \(f(x)=x^{2}\) es \(Dom_{f} = (-\infty, \infty)\). Su imagen es \(Im_{f} = [0, \infty)\)

Coding a power function#

def f3(x):
  return 7**x

y3 = f3(x)

fig, ax3 = plt.subplots()
ax3.plot(x,y3)
ax3.grid()
../_images/098227ebe7cfc998f13f0dbef9ff85cc1ee18745899476a92ee1a792d2783651.png

Trascendent functions#

these are functions that cannot be expressed as polynomials

Trigonometric functions#

def f(x):
  return np.cos(x)

y = f(x)

plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x7f7f7b89f4c0>]
../_images/e5748bb43cce8b183ea20a7972f0e08cb60d44a0a46f6d237702c6b7bbf73695.png

Exponential function#

Tienen la forma de $\(f(x)=a^x\)\( donde la base \)a$ es una constante positiva. Un gran ejemplo de una función exponencial es usando la base como el número de euler:

\[f(x)=e^x\]
def f(x):
  return np.exp(x)    #euler

y=f(x)

plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x7f7f7b82c4c0>]
../_images/d18a179339e9bf05c202671f26cf15205c2967ee2c02fa52bc93e3e67da5eb2f.png

Logarithmic functions#

El logaritmo está definido por la relación:

\[log_{b}(x) = n \Longleftrightarrow x=b^n\]

donde:

  • \(b\) es la base.

  • \(n\) es el exponente al que está elevado la base.

  • \(x\) es el resultado de elevar la base \(b\) al exponente \(n\)

Ejemplo:

Teniendo b=2 y n=8, entonces:

\[2^8=256\]

Por lo que \(x=256\). Calculando el logaritmo base 2 de \(x\) es:

\[log_{2}(256) = 8\]
def f(x):
    return np.log2(x)

#domain
x = np.linspace(0, 10, 1000)

plt.plot(x, f(x))
plt.show()
/tmp/ipykernel_224/3839064836.py:2: RuntimeWarning: divide by zero encountered in log2
  return np.log2(x)
../_images/e79f6ae31e8bc71d4f058751d59cdb0135302304e609ba858c9e1f22ba495930.png

Heavyside function#

Son funciones que tienen diferentes valores definidos por un intervalo. Por ejemplo la función escalón de Heaviside:

\[\begin{split}H(x) = \begin{cases} 0, &\quad \text{para, } x < 0 \\ 1, &\quad\text{para. } x \ge 0 \\ \end{cases} \end{split}\]
x = np.linspace(-10, 10, 1000)

def f(x):
    
    Y = np.zeros(len(x))
    
    for index, x in enumerate(x):
        if x >= 0:
            Y[index] = 1
    return Y

plt.plot(x, f(x))
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
../_images/65afcebed98bfcb3a08b25bf457bd161b2081ae471e11961920d1f0e0b56b9c6.png
x = np.linspace(-3, 3, 7)

#if you want to understand the enumerate:

type(enumerate(x))

for index, x in enumerate(x):
    print("index is:", index)
    print("value is:", x)
index is: 0
value is: -3.0
index is: 1
value is: -2.0
index is: 2
value is: -1.0
index is: 3
value is: 0.0
index is: 4
value is: 1.0
index is: 5
value is: 2.0
index is: 6
value is: 3.0

Composite functions#

import numpy as np
import matplotlib.pyplot as plt

N = 1000

x = np.linspace(-10,10, num=N)

def g(x):
  return x**2

def f(x):
  return np.sin(x)

y = g(x)

#this is basically plotting sin(x^2)
f_o_g = f(g(x))

plt.plot(x,f_o_g)
[<matplotlib.lines.Line2D at 0x7f7f7b7b30a0>]
../_images/67a087b6e78d6e964b3f9ec3c5780c6ae1bf6d0c3de8f16affd0d87a3ae08a0e.png

How to manipulate functions#

Functions displacement#

Siendo \(c\) una constante mayor que cero, entonces la gráfica:

  • \(y=f(x)+c\) se desplaza \(c\) unidades hacia arriba.

  • \(y=f(x)-c\) se desplaza \(c\) unidades hacia abajo.

  • \(y=f(x-c)\) se desplaza \(c\) unidades hacia la derecha.

  • \(y=f(x+c)\) se desplaza \(c\) unidades hacia la izquierda.

N = 1000

def f(x):
  return x**2;

c = 4

x = np.linspace(-10,10, num=N)

y = f(x + c)     #note that this will displace y 4 units to the right

fig, ax = plt.subplots(nrows=1, ncols=2)

ax[0].plot(x, f(x))     #original cuadratic function
ax[0].grid()
ax[0].axhline(y=0, color='r')
ax[0].axvline(x=0, color='r')
ax[0].set_title("Original chart")

ax[1].plot(x,y)         #function with transformation
ax[1].grid()
ax[1].axhline(y=0, color='r')
ax[1].axvline(x=0, color='r')
ax[1].set_title("Displaced chart")
Text(0.5, 1.0, 'Displaced chart')
../_images/510f29d938509c60e4294d7e8dcb3d091670e9963a1512ed456f90d4dfe83d1d.png

Functions elongations & compressions#

Siendo \(c\) una constante mayor que cero, entonces la gráfica:

  • \(y=c \cdot f(x)\) alarga la gráfica verticalmente en un factor de \(c\).

  • \(y= \frac{1}{c} \cdot f(x)\) comprime la gráfica verticalmente en un factor de \(c\).

  • \(y=f(c \cdot x)\) comprime la gráfica horizontelmente en un factor de \(c\).

  • \(y= f(\frac{1}{c} \cdot x )\) alarga la gráfica horizontelmente en un factor de \(c\).

N = 1000

def f(x):
  return np.sin(x);

c = 2

x = np.linspace(-15,15, num=N)

y = f((1/c)*x)     #note that this will elonge the chart in a proportion of 2


fig, ax = plt.subplots(nrows=1, ncols=2)

ax[0].plot(x, f(x))     #original sinusoidal function
ax[0].grid()
ax[0].axhline(y=0, color='r')
ax[0].axvline(x=0, color='r')
ax[0].set_title("Original chart")

ax[1].plot(x,y)         #function with transformation (elonged horizontally)
ax[1].grid()
ax[1].axhline(y=0, color='r')
ax[1].axvline(x=0, color='r')
ax[1].set_title("Elonged chart")
Text(0.5, 1.0, 'Elonged chart')
../_images/7a4885b27f44a5a661840b83fad6d72388404d65c4d5492a30bfaea383d35cab.png

Function reflection#

  • \(y=-f(x)\) refleja la gráfica respecto al eje x.

  • \(y=f(-x)\) refleja la gráfica respecto al eje y.

N = 1000

def f(x):
  return x**3;

x = np.linspace(-10,10, num=N)

y = f(-x)      #this will reflect the function about the y axis

fig, ax = plt.subplots(nrows=1, ncols=2)

ax[0].plot(x, f(x))     #original cubic function
ax[0].grid()
ax[0].axhline(y=0, color='r')
ax[0].axvline(x=0, color='r')
ax[0].set_title("Original chart")

ax[1].plot(x,y)         #function with transformation (reflected about the y axis)
ax[1].grid()
ax[1].axhline(y=0, color='r')
ax[1].axvline(x=0, color='r')
ax[1].set_title("Reflected chart")
Text(0.5, 1.0, 'Reflected chart')
../_images/ed0bed84826361b115e81103fe9ea40e0afca4d8cec8705cc5f8bc2cf8b5cadd.png

Activation Functions#

import numpy as np
import matplotlib.pyplot as plt

N = 1000
x = np.linspace(-5,5, num=N)

Linear function#

\[y=mx+b\]
def f(x):
  return x

plt.plot(x, f(x))
plt.grid()
../_images/213f0337667697e759d8a6771ceade9f31bd41adc28a403a03be64e2eb5a09d3.png

heavyside function#

\[\begin{split}H(x) = \begin{cases} 0, &\quad \text{para, } x < 0 \\ 1, &\quad\text{para. } x \ge 0 \\ \end{cases} \end{split}\]
def H(x):
  Y = np.zeros(len(x))
  for idx,x in enumerate(x):
    if x>=0:
      Y[idx]=1
  return Y
    

N=1000


y = H(x)

plt.plot(x,y)
plt.grid()
../_images/09a9828ce90238be01f30f12c43ee5bee4f2273a02f6f42dea35b4432bddd5af.png

sigmoid function#

\[f(x)=\frac{1}{1-e^{-x}}\]
def f(x):
  return 1/(1 + np.exp(-x))
    

N=1000

y = f(x)

plt.plot(x,y)
plt.grid()
../_images/b2a44477fb358d15eaa56b96abf5b9825a0270544a98c5c9d520207b5c7e38d0.png

hyperbolic tangent function#

\[f(x)=\frac{2}{1+e^{-2x}}-1\]
def f(x):
  return np.tanh(x)
    

N=1000

y = f(x)

plt.plot(x,y)
plt.grid()
../_images/6578bf5e7fcc3c4a619de1235e148ab9c78902b59e3bc9317744947bfafd4886.png

ReLu function#

\[R(x)=max(0,x)\]
def f(x):
  return np.maximum(x,0)
    

N=1000

y = f(x)

plt.plot(x,y)
plt.grid()
../_images/4a378915b98026a2cb18e0daa8cbe29cd9f189be1405b820ece9ce407ee266b6.png
Created in deepnote.com Created in Deepnote