0% encontró este documento útil (0 votos)
103 vistas

02 Intro Python

Este documento presenta una introducción a la programación en Python. Explica que Python es un lenguaje de programación interpretado, dinámico y multiplataforma que soporta programación orientada a objetos e imperativa. También describe algunos motivos para aprender Python como su facilidad de aprendizaje, gran cantidad de librerías y excelente soporte científico. Finalmente, introduce conceptos básicos de Python como tipos de datos, sintaxis, funciones y estructuras de datos como listas y diccionarios.

Cargado por

DilandCastro
Derechos de autor
© © All Rights Reserved
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
103 vistas

02 Intro Python

Este documento presenta una introducción a la programación en Python. Explica que Python es un lenguaje de programación interpretado, dinámico y multiplataforma que soporta programación orientada a objetos e imperativa. También describe algunos motivos para aprender Python como su facilidad de aprendizaje, gran cantidad de librerías y excelente soporte científico. Finalmente, introduce conceptos básicos de Python como tipos de datos, sintaxis, funciones y estructuras de datos como listas y diccionarios.

Cargado por

DilandCastro
Derechos de autor
© © All Rights Reserved
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 72

Una introducción a la programación en python

Cecilia Jarne

[email protected]

Cecilia Jarne Fundamentos de Python [email protected] 1 / 67


Qué es Python?

Es un lenguaje de programación interpretado, que permite tipeado


dinámico y es multiplataforma.
Soporta orientación a objetos.
Programación imperativa.
Programación funcional.

Se pueden usar distintos paradigmas de programación.


Tiene una sintaxis clara.
Se puede extender su funcionalidad a través de distintas librerı́as.

https://www.python.org
Cecilia Jarne Fundamentos de Python [email protected] 2 / 67
Motivos para aprender Python

Fácil de aprender.
Un conjunto gigante de librerı́as.
Soporte cientı́fico excelente!!
Se puede desarrollar software bastante rápido.
Posee una licencia de código abierto.
Una comunidad gigante desarrollando con la cual realmente se puede
contar.

Cecilia Jarne Fundamentos de Python [email protected] 3 / 67


Un poquito de historia

Desarrollado desde 1989


Autor: Guido van Rossum (si lo queres seguir: @gvanrossum)

Cecilia Jarne Fundamentos de Python [email protected] 4 / 67


Sobre el diseño

Zen de Python, por Tim Peters

Bello es mejor que feo.


Explı́cito es mejor que implı́cito.
Simple es mejor que complejo.
Complejo es mejor que complicado.
Si la implementación es difı́cil de explicar, es una mala idea.
Tomado de: https://www.python.org/dev/peps/pep-0020/

Cecilia Jarne Fundamentos de Python [email protected] 5 / 67


Uso del intérprete
Sobre la instalación de python
(Las distribuciones de Linux generalmente incluyen python)
Para llamar al intérprete:
1 python
2

Para ver la versión que tienen instalada:


1 python -V o python --version
2

Posibilidad de probar porciones de código en el modo interactivo


antes de integrarlo como parte de un programa.
1 >>> 1 + 1
2 2
3 >>> a = range(10)
4 >>> print(a)
5 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Cecilia Jarne Fundamentos de Python [email protected] 6 / 67


Ideas básicas

En un lenguaje estático, el nombre de la variable está ligado a


• un tipo.
• un objeto.
En python puede tomar distintos valores en otro momento, incluso de
un tipo diferente al que tenı́a previamente.

1 x = 1
2 x = "text" # dynamic typing :)

Cecilia Jarne Fundamentos de Python [email protected] 7 / 67


Tipos de datos

Una lista de los tipos de datos más comunes:

https://docs.python.org/2/library/types.html

Cecilia Jarne Fundamentos de Python [email protected] 8 / 67


Tipos de datos

Una lista de los tipos de datos más comunes:

https://docs.python.org/2/library/types.html

Cecilia Jarne Fundamentos de Python [email protected] 9 / 67


Algunas ideas para entender que es mutable e inmutable

1 >> x = ’foo’ 1 >> def func(val):


