#!/usr/bin/env python # coding: utf-8 # #Data Science con Python # ##(o un breve raconto de las libs para laburar con datos) # ## ¿Quién les habla? # ### *de iure*: # # * Lic. en Bioquímica. # * Doctorando en Ciencias Biológicas (escribiendo... una tesis inmunológica). # ### *de facto*: # # * Desarrollador Python/JS (ponele...). # * Científico de Datos (ponele...). # * Analista Cuantitativo en Finanzas (ponele...) # # Curioso... #

[damianavila](https://github.com/damianavila)

# #

[@damian_avila](http://twitter.com/damian_avila)

# #

damianavila@gmail.com

# #

[www.damian.oquanta.info](http://www.damian.oquanta.info)

# ## ¿Qué hace un científico? # * **Observa** # * Genera una **hipótesis** sobre el/los fenómeno/s observado/s # * Diseña y realiza un **experimento** (o una **simulación**) para testear la hipótesis # * Obtiene **datos** del experimento (o la simulación) # * **Procesa** y **visualiza** los datos obtenidos # * Propone un **modelo** para explicar los datos procesados # * Genera **predicciones** a partir del modelo propuesto # * **Contrasta** (valida) las predicciones con los datos experimentales (o simulados) # * **Comunica** la hipótesis, los resultados obtenidos y el modelo propuesto # ###The Cross Industry Standard Process for Data Mining # ![models1](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b9/CRISP-DM_Process_Diagram.png/479px-CRISP-DM_Process_Diagram.png) # ###Data Science Workflow # ![models2](http://cacm.acm.org/system/assets/0001/3678/rp-overview.jpg) # ##¿Qué necesita un científico de datos? # * Un lenguaje **fácil** de aprender. # * Un lenguaje **versátil** en su utilización. # * Un lenguaje con una sintaxis **simple** y de **alto nivel**. # * Una colección de **herramientas** para el tratamiento de datos. # * Múltiples opciones para la **visualización** de datos. # * Un "entorno" **unificado** e **interactivo**. # #Python # * Un lenguaje **fácil** de aprender. # * Un lenguaje con una sintaxis **simple** y de **alto nivel**. # * Un lenguaje **versátil** en su utilización. # ##y las baterías adicionales... # * Una colección de **herramientas** para el tratamiento de datos. # ###Bajo nivel... # * [**Numpy**](http://www.numpy.org), objetos tipo arreglos y rutinas para manipularlos. # * Python tiene listas, enteros, punto flotante, etc. Para cálculo numérico necesitamos más... allí aparece Numpy. # * Numpy es un paquete que provee a Python con arreglos multidimensionales de alta eficiencia y diseñados para cálculo científico. # * Un array puede contener: # * tiempos discretos de un experimento o simulación. # * señales grabadas por un instrumento de medida. # * pixeles de una imagen, etc. # ### El objeto *arreglo*. # # * Los arreglos de NumPy son de tipado estático y homogéneo. # * Multidimensionales. # * Son más eficientes en el uso de la memoria. La funciones matemáticas complejas y computacionalmente costosas (pj: la multiplicación de matrices) son implementadas en lenguajes compilados como C o Fortran. # In[1]: import numpy as np # In[2]: lista = [1, 2, 3, 4 , 5] lista # In[3]: a = np.array(lista) a # In[4]: type(a) # In[5]: a.dtype # In[6]: a.ndim # In[7]: a.shape # ###Indexado y cortes # In[8]: a = np.arange(10) a # In[9]: a[0], a[2], a[-1] # In[11]: mis_indices = [0, 2, -1] # In[12]: a[mis_indices] # In[13]: a[2:9] # In[14]: a[2:9:3] # In[15]: a[::2] # In[16]: a[3::2] # In[17]: a[-2:] # ###Copias y Vistas # ####Plain Python # In[18]: a = [1, 2, 3] b = a[:] b # In[19]: b[0] = 100 b # In[20]: a # ####Numpy # In[21]: a = np.array([1, 2, 3]) b = a[:] b # In[22]: b[0] = 100 # In[23]: a # ###¿Qué más tenemos en Numpy? # * Operaciones por elementos: # * Escalares # * Aritméticas # * Lógicas # # * Reducciones básicas: # * Aritmeticas # * Estadísticos # * Lógicas # # * Broadcasting: # # En NumPy es posible hacer operaciones entre arreglos de diferente tamaño a través del broadcasting. NumPy transforma (propaga) los arreglos involucrados para que tengan el mismo tamaño y, por tanto, puedan someterse a las operaciones por elementos sin generar excepciones. # # * Manipulación de arreglos # # * I/O # # * Algebra lineal básica # * [**Scipy**](http://www.scipy.org), biblioteca para procesamiento de datos de alto nivel: optimización, regresión, interpolación, etc. # SciPy se desarrolla sobre NumPy y provee de un gran número de algoritmos científicos de alto nivel. # # * Functiones especiales (scipy.special) # * Integración (scipy.integrate) # * Optimización (scipy.optimize) # * Interpolación (scipy.interpolate) # * Transformadas de Fourier (scipy.fftpack) # * Procesamiento de señales (scipy.signal) # * Algebra lineal(scipy.linalg) # * Problemas de matrices dispersas (scipy.sparse) # * Estadística (scipy.stats) # * Procesamiento de imágenes multidimensional (scipy.ndimage) # * IO (scipy.io) # ###Buscando mínimos y máximos de una función. # In[24]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from scipy import optimize # In[25]: def f(x): return 4*x**3 + (x-2)**2 + x**4 # In[26]: fig, ax = plt.subplots() x = np.linspace(-5, 3, 100) ax.plot(x, f(x)); # Podemos usar la función fmin_bfgs para buscar los mínimos locales: # In[27]: x_min = optimize.fmin_bfgs(f, -2) x_min # In[28]: optimize.fmin_bfgs(f, 0.5) # In[29]: optimize.brent(f) # In[30]: optimize.fminbound(f, -4, 2) # ###Alto nivel... # * [**pandas**](http://pandas.pydata.org/), "el cinturón de Batman para el analista de datos". El actor principal es el objeto DataFrame, una estructura de datos bidimensional con filas y columnas indexables, inspirado en el dataframe de R. # Algunas de sus principales características son: # # * DataFrame # * Indexado por filas y columnas # * Indexado booleano # * Tratamiento de valores NA # * Broadcasting # * Excelente métodos de "split", "apply", "combine", "groupby" # * Estadística (media, std, corr, etc.) # * Mergeado, unión y concatenación de datasets # In[31]: import pandas as pd df2 = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1,index=range(4),dtype='float32'), 'D' : np.array([3] * 4,dtype='int32'), 'E' : 'foo' }) df2 # In[32]: df2.dtypes # In[33]: dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD')) df # In[34]: df.head(2) # In[35]: df.tail(3) # In[36]: df.index # In[37]: df.columns # In[38]: df.values # In[39]: df.describe() # In[40]: df.T # In[41]: df.sort_index(axis=1, ascending=False) # In[42]: df.sort(columns='B') # In[44]: type(df['A']) # In[45]: df[0:3] # In[46]: df['20130102':'20130104'] # In[47]: df.mean() # In[48]: df.apply(np.cumsum) # In[49]: df = pd.DataFrame(np.random.randn(10, 4)) df # In[51]: pieces = [df[:3], df[3:7], df[7:]] # In[52]: pieces[0], pieces[2] = pieces[2], pieces[0] # In[53]: pd.concat(pieces) # In[54]: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C' : np.random.randn(8), 'D' : np.random.randn(8)}) df # In[55]: df.groupby('A').sum() # In[56]: df.groupby(['A','B']).sum() # * [**statsmodels**](http://statsmodels.sourceforge.net/), modelos estadísticos y econometría # * Modelos de regresión lineal # * Modelos lineas generalizados # * Modelos lineares robustos # * Modelos de series de tiempo # * Estimadores no paramétricos # * Tests estadísticos # * Integración con pandas # In[57]: import pandas as pd import statsmodels.api as sm import numpy as np # read the data in df = pd.read_csv("http://www.ats.ucla.edu/stat/data/binary.csv") # rename the 'rank' column because there is also a DataFrame method called 'rank' df.columns = ["admit", "gre", "gpa", "prestige"] dummy_ranks = pd.get_dummies(df['prestige'], prefix='prestige') dummy_ranks.head() # In[58]: # create a clean data frame for the regression cols_to_keep = ['admit', 'gre', 'gpa'] data = df[cols_to_keep].join(dummy_ranks.ix[:, 'prestige_2':]) data.head() # In[59]: # manually add the intercept data['intercept'] = 1.0 train_cols = data.columns[1:] # Index([gre, gpa, prestige_2, prestige_3, prestige_4], dtype=object) logit = sm.Logit(data['admit'], data[train_cols]) # fit the model result = logit.fit() result.summary() # * Múltiples opciones para la **visualización** de datos. # ###Fuera del browser... # # * matplotlib # # * Matplotlib es una biblioteca para generar figuras en 2 y 3 dimensiones. # * Es fácil de aprender. # * Soporta LATEX para etiquetas y texto. # * Cada uno de los elementos de la figura pueden controlarse programaticamente (reproducibilidad). # * Varios formatos para la exportación de las figuras: PNG, PDF, SVG y EPS. # * GUI para la exploraración interactiva las figuras. # * [Galería](http://matplotlib.org/gallery.html) # * ggplot, "me quiero parecer al ggplot de R" # * prettyplotlib, "no quiero ser tan feo como matplotlib" # * seaborn # * "quiero ser lindo e inteligente" # * Interfase de alto nivel para plotear gráficos estadísticos "lindos". # * [Galería](http://web.stanford.edu/~mwaskom/software/seaborn/examples/index.html) # ###En el browser... # # * Bokeh # * Laburo en Bokeh así que ojo con lo que dicen... # * [Galería](http://bokeh.pydata.org/en/latest/docs/gallery.html) # # * plotly # * Parecido a Bokeh pero hay que pagar... # * Un "entorno" **unificado** e **interactivo**. # * [**IPython**/**Jupyter**](http://ipython.org), un interprete interactivo avanzado, un web-notebook, una infraestructura para *computación* en paralelo. # ##Y además... # * scikit-learn (a.k.a, machine learning en python) # Incluye (entre otras cosas): # # * Biclustering # * Clustering # * Covariance estimation # * Cross decomposition # * Dataset examples # * Decomposition # * Ensemble methods # * Gaussian Process for Machine Learning # * Generalized Linear Models # * Manifold learning # * Gaussian Mixture Models # * Nearest Neighbors # * Semi Supervised Classification # * Support Vector Machines # * Decision Trees # In[60]: import numpy as np import pylab as pl from matplotlib.colors import ListedColormap from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_moons, make_circles, make_classification from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.lda import LDA from sklearn.qda import QDA h = .02 # step size in the mesh names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Decision Tree", "Random Forest", "Naive Bayes", "LDA", "QDA"] classifiers = [ KNeighborsClassifier(3), SVC(kernel="linear", C=0.025), SVC(gamma=2, C=1), DecisionTreeClassifier(max_depth=5), RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1), GaussianNB(), LDA(), QDA()] X, y = make_classification(n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1) rng = np.random.RandomState(2) X += 2 * rng.uniform(size=X.shape) linearly_separable = (X, y) datasets = [make_moons(noise=0.3, random_state=0), make_circles(noise=0.2, factor=0.5, random_state=1), linearly_separable ] figure = pl.figure(figsize=(24, 8)) i = 1 # iterate over datasets for ds in datasets: # preprocess dataset, split into training and test part X, y = ds X = StandardScaler().fit_transform(X) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4) x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # just plot the dataset first cm = pl.cm.RdBu cm_bright = ListedColormap(['#FF0000', '#0000FF']) ax = pl.subplot(len(datasets), len(classifiers) + 1, i) # Plot the training points ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright) # and testing points ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6) ax.set_xlim(xx.min(), xx.max()) ax.set_ylim(yy.min(), yy.max()) ax.set_xticks(()) ax.set_yticks(()) i += 1 # iterate over classifiers for name, clf in zip(names, classifiers): ax = pl.subplot(len(datasets), len(classifiers) + 1, i) clf.fit(X_train, y_train) score = clf.score(X_test, y_test) # Plot the decision boundary. For that, we will asign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. if hasattr(clf, "decision_function"): Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) else: Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1] # Put the result into a color plot Z = Z.reshape(xx.shape) ax.contourf(xx, yy, Z, cmap=cm, alpha=.8) # Plot also the training points ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright) # and testing points ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6) ax.set_xlim(xx.min(), xx.max()) ax.set_ylim(yy.min(), yy.max()) ax.set_xticks(()) ax.set_yticks(()) ax.set_title(name) ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'), size=15, horizontalalignment='right') i += 1 figure.subplots_adjust(left=.02, right=.98) pl.show() #

Gracias!

#

[damianavila](https://github.com/damianavila)

# #

[@damian_avila](http://twitter.com/damian_avila)

# #

damianavila@gmail.com

# #

[www.damian.oquanta.info](http://www.damian.oquanta.info)