PDF de programación - NumPy + SciPy

Imágen de pdf NumPy + SciPy

NumPy + SciPygráfica de visualizaciones

Publicado el 8 de Mayo del 2017
1.939 visualizaciones desde el 8 de Mayo del 2017
785,9 KB
34 paginas
Creado hace 14a (08/09/2009)
NumPy

.

.

.

.NumPy / SciPy

. .2 / 34

¿Qué es NumPy?

1 Es una biblioteca de Python para trabajar con arreglos

multidimensionales.

1 El principal tipo de dato es el arreglo o array

1 También nos permite trabajar con la semántica de matrices

1 Nos ofrece muchas funciones útiles para el procesamiento de números

.

.

.

.NumPy / SciPy

. .3 / 34

Disclaimer

1 Pueden ver toda la info de esta presentación en

http://www.scipy.org/Tentative_NumPy_Tutorial

1 Los ejemplos suponen que primero se hizo en el intérprete:

>>> from numpy import *

.

.

.

.NumPy / SciPy

. .4 / 34

El Array

1 Es una tabla de elementos
1 normalmente números
1 todos del mismo tipo
1 indexados por enteros

1 Ejemplo de arreglos multidimensionales

1 Vectores
1 Matrices
1 Imágenes
1 Planillas

1 ¿Multidimensionales?

1 Que tiene muchas dimensiones o ejes
1 Un poco ambiguo, mejor usar ejes
1 Rango: cantidad de ejes

.

.

.

.NumPy / SciPy

. .5 / 34

Propiedades del Array

1 Como tipo de dato se llama ndarray

1 ndarray.ndim: cantidad de ejes

1 ndarray.shape: una tupla indicando el tamaño del array en cada eje

1 ndarray.size: la cantidad de elementos en el array

1 ndarray.dtype: el tipo de elemento que el array contiene

1 ndarray.itemsize: el tamaño de cada elemento en el array

.

.

.

.NumPy / SciPy

. .6 / 34

Propiedades del Array

>>> a = arange(10).reshape(2,5)
>>> a
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])

>>> a.shape
(2, 5)
>>> a.ndim
2
>>> a.size
10
>>> a.dtype
dtype('int32')
>>> a.itemsize
4

.

.

.

.NumPy / SciPy

. .7 / 34

Creando Arrays

1 Tomando un iterable como origen

>>> array( [2,3,4] )
array([2, 3, 4])
>>> array( [ (1.5,2,3), (4,5,6) ] )
array([[ 1.5,
[ 4. ,

3. ],
6. ]])

2. ,
5. ,

.

.

.

.NumPy / SciPy

. .8 / 34

Creando Arrays

1 Con funciones específicas en función del contenido

>>> arange(5)
array([0, 1, 2, 3, 4])
>>> zeros((2, 3))
array([[ 0.,
0.,
0.,
[ 0.,

0.],
0.]])

>>> ones((3, 2), dtype=int)
array([[1, 1],
[1, 1],
[1, 1]])

>>> empty((2, 2))
array([[
[

9.43647120e -268,
1.08290285e -312,

>>> linspace(-pi, pi, 5)
array([-3.141592 , -1.570796 ,

7.41399396e -269],
NaN]])

0.

,

1.570796 ,

3.141592])

.

.

.

.NumPy / SciPy

. .9 / 34

Manejando los ejes

>>> a = arange(6)
>>> a
array([0, 1, 2, 3, 4, 5])
>>> a.shape = (2, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])

>>> a.shape = (3, 2)
>>> a
array([[0, 1],
[2, 3],
[4, 5]])

>>> a.size
6

.

.

.

.NumPy / SciPy

. .10 / 34

Operaciones básicas

1 Los operadores aritméticos se aplican por elemento

>>> a = arange(20, 60, 10)
>>> a
array([20, 30, 40, 50])
>>> a + 1
array([21, 31, 41, 51])
>>> a * 2
array([ 40,

60,

80, 100])

1 Si es inplace, no se crea otro array

>>> a
array([20, 30, 40, 50])
>>> a /= 2
>>> a
array([10, 15, 20, 25])

.

.

.

.NumPy / SciPy

. .11 / 34

Operaciones básicas

1 Podemos realizar comparaciones

>>> a = arange(5)
>>> a >= 3
array([False , False , False ,
>>> a % 2 == 0
array([ True , False ,

True ,

True], dtype=bool)

True , False ,

True], dtype=bool)

1 También con otros arrays