2 >> y = x 2 >> val += [3, 2, 1]
3 >> print(x) 3
4 foo 4 >> x = [1, 2, 3]
5 >> y += ’bar’ 5 >> print(x)
6 >> print(x) 6 [1, 2, 3]
7 foo 7 >> func(x)
1 >> def func(val): 8 >> print(x)
2 >> val += ’bar’ 9 [1, 2, 3, 3, 2, 1]
3 >> x = ’foo’ 1 >> a="ejemplo"
4 >> print x 2 >> a="otro"
5 foo 3 >> a[2]="c"
6 >> func(x) 4 Traceback (most recent call last):
7 >> print(x) 5 File "<stdin>", line 1, in <module>
8 foo 6 TypeError: ’str’ object does not support item
1 >> x = [1, 2, 3] assignment
2 >> y = x
3 >> print (x)
4 [1, 2, 3]
5 >> y += [3, 2, 1]
6 >> print (x)
7 [1, 2, 3, 3, 2, 1]

Cecilia Jarne Fundamentos de Python [email protected] 10 / 67


Sintaxis de Python

En C o C++: se usa ; al final de 1 if(a>b)


cada linea 2 foo();
3 bar();
4 baz();

En python: El nivel de indentación es significativo! Aca la ultima linea se


ejecuta fuera del condicional.

1 if(a>b):
2 foo()
3 bar()
4 baz()

Cecilia Jarne Fundamentos de Python [email protected] 11 / 67


Sintaxis de Python

Cecilia Jarne Fundamentos de Python [email protected] 12 / 67


Sintaxis de Python

Cómo definir una función:

1 def function(x,y,z):
2 x=3*y
3 return x+y-z

Algunas funciones en Python que devuelven valores:

1 >> longitud = len(’La casa de la pradera’)


2 >> print (longitud)
3 21

Cecilia Jarne Fundamentos de Python [email protected] 13 / 67


Sintaxis de Python ejemplo
En C la indentation es opcional:

1 int factorial(int x)
2 {
3 if (x == 0)
4 return 1;
5 else
6 return x * factorial(x - 1);
7 }

En python es obligatoria:

1 def factorial(x):
2 if x == 0:
3 return 1
4 else:
5 return x * factorial(x - 1)

Cecilia Jarne Fundamentos de Python [email protected] 14 / 67


Recursividad en Python

Un ejemplo simple:

1
2 def jugar(intento=1):
3 respuesta = raw_input("De que color es una naranja? ")
4 if respuesta != "naranja":
5 if intento < 3:
6 print "\nFallaste Intentalo de nuevo"
7 intento += 1
8 jugar(intento) # Llamada recursiva
9 else:
10 print "\nPerdiste"
11 else:
12 print "\nGanaste!"
13 jugar()

Cecilia Jarne Fundamentos de Python [email protected] 15 / 67


Operadores en Python

Matemáticos:
Name Function symbol
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and returns remainder b% a = 0
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20

Booleanos:
Operation Result
x or y if x is false, then y, else x
x and y if x is false, then x, else y
not x if x is false, then True, else False

Cecilia Jarne Fundamentos de Python [email protected] 16 / 67


Strings

Se puede usar ’ o “ para la definición de los string

1 a= "Soy Cecilia"
2 b= ’Soy de Argentina’

Para imprimir en la pantalla:

print (’---All rigth!!!----’)

Cecilia Jarne Fundamentos de Python [email protected] 17 / 67


Strings: ejemplos

Un ejemplo:

’Yo comi %d %s hoy’ %(12,’manzanas’)

Otro ejemplo: I ate today.format(12,’apples’)

Cecilia Jarne Fundamentos de Python [email protected] 18 / 67


structures
List

1 a=[1,’apple’,1.2]

Tuple

1 a=(1,’apple’,1.2)

Dict

1 a={’name’:’Giovanni’, ’age’:42}

Set

1 a={1,’apple’,1.2}

Cecilia Jarne Fundamentos de Python [email protected] 19 / 67


Listas

Son estructuras de python super útiles


Se pueden acceder usando un ı́ndice y se puede hacer slicing

1 a[0] a[1] a[2:5] a[2:10:2]

Para obtener el ultimo elemento de la lista:

1 a[-1]

Se pueden definir por comprensión

1 [x**2 for x in range(1,11)]

