Estructuras principales de datos
Diferencias entre escalar, vector, matriz & tensor
Escalar
#un escalar (float)
escalar = 5.867
#otro escalar (logical)
escalar_python = True
#y otro escalar (string)
escalar_string = "hi"
Vector
import numpy as np
#vector (notese que solo hay 1 dimension)
vector = np.array(
[1, 2, 3, 4]
)
Funcion para graficar vectores
import numpy as np
import matplotlib.pyplot as plt
#se crea la funcion para graficar vectores
def graficarVectores(vecs, cols, alpha=1):
plt.figure()
#se dibuja eje Y
plt.axvline(x=0, color = "grey", zorder = 0)
#se dibuja eje X
plt.axhline(y=0, color = "grey", zorder = 0)
for i in range(len(vecs)):
x = np.concatenate([[0,0], vecs[i]])
plt.quiver(
[x[0]],
[x[1]],
[x[2]],
[x[3]],
angles="xy", scale_units="xy", scale=1,
color = cols[i],
alpha = alpha
)
#el vector(es) a graficar, debe pasarse como una lista
#el color(es) a emplear, debe pasarse como una lista de strings
Combinacion lineal
import numpy as np
import matplotlib.pyplot as plt
#vector 1
v1 = np.array([2,5])
#vector 2
v2 = np.array([3,2])
#combinacion lineal
v1v2 = 2*v1 + 3*v2
graficarVectores([v1, v2, v1v2], ["red", "orange", "yellow"])
plt.xlim(-1, 20)
plt.ylim(-1, 20)
Todas las posibles combinaciones lineales
for a in range(-10, 10):
for b in range(-10,10):
plt.scatter(v1[0]*a + v2[0]*b, v1[1]*a + v2[1]*b,
marker = ".",
color = "orange")
plt.xlim(-100,100)
plt.ylim(-100,100)
plt.axvline(x=0, color="grey")
plt.axhline(y=0, color="grey")
plt.show()
Matriz
import numpy as np
#matriz (notese que hay 2 dimensiones) Pueden ser n vectores, pero solo hay 2 dimensiones
matriz = np.array([
[1,2,3], #primer vector
[4,5,6], #segundo vector
[7,8,9] #tercer vector (pueden ser mas)
])
matriz
Graficando una matriz con matplotlib
import matplotlib.pyplot as plt
plt.imshow(matriz, interpolation="nearest")
plt.show()
Matriz identidad
import numpy as np
#Generar matriz identidad
identidad = np.eye(4) #matriz identidad 4x4
identidad
Inversa de una matriz
matrizz = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 10]])
#calculando inversa
matrizz_inv = np.linalg.inv(matrizz)
print("matriz:", matrizz)
print("matriz inversa:", matrizz_inv)
determinante de una matriz
matrizz = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
np.linalg.det(matrizz)
#determinante = 0
#esta matriz no tiene inversa, es una matriz singular
Tensor
import numpy as np
# Se crea el tensor
# (note que hay 3 dimensiones) Pueden ser n matrices (o n tensores), en este caso solo haremos 2 matrices
tensor = np.array([
[
[1,2,3], #matriz 1
[4,5,6],
[7,8,9]
],
[
[10,11,12], #matriz 2
[13,14,15],
[16,17,18]
],
[
[19,20,21], #matriz 3
[22,23,24],
[25,26,27]
]
])
#imprimir el tensor
tensor
Graficando un tensor con matplotlib
import matplotlib.pyplot as plt
plt.imshow(tensor, interpolation="nearest")
plt.show()
tensor2 = np.array([
[[0,0,0],[0,0,0],[0,0,0]], #0 representa el negro
[[128,128,128],[128,128,128],[128,128,128]], #128 lo que hay entre negro y blanco
[[255,255,255],[255,255,255],[255,255,255]], #255 representa el blanco
])
plt.imshow(tensor2, interpolation="nearest")
plt.show()
El mejor tensor que veras en tu vida
#matriz para dibujar los cuadros del fondo
baseMatrix = np.array([
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]]
])
#matriz para dibujar a mario
pixelart = np.array([
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[232,12,12],[221,11,10],[210,0,0],[199,1,0],[200,0,0],[189,5,5],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[221,11,10],[254,0,0],[245,0,10],[245,0,10],[234,0,9],[223,6,14],[223,6,14],[189,5,5],[200,0,2],[210,0,0],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[98,78,43],[106,82,46],[117,92,51],[197,177,144],[209,189,154],[204,184,149],[27,27,27],[197,177,144],[192,192,192],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[98,78,43],[213,194,162],[117,92,51],[213,194,162],[214,197,169],[218,199,167],[213,194,162],[47,47,47],[209,189,156],[204,184,149],[197,177,144],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[92,68,30],[218,199,167],[128,100,60],[214,197,169],[218,199,167],[218,199,167],[213,194,162],[208,189,156],[27,27,27],[208,189,156],[203,183,150],[197,177,144],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[78,57,26],[92,68,30],[197,177,144],[218,199,167],[213,194,162],[208,189,156],[208,189,156],[27,27,27],[47,47,47],[63,63,63],[27,27,27],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192],[204,184,149],[213,194,162],[209,189,154],[204,184,149],[197,177,144],[204,184,149],[204,184,149],[197,177,144],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[221,11,10],[210,0,1],[92,49,224],[200,0,0],[212,0,0],[221,11,10],[42,41,220],[192,192,192],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[232,12,12],[254,0,0],[245,0,10],[84,45,214],[245,0,10],[234,0,9],[83,46,201],[210,0,1],[221,11,10],[232,12,12],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[232,12,12],[254,0,0],[245,0,10],[234,0,9],[84,45,214],[92,49,224],[84,45,214],[77,41,189],[234,0,9],[245,0,10],[254,0,0],[221,11,10],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[197,177,144],[208,191,161],[245,0,10],[84,45,214],[247,223,61],[92,49,224],[83,46,201],[225,202,47],[67,35,172],[232,1,9],[208,191,161],[197,177,144],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[204,184,149],[214,197,169],[197,177,144],[84,45,214],[92,49,224],[84,45,214],[83,46,201],[77,41,189],[67,35,172],[197,177,144],[214,197,171],[204,184,149],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[209,189,154],[204,184,149],[84,45,214],[98,55,233],[92,49,224],[83,46,201],[77,41,189],[83,46,201],[77,41,189],[67,34,173],[204,184,149],[209,189,154],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[128,128,128],[192,192,192],[84,45,214],[84,45,214],[83,46,201],[192,192,192],[128,128,128],[67,35,172],[67,35,172],[67,35,172],[128,128,128],[192,192,192],[128,128,128],[192,192,192]],
[[192,192,192],[128,128,128],[192,192,192],[107,83,45],[117,92,51],[111,86,45],[91,67,29],[128,128,128],[192,192,192],[102,78,40],[111,86,45],[103,80,38],[84,61,27],[128,128,128],[192,192,192],[128,128,128]],
[[128,128,128],[192,192,192],[107,83,45],[102,78,40],[96,72,34],[91,67,29],[84,61,27],[192,192,192],[128,128,128],[96,72,34],[91,67,29],[84,61,27],[73,54,21],[65,48,18],[128,128,128],[192,192,192]]
])
plt.imshow(pixelart, interpolation='nearest')
plt.show()
Operaciones algebraicas
import numpy as np
vector = np.array(
[1, 2, 3, 4]
)
matriz = np.array([
[1,2,3],
[4,5,6],
[7,8,9]
])
tensor = np.array([
[
[1,2,3],
[4,5,6],
[7,8,9]
],
[
[10,11,12],
[13,14,15],
[16,17,18]
],
[
[19,20,21],
[22,23,24],
[25,26,27]
]
])
Transpuesta
Transpuesta en vector
print("vector original", vector)
print("vector transpuesto:", vector.T)
Transpuesta en Matriz
print("matriz original:")
print(matriz)
print("matriz transpuesta:")
print(matriz.T)
Transpuesta en Tensor
print("tensor original:")
print(tensor)
print("tensor transpuesto:")
print(tensor.T)
Producto punto
Funcion para producto punto en python
import numpy as np
A = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
B = np.array([[2,3],[5,7],[11,13]])
C = A.dot(B)
C
Sistemas de ecuaciones como matrices
Matriz inversa para resover sistema de ecuaciones
import numpy as np
# Se establece que cualquier valor muy cercano a cero, se haga cero. Esto para
# identificar mas facilmente la matriz identidad.
np.set_printoptions(suppress=True)
#matriz A
A = np.array([[3,1], [2,1]])
#matriz B
B = np.array([[1],[1]])
A_inv = np.linalg.inv(A)
#solucion: se multiplica la inversa de A por el vector B
x = A_inv.dot(B)
print(A.dot(x))
Verificar si un sistema de ecuaciones tiene solucion
import numpy as numpy
import matplotlib.pyplot as plt
# se crea un eje x
x = np.arange(-6, 6)
# primera ecuacion
y_1 = -1*x + 3
#segunda ecuacion
y_2 = 2*x + 5
#se grafican las rectas
plt.plot(x, y_1)
plt.plot(x, y_2)
# se limita el eje X y el eje Y para enfatizar solo una zona
plt.xlim(-8,8)
plt.ylim(-8,8)
# se dibuja el eje X y el eje Y
plt.axvline(x=0, color="grey")
plt.axhline(y=0, color="grey")
plt.show()
Sistemas de ecuaciones sin solucion
Sistemas sobredeterminados
import numpy as numpy
import matplotlib.pyplot as plt
# se crea un eje x
x = np.arange(-6, 6)
# primera ecuacion
y_1 = 3*x + 5
#segunda ecuacion
y_2 = -x + 3
#tercera ecuacion
y_3 = 2*x + 1
#se grafican las rectas
plt.plot(x, y_1)
plt.plot(x, y_2)
plt.plot(x, y_3)
# se limita el eje X y el eje Y para enfatizar solo una zona
plt.xlim(-8,8)
plt.ylim(-8,8)
# se dibuja el eje X y el eje Y
plt.axvline(x=0, color="grey")
plt.axhline(y=0, color="grey")
plt.show()
import numpy as np
import matplotlib.pyplot as plt
#se crea la funcion para graficar vectores
def graficarVectores(vecs, cols, alpha=1):
plt.figure()
#se dibuja eje Y
plt.axvline(x=0, color = "grey", zorder = 0)
#se dibuja eje X
plt.axhline(y=0, color = "grey", zorder = 0)
for i in range(len(vecs)):
x = np.concatenate([[0,0], vecs[i]])
plt.quiver(
[x[0]],
[x[1]],
[x[2]],
[x[3]],
angles="xy", scale_units="xy", scale=1,
color = cols[i],
alpha = alpha
)
#el vector(es) a graficar, debe pasarse como una lista
#el color(es) a emplear, debe pasarse como una lista de strings
Graficar sistemas de ecuaciones como vectores
import numpy as np
import matplotlib.pyplot as plt
#se crea la funcion para graficar vectores
def graficarVectores(vecs, cols, alpha=1):
plt.figure()
#se dibuja eje Y
plt.axvline(x=0, color = "grey", zorder = 0)
#se dibuja eje X
plt.axhline(y=0, color = "grey", zorder = 0)
for i in range(len(vecs)):
x = np.concatenate([[0,0], vecs[i]])
plt.quiver(
[x[0]],
[x[1]],
[x[2]],
[x[3]],
angles="xy", scale_units="xy", scale=1,
color = cols[i],
alpha = alpha
)
#el vector(es) a graficar, debe pasarse como una lista
#el color(es) a emplear, debe pasarse como una lista de strings
v1 = np.array([2,5])
v2 = np.array([3,2])
graficarVectores([v1, v2], ["red", "blue"])
#se ajustan los limites x & y para mejor visibilidad
plt.xlim(-1, 8)
plt.ylim(-1, 8)
Matrices como combinaciones lineales
import numpy as np
import matplotlib.pyplot as plt
#matriz A
A = np.array([[-1,3], [2,-2]])
print(A)
# vector [2,1]
vector = np.array([[2], [1]])
print(vector)
vector.flatten()
graficarVectores([vector.flatten()], cols = "blue")
plt.xlim(-0.5, 3)
plt.ylim(-0.5, 2)
vector_transformado = A.dot(vector)
print(vector_transformado)
graficarVectores([vector.flatten(), vector_transformado.flatten()], ["red", "blue"])
plt.xlim(-0.5, 3)
plt.ylim(-0.5, 2)
Autovectores y Autovalores
import numpy as np
import matplotlib.pyplot as plt
# matriz cuadrada X
X = np.array([[3,2], [4,1]])
print(X)
#vector original
v = np.array([[1], [1]])
# vector lambda*v
u = X.dot(v)
#se definen unos colores para el grafico
orange_light = "#FF9A13"
blue_light = "#1190FF"
#se grafican el vector original y el modificado
graficarVectores([u.flatten(), v.flatten()], cols=[orange_light, blue_light])
plt.xlim(-1, 6)
plt.ylim(-1, 6)
# vector original
s = np.array([[-1], [2]])
# vector transformado (producto punto de X con s)
t = X.dot(s)
graficarVectores([t.flatten(), s.flatten()], cols=[orange_light, blue_light])
plt.xlim(-3, 3)
plt.ylim(-3, 3)
Calcular autovalores y autovectores
import numpy as np
import matplotlib.pyplot as plt
X = np.array([[3,2], [4,1]])
# se calculan los eigen values
print(np.linalg.eig(X))
autovalores, autovectores = np.linalg.eig(X)
print(autovalores)
#primer autovector
print(autovectores[:, 0])
#segundo autovector
print(autovectores[:, 1])
#Notese que los autovectores cobran sentido en la columna
# vector original
v = np.array([[-1], [2]])
#autovector np.linalg.eig
Xv = autovectores[:,1]
# t es el autovector obtenido de multiplicar X*s en el ejercicio anterior
graficarVectores([v.flatten(), Xv.flatten(), t.flatten()], ["red", "blue", "yellow"])
plt.ylim(-4,2)
plt.xlim(-7,3)
Descomposicion de matrices
import numpy as np
A = np.array([[3,2], [4,1]])
autovalores, autovectores = np.linalg.eig(A)
A_recons = autovectores.dot(np.diag(autovalores)).dot(np.linalg.inv(autovectores))
A_recons
B = np.array([[3,2], [2,3]])
autovalores2, autovectores2 = np.linalg.eig(B)
B_recons = autovectores2.dot(np.diag(autovalores2)).dot(autovectores2.T)
B_recons
Descomposicion de matrices no cuadradas (SVD)
import numpy as np
C = np.array([[1,2,3], [3,4,5]])
# Descomposicion en valores singulares:
U, D, V = np.linalg.svd(C)
U
D
D_modified = np.array([[D[0],0,0],[0,D[1],0]])
D_modified
V
C_calc = U.dot(D_modified).dot(V)
C_calc
Creacion de funcion para graficar circulo unitario
import numpy as np
import matplotlib.pyplot as plt
#creacion de funcion que grafique el ciculo unitario
def graficarMatriz(matriz, vectorCol=["red", "blue"]):
#circulo unitario
x = np.linspace(-1, 1, 100000)
y = np.sqrt(1 - (x**2))
#circulo unitario transformado
x1 = matriz[0, 0]*x + matriz[0,1]*y
y1 = matriz[1, 0]*x + matriz[1,1]*y
x1_neg = matriz[0,0]*x - matriz[0,1]*y
y1_neg = matriz[1,0]*x - matriz[1,1]*y
#se usa la funcion graficar vectores para mostrar los vectores tambien
u1 = [matriz[0,0], matriz[1,0]]
v1 = [matriz[0,1], matriz[1,1]]
graficarVectores([u1, v1], cols=[vectorCol[0], vectorCol[1]])
plt.plot(x1, y1, "green", alpha = 0.7)
plt.plot(x1_neg, y1_neg, "green", alpha = 0.7)
print("Circulo unitario:")
graficarMatriz(np.eye(2))
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
plt.show()
# se define un vector A
A = np.array([[3, 7], [5, 2]])
print("Circulo unitario transformado:")
graficarMatriz(A)
plt.xlim(-8, 8)
plt.ylim(-8, 8)
plt.show()
Analizando transformaciones de matrices U-D-V en circulo unitario
print("Circulo unitario:")
graficarMatriz(np.array([[1, 0], [0, 1]]))
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
plt.show()
#Descomposicion
U, D, V = np.linalg.svd(A)
print("Primer Rotacion (V):")
graficarMatriz(V)
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
plt.show()
print("Escala (D):")
graficarMatriz(np.diag(D).dot(V))
plt.xlim(-9, 9)
plt.ylim(-9, 9)
plt.show()
print("Segunda Rotacion (U):")
graficarMatriz(U.dot(np.diag(D).dot(V)))
plt.xlim(-8, 8)
plt.ylim(-8, 8)
plt.show()
Efecto de autovalores(D) sobre los autovectores
A = np.array([[3, 7], [5,2]])
U, D, V = np.linalg.svd(A)
print(D)
print(U)
u1 = [D[0]*U[0,0], D[0]*U[0,1]]
v1 = [D[1]*U[1,0], D[1]*U[1,1]]
#La matriz original (A) vs la matriz transformada (A afectada por los autovalores)
print([A[0,0], A[1,0]])
print(u1)
print()
print([A[0,1], A[1,1]])
print(v1)
graficarMatriz(A)
graficarVectores([u1, v1], cols = ["red", "blue"])
plt.text(3, 5, r"$u_1$", size = 18)
plt.text(7, 2, r"$v_1$", size = 18)
plt.text(-5, -4, r"$D(u_1)$", size = 18)
plt.text(-4, 1, r"$D(v_1)$", size = 18)
plt.xlim(-8, 8)
plt.ylim(-8, 8)
plt.show()
Imágenes como matriz
Objeto de tipo PIL
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# Se importa la imagen
imagen = Image.open("imagen_ejemplo_frida_bredesen.jpg")
print(imagen)
Mostrar imagen de tipo PIL
plt.imshow(imagen)
plt.show()
Convertir a escala de grises
imagen_gr = imagen.convert("LA")
plt.imshow(imagen_gr)
plt.show()
Transformar a matriz
imagen_mat = np.array(list(imagen_gr.getdata(band=0)), float)
print(imagen_mat)
#veamos las dimensiones de la matriz
print(imagen_mat.shape)
Cambiar dimensiones de la matriz
imagen_mat.shape = (imagen_gr.size[1], imagen_gr.size[0])
print(imagen_mat.shape)
print(imagen_mat)
Modificar valores de matriz
# Todos los valores sobre 10
imagen_mat2 = imagen_mat/10
plt.imshow(imagen_mat2)
plt.show()
plt.imshow(imagen_mat2, cmap="gray")
plt.show()
Valores entre cero y uno a partir de matriz
imagen_mat3 = imagen_mat/(np.max(imagen_mat))
plt.imshow(imagen_mat3)
plt.show()
# Valor minimo
print(np.min(imagen_mat3))
# Valor maximo
print(np.max(imagen_mat3))
Descomposicion SVD de imagenes
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
#importar la imagen
imagen = Image.open("imagen_ejemplo_frida_bredesen.jpg")
#convertir a grises
imagen_gr = imagen.convert("LA")
#convertir a matriz
imagen_mat = np.array(list(imagen_gr.getdata(band=0)), float)
#dar dimensiones
imagen_mat.shape = (imagen_gr.size[1], imagen_gr.size[0])
Obteniendo vectores U,D,V
# descomposicion en valores singulares
U, D, V = np.linalg.svd(imagen_mat)
print(imagen_mat.shape)
print(U.shape)
print(D.shape)
print(V.shape)
Reconstruir la imagen usando vectores U,D,V
imagen_recons = np.matrix(U[:, :1])*np.diag(D[:1])*np.matrix(V[:1,:])
plt.imshow(imagen_recons, cmap="gray")
plt.show()
Usando 5 valores singulares
# Se construye nuevamente la imagen
# esta vez se hace con i valores singulares
i = 5
imagen_recons = np.matrix(U[:, :i])*np.diag(D[:i])*np.matrix(V[:i,:])
# se crea un titulo
titulo = "valores singulares = %s" %i
#ahora veamos la imagen
plt.imshow(imagen_recons, cmap="gray")
plt.title(titulo)
plt.show()
Usando 10 valores singulares
# Se construye nuevamente la imagen
# esta vez se hace con i valores singulares
i = 10
imagen_recons = np.matrix(U[:, :i])*np.diag(D[:i])*np.matrix(V[:i,:])
# se crea un titulo
titulo = "valores singulares = %s" %i
#ahora veamos la imagen
plt.imshow(imagen_recons, cmap="gray")
plt.title(titulo)
plt.show()
Usando 25 valores singulares
# Se construye nuevamente la imagen
# esta vez se hace con i valores singulares
i = 25
imagen_recons = np.matrix(U[:, :i])*np.diag(D[:i])*np.matrix(V[:i,:])
# se crea un titulo
titulo = "valores singulares = %s" %i
#ahora veamos la imagen
plt.imshow(imagen_recons, cmap="gray")
plt.title(titulo)
plt.show()
Usando 50 valores singulares
# Se construye nuevamente la imagen
# esta vez se hace con i valores singulares
i = 50
imagen_recons = np.matrix(U[:, :i])*np.diag(D[:i])*np.matrix(V[:i,:])
# se crea un titulo
titulo = "valores singulares = %s" %i
#ahora veamos la imagen
plt.imshow(imagen_recons, cmap="gray")
plt.title(titulo)
plt.show()
Pseudoinversa de Moore Penrose
Como se calcula la pseudoinversa de moore penrose?
import numpy as np
# Esta linea le dice a numpy que no imprima numeros muy cercanos a cero
np.set_printoptions(suppress=True)
A = np.array([[2,3], [5,7], [11,13]])
print(A)
U, D, V = np.linalg.svd(A)
print("U")
print(U)
print("D")
print(D)
print("V")
print(V)
Calculando D_pse
D_pse = np.zeros( ( A.shape[0],A.shape[1] ) ).T
D_pse
# Esta es la inversa de la matriz diagonal D
np.linalg.inv(np.diag(D))
# y aqui estamos reemplazando
D_pse[:D.shape[0], :D.shape[0]] = np.linalg.inv(np.diag(D))
# El resultado:
D_pse
Reconstruyendo A_pse
A_pse = V.T.dot(D_pse).dot(U.T)
A_pse
Comparando A_pse manual con A_pse de numpy
# Matriz pseudoinversa manual
print("A_pse calculada manualmente")
print(A_pse)
#Matriz pseudoinversa de numpy
print("A_pse calculada con numpy")
A_pse_numpy = np.linalg.pinv(A)
print(A_pse_numpy)
Usando Pseudoinversa para resolver sistema de ecuaciones sobredeterminado
Definiendo sistema de ecuaciones
import numpy as np
import matplotlib.pyplot as plt
# se define el eje x
x = np.linspace(-5, 5, 1000)
# se definen las tres rectas
y1 = -4*x + 3
y2 = 2*x + 5
y3 = -3*x + 1
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.xlim(-2, 2.5)
plt.ylim(-6, 6)
plt.show()
Convertir las rectas en matrices
A = np.array([[4, 1], [-2, 1], [3, 1]])
A
b = np.array([[3], [5], [1]])
b
Calculando la solucion
# Matriz pseudoinversa
A_pse = np.linalg.pinv(A)
# a x la llamaremos "resultado"
resultado = A_pse.dot(b)
#imprimir resultado
resultado
Interpretando la solucion graficamente
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.xlim(-2, 2.5)
plt.ylim(-6, 6)
plt.scatter(resultado[0], resultado[1])
plt.show()
PCA (Analisis de componentes principales)
import numpy as np
import matplotlib.pyplot as plt
# Se define valor semilla para obtener aleatorios igules en cada ejecucion
np.random.seed(42)
x = 3*np.random.rand(200)
y = 20*x + 2*np.random.randn(200) #Se agrega un error
# Se le da formato de columna a las dos variables
x = x.reshape(200,1)
y = y.reshape(200,1)
# Se unen los dos vectores como uno solo
xy = np.hstack([x, y])
plt.plot(xy[:,0], xy[:,1], ".")
plt.show()
xy_centrado = xy - np.mean(xy, axis = 0)
plt.plot(xy_centrado[:,0], xy_centrado[:,1], ".")
plt.show()
autovalores, autovectores = np.linalg.eig(xy_centrado.T.dot(xy_centrado))
print(autovectores)
# autovectores transpuestos porque los autovectores se interpretan a nivel de columna
graficarVectores(autovectores.T, ["blue", "red"])
# pongamos en el mismo grafico la nube de puntos
plt.plot(xy_centrado[:,0], xy_centrado[:,1], ".")
plt.show()
# autovectores transpuestos porque los autovectores se interpretan a nivel de columna
graficarVectores(autovectores.T, ["blue", "red"])
# pongamos en el mismo grafico la nube de puntos
plt.plot(xy_centrado[:,0], xy_centrado[:,1]/20, ".")
plt.show()
print(autovalores)
Calculando los componentes principales
xy_nuevo = autovectores.T.dot(xy_centrado.T)
# pongamos en el mismo grafico la nube de puntos
plt.plot(xy_nuevo[0, :], xy_nuevo[1, :], ".")
plt.show()