>>> b = arange(4)
>>> b
array([0, 1, 2, 3])
>>> a - b
array([20, 29, 38, 47])
>>> a * b
array([

30,

0,

80, 150])

.

.

.

.NumPy / SciPy

. .12 / 34

Operaciones básicas

1 Tenemos algunos métodos con cálculos típicos

>>> c
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> c.min(), c.max()
(0, 9)
>>> c.mean()
4.5
>>> c.sum()
45
>>> c.cumsum()
array([ 0,
1,

3,

6, 10, 15, 21, 28, 36, 45])

1 Hay muchas funciones que nos dan info del array

1 all, alltrue, any, argmax, argmin, argsort, average, bincount, ceil, clip,

conj, conjugate, corrcoef, cov, cross, cumprod, cumsum, diff, dot, floor,
inner, inv, lexsort, max, maximum, mean, median, min, minimum,
nonzero, outer, prod, re, round, sometrue, sort, std, sum, trace,
transpose, var, vdot, vectorize, where

.

.

.

.NumPy / SciPy

. .13 / 34

Trabajando con los elementos

1 La misma sintaxis de Python
>>> a = arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[2]
2
>>> a[2:5]
array([2, 3, 4])
>>>
>>> a[1] = 88
>>> a[-5:] = 100
>>> a
array([ 0,

88,

2,

3,

4, 100, 100, 100, 100, 100])

.

.

.

.NumPy / SciPy

. .14 / 34

Trabajando con los elementos

1 Pero también podemos trabajar por eje

>>> a = arange(8).reshape((2,4))
>>> a
array([[0, 1, 2, 3],
[4, 5, 6, 7]])

>>> a[:,1]
array([1, 5])
>>> a[0,-2:]
array([2, 3])

.

.

.

.NumPy / SciPy

. .15 / 34

Cambiando la forma del array

1 Podemos usar .shape directamente

>>> a = arange(8)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> a.shape = (2,4)
>>> a
array([[0, 1, 2, 3],
[4, 5, 6, 7]])

1 Usando .shape con comodín
>>> a.shape = (4,-1)
>>> a
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])

>>> a.shape
(4, 2)

.

.

.

.NumPy / SciPy

. .16 / 34

Cambiando la forma del array

1 Transponer y aplanar

>>> a
array([[0, 1, 2, 3],
[4, 5, 6, 7]])

>>> a.transpose()
array([[0, 4],
[1, 5],
[2, 6],
[3, 7]])

>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> a
array([[0, 1, 2, 3],
[4, 5, 6, 7]])

.

.

.

.NumPy / SciPy

. .17 / 34

Juntando y separando arrays

1 Tenemos vstack y hstack

>>> a = ones((2,5)); b = arange(5)
>>> a
array([[ 1.,
[ 1.,

1.],
1.]])

1.,
1.,

1.,
1.,

1.,
1.,

>>> b
array([0, 1, 2, 3, 4])
>>> juntos = vstack((a,b))
>>> juntos
array([[ 1.,
[ 1.,
[ 0.,

1.,
1.,
1.,

1.,
1.,
2.,

1.,
1.,
3.,

1.],
1.],
4.]])

.

.

.

.NumPy / SciPy

. .18 / 34

Juntando y separando arrays

1 También hsplit y vsplit

>>> hsplit(juntos , (1,3))
[array([[ 1.],
[ 1.],
[ 0.]]),

array([[ 1.,
[ 1.,
[ 1.,
array([[ 1.,
[ 1.,
[ 3.,

1.],
1.],
2.]]),
1.],
1.],
4.]])]

.

.

.

.NumPy / SciPy

. .19 / 34

Indexado avanzado

1 Podemos indizar con otros arrays
>>> a = arange(10) ** 2
>>> i = array([ (2,3), (6,7) ])
>>> a
array([ 0,
>>> a[i]
array([[ 4,

1,

9],
[36, 49]])

4,

9, 16, 25, 36, 49, 64, 81])

1 O elegir elementos

>>> a = arange(5)
>>> b = a % 2 == 0
>>> a
array([0, 1, 2, 3, 4])
>>> b
array([ True , False ,
>>> a[b]
array([0, 2, 4])

True , False ,

True], dtype=bool)

.

.

.

.NumPy / SciPy

. .20 / 34

Matrices

1 Es un caso específico del array

>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> A = matrix(a)
>>> A
matrix([[0, 1, 2],
[3, 4, 5]])

>>> A.T
matrix([[0, 3],
[1, 4],
[2, 5]])