Cecilia Jarne Fundamentos de Python [email protected] 20 / 67


Métodos útiles asociados a las listas

list.append(obj)
Appends object obj to list

list.count(obj)
Returns count of how many times obj occurs in list

list.extend(seq)
Appends the contents of seq to list

list.index(obj)
Returns the lowest index in list that obj appears

list.insert(index, obj)

Inserts object obj into list at offset index

Cecilia Jarne Fundamentos de Python [email protected] 21 / 67


Métodos útiles asociados a las listas

list.pop(obj=list[-1])
Removes and returns last object or obj from list

list.remove(obj)
Removes object obj from list

list.reverse()

Reverses objects of list in place

Cecilia Jarne Fundamentos de Python [email protected] 22 / 67


Mis Motivos (y los de muchos) para usar Python

Estas librerı́as:

NumPy:
http://www.numpy.org/
SciPy:
http://www.scipy.org/
MatPlotLib:
http://matplotlib.org/

Son todas open source!

Cecilia Jarne Fundamentos de Python [email protected] 23 / 67


Mis Motivos (y los de muchos) para usar Python

NumPy provee funcionalidad para crear, borrar, manejar y operar en


grandes arrays de datos crudos (como los de Fortran and C/C++
arrays).
SciPy extiende NumPy con una colección de algoritmos útiles como
minimimización, transformada de Fourier, regresión y otras
herramientas.
Ambos paquetes son add-on packages (no son parte de python en si.
Continen código en Python y compilado con (fftpack, BLAS).
MatPlotLib es una librerı́a para hacer gráficos.

Cecilia Jarne Fundamentos de Python [email protected] 24 / 67


Numpy

NumPy es un paquete fundamental para python de programación


cientı́fica. Entre otras cosas contiene:

Potentes arrays N-dimensionales.


Funciones sofisticadas.
Herramientas para integración con código C/C++ y Fortran.
Herramientas útiles de alegra lineal, transformada de fourier, y
generadores de números aleatorios.

Cecilia Jarne Fundamentos de Python [email protected] 25 / 67


Scipy

Es un paquete que extiende la funcionalidad de Numpy con una


colección substancial de algoritmos por ejemplo de minimización, cálculo y
procesamiento de señales.
Es user-friendly
Tiene rutinas eficientes de integration and optimization. Permiten
trabajar con:

• Clustering.
• Fourier transforms.
• numerical integration, interpolations.
• data I/O, LAPACK.
• sparse matrices, linear solvers, optimization.
• signal processing.
• statistical functions.
Cecilia Jarne Fundamentos de Python [email protected] 26 / 67
Matplotlib

Es una librerı́a de python para gráficos 2D (y 3D también un poquito) que


produce imágenes de alta calidad en una gran diversidad de formatos y
entornos o plataformas interactivas.

Python scripts.
The Python y tambien IPython shell.
The jupyter notebook.
Web application servers.
Graphical user interface toolkits.

Cecilia Jarne Fundamentos de Python [email protected] 27 / 67


Como usarlas?
Es necesario importar las librerias:

1 import numpy
2 import scipy
3 import matplotlib.pyplot

Se puede hacer de distintas maneras:

1 import numpy
2 import numpy as np
3 from numpy import *

Yo uso:

1 import numpy as np
2 import scipy as sp
3 import matplotlib.pyplot as pp (o tambien) plt

Cecilia Jarne Fundamentos de Python [email protected] 28 / 67


Cosas sobre Numpy

Funcionalidad de NumPy :

Funciones polinómicas.
Cómputo estadı́stico.
Generadores de números aleatoreos.
Transformada de Fourier discreta.
Cambio de tamaño, forma, testeo y cálculo con arrays.

Cecilia Jarne Fundamentos de Python [email protected] 29 / 67


Algo fundamental de Numpy: np.array

Hay 5 mecanismos generales para crear arrays:

Conversión desde otras estructuras de Python (e.g., lists, tuples).


Directamente como Numpy array (e.g., arange, ones, zeros, etc.).
Leer los arrays del disco.
Crearlos a partir de strings o datos en buffers.
Usar las librerı́as especiales (e.g., random).

Cecilia Jarne Fundamentos de Python [email protected] 30 / 67


Numpy: ejemplos
(>>> significa input)

1 import numpy as np
2 >>> x = np.array([2, 3, 1, 0])
3 >>> print(x)
4 [2 3 1 0]
5
6 >>> np.arange(10)
7 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
8
9 >>> np.arange(2, 10, dtype=np.float)
10 array([ 2., 3., 4., 5., 6., 7., 8., 9.])
11
12 >>> np.arange(2, 3, 0.1)
13 array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
14
15 >>> np.linspace(1., 4., 6)
16 array([ 1. , 1.6, 2.2, 2.8, 3.4, 4. ])

Cecilia Jarne Fundamentos de Python [email protected] 31 / 67


Cambiando la forma del array

1 >>> a = np.zeros((5, 2))


2 >>> print(a)
3 [[ 0. 0.]
4 [ 0. 0.]
5 [ 0. 0.]
6 [ 0. 0.]
7 [ 0. 0.]]

reshape:

1 >>> b = a.reshape((2, 5))


2 >>> print(b)
3 [[ 0. 0. 0. 0. 0.]
4 [ 0. 0. 0. 0. 0.]]

Cecilia Jarne Fundamentos de Python [email protected] 32 / 67


Trasponer y llenar:

Algunas rutinas de ejemplo:

1 >>> x = np.array([1.,2.,3.,4.])
2 >>> x
3 array([ 1., 2., 3., 4.])
4 >>> x.T
5 array([ 1., 2., 3., 4.])

1 >>> a = np.array([1, 2])


2 >>> a.fill(0)
3 >>> a
4 array([0, 0])
5 >>> a = np.empty(2)
6 >>> a.fill(1)
7 >>> a
8 array([ 1., 1.])

Cecilia Jarne Fundamentos de Python [email protected] 33 / 67


Operaciones elementales con Numpy:

1 x = np.array([[1,2],[3,4]], dtype=np.float64)
2 y = np.array([[5,6],[7,8]], dtype=np.float64)
3
4 # Elementwise sum; both produce the array
5
6 >>>print(x + y)
7 >>>print(np.add(x, y))
8 [[ 6.0 8.0]
9 [10.0 12.0]]
10
11 # Elementwise difference; both produce the array
12
13 >>>print(x - y)
14 >>>print(np.subtract(x, y))
15 [[-4.0 -4.0]
16 [-4.0 -4.0]]

Cecilia Jarne Fundamentos de Python [email protected] 34 / 67


Operaciones elementales con Numpy:

1 # Elementwise product; both produce the array


2 >>>print(x * y)
3 >>>print(np.multiply(x, y))
4 [[ 5.0 12.0]
5 [21.0 32.0]]
6
7 # Elementwise division; both produce the array
8 >>>print(x / y)
9 >>>print(np.divide(x, y))
10 [[ 0.2 0.33333333]
11 [ 0.42857143 0.5 ]]
12
13 # Elementwise square root; produces the array
14 >>>print(np.sqrt(x))
15 [[ 1. 1.41421356]
16 [ 1.73205081 2. ]]

Cecilia Jarne Fundamentos de Python [email protected] 35 / 67


Más operaciones con arrays
1 x = np.array([[1,2],[3,4]])
2 y = np.array([[5,6],[7,8]])
3
4 v = np.array([9,10])
5 w = np.array([11, 12])
6
7 # Inner product of vectors; both produce 219
8 print(v.dot(w))
9 print(np.dot(v, w))
10
11 # Matrix / vector product; both produce the rank 1 array [29 67]
12 print(x.dot(v))
13 print(np.dot(x, v))
14
15 # Matrix / matrix product; both produce the rank 2 array
16
17 print(x.dot(y))
18 print(np.dot(x, y))

Cecilia Jarne Fundamentos de Python [email protected] 36 / 67


Sobre creación de vectores

1 a = np.zeros((2,2)) # Create an array of all zeros


2 print(a) # Prints "[[ 0. 0.]
3 # [ 0. 0.]]"
4 b = np.ones((1,2)) # Create an array of all ones
5 print(b) # Prints "[[ 1. 1.]]"
6 c = np.full((2,2), 7) # Create a constant array
7 print(c) # Prints "[[ 7. 7.]
8 # [ 7. 7.]]"
9 d = np.eye(2) # Create a 2x2 identity matrix
10 print(d) # Prints "[[ 1. 0.]
11 # [ 0. 1.]]"
12 e = np.random.random((2,2)) # Create an array filled with random values
13 print(e) # Might print "[[ 0.91940167 0.08143941]
14 # [ 0.68744134 0.87236687]]"

Cecilia Jarne Fundamentos de Python [email protected] 37 / 67


Numpy Chart:

Cecilia Jarne Fundamentos de Python [email protected] 38 / 67


Scipy Basics:

Cecilia Jarne Fundamentos de Python [email protected] 39 / 67


Matplotlib basics and How do we prepare data in general?

Cecilia Jarne Fundamentos de Python [email protected] 40 / 67


Como crear un dataset y salvarlo en un .txt

1 from math import *


2 import numpy as np
3 import matplotlib.pyplot as pp
4 #File creation
5 f_out_max = open(’tabla.txt’, ’w’)
6 #data generation
7 x = np.arange(441)
8 Sin1 = 1*np.sin(2*pi*(25/441.0)*x)
9 Sin2 = 0.25*np.sin(2*pi*((25./2)/441.0)*x)
10 Sin = Sin1+Sin2
11 Vec = np.c_[x, Sin]
12 #printing
13 print (’Vec: ’, Vec.shape)
14 #save in .txt file
15 np.savetxt(f_out_max, Vec, fmt=’ %f’, delimiter=’\t’, header="x #f(x)")
16 f_out_max.close()
17 #plot figure
18 pp.figure()
19 pp.plot(x*1./44100., Sin, color=’r’, label=’Sin vs x’)
20 pp.xlabel(’Time (s)’)
21 pp.savefig("fig_01.jpg",dpi=200)

Cecilia Jarne Fundamentos de Python [email protected] 41 / 67


Como crear un dataset y salvarlo en un .txt

1 from math import *


2 import numpy as np
3 import matplotlib.pyplot as pp
4 #File creation
5 f_out_max = open(’tabla.txt’, ’w’)
6 #data generation
7 x = np.arange(441)
8 Sin1 = 1*np.sin(2*pi*(25/441.0)*x)
9 Sin2 = 0.25*np.sin(2*pi*((25./2)/441.0)*x)
10 Sin = Sin1+Sin2
11 Vec = np.c_[x, Sin]
12 #printing
13 print (’Vec: ’, Vec.shape)
14 #save in .txt file
15 np.savetxt(f_out_max, Vec, fmt=’ %f’, delimiter=’\t’, header="x #f(x)")
16 f_out_max.close()
17 #plot figure
18 pp.figure()
19 pp.plot(x*1./44100., Sin, color=’r’, label=’Sin vs x’)
20 pp.xlabel(’Time (s)’)
21 pp.savefig("fig_01.jpg",dpi=200)

Cecilia Jarne Fundamentos de Python [email protected] 41 / 67


Como crear un dataset y salvarlo en un .txt

1 from math import *


2 import numpy as np
3 import matplotlib.pyplot as pp
4 #File creation
5 f_out_max = open(’tabla.txt’, ’w’)
6 #data generation
7 x = np.arange(441)
8 Sin1 = 1*np.sin(2*pi*(25/441.0)*x)
9 Sin2 = 0.25*np.sin(2*pi*((25./2)/441.0)*x)
10 Sin = Sin1+Sin2
11 Vec = np.c_[x, Sin]
12 #printing
13 print (’Vec: ’, Vec.shape)
14 #save in .txt file
15 np.savetxt(f_out_max, Vec, fmt=’ %f’, delimiter=’\t’, header="x #f(x)")
16 f_out_max.close()
17 #plot figure
18 pp.figure()
19 pp.plot(x*1./44100., Sin, color=’r’, label=’Sin vs x’)
20 pp.xlabel(’Time (s)’)
21 pp.savefig("fig_01.jpg",dpi=200)

Cecilia Jarne Fundamentos de Python [email protected] 41 / 67


Como crear un dataset y salvarlo en un .txt

1 from math import *


2 import numpy as np
3 import matplotlib.pyplot as pp
4 #File creation
5 f_out_max = open(’tabla.txt’, ’w’)
6 #data generation
7 x = np.arange(441)
8 Sin1 = 1*np.sin(2*pi*(25/441.0)*x)
9 Sin2 = 0.25*np.sin(2*pi*((25./2)/441.0)*x)
10 Sin = Sin1+Sin2
11 Vec = np.c_[x, Sin]
12 #printing
13 print (’Vec: ’, Vec.shape)
14 #save in .txt file
15 np.savetxt(f_out_max, Vec, fmt=’ %f’, delimiter=’\t’, header="x #f(x)")
16 f_out_max.close()
17 #plot figure
18 pp.figure()
19 pp.plot(x*1./44100., Sin, color=’r’, label=’Sin vs x’)
20 pp.xlabel(’Time (s)’)
21 pp.savefig("fig_01.jpg",dpi=200)

Cecilia Jarne Fundamentos de Python [email protected] 41 / 67


Obtenemos:

Una tabla en txt y una figura:


#x #f(x)
0.000000 0.000000
1.000000 0.392994
2.000000 0.740813
3.000000 1.003819
4.000000 1.152764
5.000000 1.172342
6.000000 1.062998
7.000000 0.840786
8.000000 0.535279
9.000000 0.185801
10.000000 -0.163538
11.000000 -0.469389
12.000000 -0.694586
13.000000 -0.812779
14.000000 -0.811673
15.000000 -0.694499
16.000000 -0.479506
17.000000 -0.197559
18.000000 0.111860 ...

Cecilia Jarne Fundamentos de Python [email protected] 42 / 67


Como abrir .txt or cvs

Un modo super facil es usar Numpy:

1 import numpy as np
2
3 file_name_you_want = np.loadtxt(fname,delimiter=" ")
4
5 print "First column element: ",file_name_you_want[0]
6 #to get the full column:
7
8 Transpose_your_file = file_name_you_want.T
9
10 print "First column: ", Transpose_your_file[0]

Cecilia Jarne Fundamentos de Python [email protected] 43 / 67


Como hacer un ajuste y graficarlo:

1 import numpy as np
2 import matplotlib.pyplot as pp
3 from scipy.optimize import curve_fit
4
5 def fitFunc(t, a, b, c):
6 return a*np.exp(-b*t) + c
7
8 t = np.linspace(0,4,50)
9 temp = fitFunc(t, 2.5, 1.3, 0.5)
10 noisy = temp + 0.25*np.random.normal(size=len(temp))
11 fitParams, fitCovariances = curve_fit(fitFunc, t, noisy)
12
13 pp.figure(figsize=(12, 6))
14 pp.ylabel(’Temperature (C)’, fontsize = 16)
15 pp.xlabel(’time (s)’, fontsize = 16)
16 pp.xlim(0,4.1)
17 pp.errorbar(t, noisy, fmt = ’ro’, yerr = 0.2)
18 sigma = [fitCovariances[0,0], fitCovariances[1,1], fitCovariances[2,2] ]
19 pp.plot(t, fitFunc(t, fitParams[0], fitParams[1], fitParams[2]))
20 pp.plot(t, fitFunc(t, fitParams[0] + sigma[0], fitParams[1] - sigma[1], fitParams[2] + sigma[2]))
21 pp.plot(t, fitFunc(t, fitParams[0] - sigma[0], fitParams[1] + sigma[1], fitParams[2] - sigma[2]))
22 pp.savefig(’dataFitted.pdf’, bbox_inches=0, dpi=600)
23 pp.show()

Cecilia Jarne Fundamentos de Python [email protected] 44 / 67


Como hacer un ajuste y graficarlo:

1 import numpy as np
2 import matplotlib.pyplot as pp
3 from scipy.optimize import curve_fit
4
5 def fitFunc(t, a, b, c):
6 return a*np.exp(-b*t) + c
7
8 t = np.linspace(0,4,50)
9 temp = fitFunc(t, 2.5, 1.3, 0.5)
10 noisy = temp + 0.25*np.random.normal(size=len(temp))
11 fitParams, fitCovariances = curve_fit(fitFunc, t, noisy)
12
13 pp.figure(figsize=(12, 6))
14 pp.ylabel(’Temperature (C)’, fontsize = 16)
15 pp.xlabel(’time (s)’, fontsize = 16)
16 pp.xlim(0,4.1)
17 pp.errorbar(t, noisy, fmt = ’ro’, yerr = 0.2)
18 sigma = [fitCovariances[0,0], fitCovariances[1,1], fitCovariances[2,2] ]
19 pp.plot(t, fitFunc(t, fitParams[0], fitParams[1], fitParams[2]))
20 pp.plot(t, fitFunc(t, fitParams[0] + sigma[0], fitParams[1] - sigma[1], fitParams[2] + sigma[2]))
21 pp.plot(t, fitFunc(t, fitParams[0] - sigma[0], fitParams[1] + sigma[1], fitParams[2] - sigma[2]))
22 pp.savefig(’dataFitted.pdf’, bbox_inches=0, dpi=600)
23 pp.show()

Cecilia Jarne Fundamentos de Python [email protected] 44 / 67


Como hacer un ajuste y graficarlo:

1 import numpy as np
2 import matplotlib.pyplot as pp
3 from scipy.optimize import curve_fit
4
5 def fitFunc(t, a, b, c):
6 return a*np.exp(-b*t) + c
7
8 t = np.linspace(0,4,50)
9 temp = fitFunc(t, 2.5, 1.3, 0.5)
10 noisy = temp + 0.25*np.random.normal(size=len(temp))
11 fitParams, fitCovariances = curve_fit(fitFunc, t, noisy)
12
13 pp.figure(figsize=(12, 6))
14 pp.ylabel(’Temperature (C)’, fontsize = 16)
15 pp.xlabel(’time (s)’, fontsize = 16)
16 pp.xlim(0,4.1)
17 pp.errorbar(t, noisy, fmt = ’ro’, yerr = 0.2)
18 sigma = [fitCovariances[0,0], fitCovariances[1,1], fitCovariances[2,2] ]
19 pp.plot(t, fitFunc(t, fitParams[0], fitParams[1], fitParams[2]))
20 pp.plot(t, fitFunc(t, fitParams[0] + sigma[0], fitParams[1] - sigma[1], fitParams[2] + sigma[2]))
21 pp.plot(t, fitFunc(t, fitParams[0] - sigma[0], fitParams[1] + sigma[1], fitParams[2] - sigma[2]))
22 pp.savefig(’dataFitted.pdf’, bbox_inches=0, dpi=600)
23 pp.show()

Cecilia Jarne Fundamentos de Python [email protected] 44 / 67


Como hacer un ajuste y graficarlo:

1 import numpy as np
2 import matplotlib.pyplot as pp
3 from scipy.optimize import curve_fit
4
5 def fitFunc(t, a, b, c):
6 return a*np.exp(-b*t) + c
7
8 t = np.linspace(0,4,50)
9 temp = fitFunc(t, 2.5, 1.3, 0.5)
10 noisy = temp + 0.25*np.random.normal(size=len(temp))
11 fitParams, fitCovariances = curve_fit(fitFunc, t, noisy)
12
13 pp.figure(figsize=(12, 6))
14 pp.ylabel(’Temperature (C)’, fontsize = 16)
15 pp.xlabel(’time (s)’, fontsize = 16)
16 pp.xlim(0,4.1)
17 pp.errorbar(t, noisy, fmt = ’ro’, yerr = 0.2)
18 sigma = [fitCovariances[0,0], fitCovariances[1,1], fitCovariances[2,2] ]
19 pp.plot(t, fitFunc(t, fitParams[0], fitParams[1], fitParams[2]))
20 pp.plot(t, fitFunc(t, fitParams[0] + sigma[0], fitParams[1] - sigma[1], fitParams[2] + sigma[2]))
21 pp.plot(t, fitFunc(t, fitParams[0] - sigma[0], fitParams[1] + sigma[1], fitParams[2] - sigma[2]))
22 pp.savefig(’dataFitted.pdf’, bbox_inches=0, dpi=600)
23 pp.show()

Cecilia Jarne Fundamentos de Python [email protected] 44 / 67


Como hacer el ajuste
We obtain the fit parameters:
1 [ 2.595658 1.74438726 0.69809511]

The covariance matrix:


1 [[ 0.02506636 0.01490486 -0.00068609]
2 [ 0.01490486 0.04178044 0.00641246]
3 [-0.00068609 0.00641246 0.00257799]]

Cecilia Jarne Fundamentos de Python [email protected] 45 / 67


Otros tipos de gráficos

1 import networkx as nx
2 import pygraphviz
3 from graphviz import *

1 import matplotlib.pyplot as pp
2 pp.hist([vector,bins=bins)

Cecilia Jarne Fundamentos de Python [email protected] 46 / 67


Aplicando Transformada de fourier y un sonograma

1 import matplotlib.pyplot as pp
2 pp.specgram(signal, NFFT=nfft, Fs= sample_rate, noverlap=par, cmap=’jet’
)

Cecilia Jarne Fundamentos de Python [email protected] 47 / 67


Ejemplo de integración numérica
1 from scipy.integrate import odeint
2 dy/dt = func(y, t0, ...)
3 sol = odeint(func, X0, t)

Cecilia Jarne Fundamentos de Python [email protected] 48 / 67


Se pueden hacer gráficos 3d y también videos

El ejemplo anterior estudiando una Curva paramétrica:


variable extra:

Cecilia Jarne Fundamentos de Python [email protected] 49 / 67


What else do we need todo with data?

Cecilia Jarne Fundamentos de Python [email protected] 50 / 67


What can we do with data?

We are interested in:


Data Visualization.
Data Analysis (Identify features from the data).
Data Classification.
Implementation of different algorithms as intelligent as we can get.

Cecilia Jarne Fundamentos de Python [email protected] 51 / 67


Which are the available algorithms?

Cecilia Jarne Fundamentos de Python [email protected] 52 / 67


What about machine learning?

Cecilia Jarne Fundamentos de Python [email protected] 53 / 67


What we have?

Cecilia Jarne Fundamentos de Python [email protected] 54 / 67


We can use Scikit learn

Cecilia Jarne Fundamentos de Python [email protected] 55 / 67


Scikit-learn Basics:

Cecilia Jarne Fundamentos de Python [email protected] 56 / 67


Scikit-learn Basics:

Hands on in the afternoon to learn some basic use of a set of functions!

Cecilia Jarne Fundamentos de Python [email protected] 57 / 67


Neural Networks:

Cecilia Jarne Fundamentos de Python [email protected] 58 / 67


Neural Networks:

Cecilia Jarne Fundamentos de Python [email protected] 59 / 67


How do we implement this algorithms?

From zero with math libraries and python.


Using dedicated open source frameworks:
• Tensorflow.
• Keras.

Cecilia Jarne Fundamentos de Python [email protected] 60 / 67


Keras Basics:

Keras: A high-level neural networks API, written in Python and capable of


running on top of TensorFlow, CNTK, or Theano. It was developed with a
focus on enabling fast experimentation. Being able to go from idea to
result with the least possible delay is key to doing good research.

Cecilia Jarne Fundamentos de Python [email protected] 61 / 67


Keras Basics:

Cecilia Jarne Fundamentos de Python [email protected] 62 / 67


Conclusiones

Les dejamos una colección infinitamente grande de herramientas y


recursos recombinables y reutilizables para poner en práctica.
El salto es mas pequeño de lo que parece.
Posibilidades de reutilizar y adaptar código a nuestras necesidades
para crear soluciones prácticas.
Una guia de estilo en:
https://google.github.io/styleguide/pyguide.html
ejemplos de Matplotlib: http://matplotlib.org/gallery.html

Cecilia Jarne Fundamentos de Python [email protected] 63 / 67


Más librerı́as para análisis de datos:

Scikit learn:
http://scikit-learn.org
Pandas
http://pandas.pydata.org/

Cecilia Jarne Fundamentos de Python [email protected] 64 / 67


Otras librerı́as para análisis de datos:

Cecilia Jarne Fundamentos de Python [email protected] 65 / 67


Algo más

Invitación: http://www.python.org.ar/wiki/PyCamp/2018

Cecilia Jarne Fundamentos de Python [email protected] 66 / 67

También podría gustarte