>>> A.I
matrix([[-0.77777778 ,
0.27777778],
[-0.11111111 ,
0.11111111],
[ 0.55555556 , -0.05555556]])

.

.

.

.NumPy / SciPy

. .21 / 34

Matrices

1 Se comportan, obviamente, como matrices

>>> A
matrix([[0, 1, 2],
[3, 4, 5]])

>>> M
matrix([[2, 3],
[4, 5],
[6, 7]])

>>> A * M
matrix([[16, 19],
[52, 64]])

.

.

.

.NumPy / SciPy

. .22 / 34

Polinomios

>>> p = poly1d([2, 3, 4])
>>> print p

2

4

2 x + 3 x + 4
>>> print p*p

3

2

4 x + 12 x + 25 x + 24 x + 16
>>> print p.deriv()
4 x + 3
>>> print p.integ(k=2)

3

2

0.6667 x + 1.5 x + 4 x + 2
>>> p(range(5))
array([ 4,

9, 18, 31, 48])

.

.

.

.NumPy / SciPy

. .23 / 34

SciPy

.

.

.

.NumPy / SciPy

. .24 / 34

Intro

1 Colección de algoritmos matemáticos y funciones

1 Construido sobre NumPy

1 Poder al intérprete interactivo

1 Procesamiento de datos y prototipado de sistemas
1 Compite con Matlab, IDL, Octave, R-Lab, y SciLab

.

.

.

.NumPy / SciPy

. .25 / 34

Disclaimer

1 Pueden ver toda la info de esta presentación en

http://docs.scipy.org/doc/

1 ¿Les conté que me recibí de ingeniero hace más de 9 años?

.

.

.

.NumPy / SciPy

. .26 / 34

Funciones y funciones!

1 De todo tipo!

1 airy
1 elliptic
1 bessel
1 gamma
1 beta
1 hypergeometric
1 parabolic cylinder
1 mathieu
1 spheroidal wave
1 struve
1 kelvin

.

.

.

.NumPy / SciPy

. .27 / 34

Integration

1 General integration

1 Gaussian quadrature

1 Integrating using samples

1 Ordinary differential equations

.

.

.

.NumPy / SciPy

. .28 / 34

Optimization

1 Nelder-Mead Simplex algorithm
1 Broyden-Fletcher-Goldfarb-Shanno algorithm
1 Newton-Conjugate-Gradient
1 Least-square fitting
1 Scalar function minimizers
1 Root finding

2

>>> f = poly1d([1, 4, 8])
>>> print f

1 x + 4 x + 8
>>> roots(f)
array([-2.+2.j, -2.-2.j])
>>> f(-2.+2.j)
0j

.

.

.

.NumPy / SciPy

. .29 / 34

Interpolation

1 Linear 1-d interpolation
1 Spline interpolation in 1-d
1 Two-dimensional spline representation

.

.

.

.NumPy / SciPy

. .30 / 34

Signal Processing

1 B-splines

1 second- and third-order cubic spline coefficients
1 from equally spaced samples in one- and two-dimensions

1 Filtering

1 Convolution/Correlation
1 Difference-equation filtering
1 Other filters: Median, Order, Wiener, Hilbert, ...

.

.

.

.NumPy / SciPy

. .31 / 34

Algebra lineal

1 Matrices

1 Inversas
1 Determinantes
1 Resolución de sistemas lineales

1 Descomposiciones

1 Eigenvalues and eigenvectors
1 Singular value, LU, Cholesky, QR, Schur

1 Funciones de matrices

1 Exponentes y logaritmos
1 Trigonometría (común e hiperbólica)

.

.

.

.NumPy / SciPy

. .32 / 34

Estadísticas

1 Masked statistics functions

1 64!

1 Continuous distributions

1 81!

1 Discrete distributions

1 12!

1 Statistical functions

1 72!

.

.

.

.NumPy / SciPy

. .33 / 34

¡Muchas gracias!

¿Preguntas?

¿Sugerencias?

Facundo Batista
[email protected]
http://www.taniquetil.com.ar

Licencia: Creative Commons
Atribución-NoComercial-CompartirDerivadasIgual 2.5 Argentina
http://creativecommons.org/licenses/by-nc-sa/2.5/deed.es_AR

.

.

.NumPy / SciPy

. .34 / 34

.
  • Links de descarga
http://lwp-l.com/pdf3371

Comentarios de: NumPy + SciPy (0)


No hay comentarios
 

Comentar...

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad