markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
Podemos usar del para eliminar columnas, de la misma forma que podemos hacerlo con diccionarios. | del datos['mes']
datos | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Es posible extraer los datos de un DataFrame en forma de arreglo de NumPy. | datos.values | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Fijense que el dtype del arreglo es object. Esto se debe a la mezcla de enteros, strings y flotantes. El dtype es elegido por Pandas automaticamente de forma tal de acomodar todos los tipos de valores presentes en el DataFrame.
¿Qué hubiéramos obtenido si la columna phylum no fuese parte del dataFrame?
<br>
<br>
<br>
<br>
Además es posible realizar operaciones típica de arrays sobre DataFrame, por ejemplo transponerlo. | datos.T | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Index
La última estructura de datos que nos queda ver es Index, la cual en realidad la venimos usando desde el principio de este capítulo. Solo que ahora hablaremos de ella de forma un poco más explícita. | datos.index | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Los Index son inmutables, no puede ser modificados una vez creados, lo cual pueden comprobar al descomentar y ejecutar la siguiente celda. | #datos.index[0] = 15 | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
La inmutabilidad del Index tiene como función permitir que los Index se compartan entre objetos sin riesgo de que se modifiquen en algún momento. Esto es lo que permite agregar una Series a un DataFrame aunque sus longitudes no coincidan, Pandas busca que sean los índices los que coincidan y si hiciera falta completa los valores que sean necesarios.
Importando datos
En principio es posible usar Python para leer cualquier archivo que uno desee, pero para el trabajo rutinario de anñalisis de datos es preferible tener a mano funciones enlatadas que permitan leer los formatos más comunes. NumPy provee de algunas funciones para leer archivos, como genfromtxt y loadtxt. Pandas ofrece funciones más vestátiles y robustas. Empecemos leyendo un archivo en formato csv (comma separated values). | !head datos/microbioma.csv # este es un comando de Linux que nos permite ver las primeras lineas de un archivo | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Pandas ofrece una función llamada read_csv ideal para leer este tipo de datos: | mb = pd.read_csv('datos/microbioma.csv')
type(mb) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
De forma similar al comando head de Linux, le podemos pedir a Pandas que nos nuestre solo las primeras lineas. | mb.head() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Por defecto read_csv usará la primer linea del archivo como encabezado (header). Este comportamiento lo podemos modificar usando el argumento header. | pd.read_csv('datos/microbioma.csv', header=None).head() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Por defecto read_csv usa , como separadores, pero es posible modificar este comportamiento usando el argumento sep. Un caso muy común es el de archivos que tienen una cantidad variable de espacios en blanco. En esos casos podemos usar una expresión regular:
sep='\s+'
'\s+' quiere decir "1 o más espacios en blanco". Otro caso común son archivos separados por tabulaciones (tabs), en ese caso podemos usar \t.
Si queremos omitir datos (por ejemplo datos mal tomados), podemos indicaselo a Pandas usando el argumento skiprows: | pd.read_csv('datos/microbioma.csv', skiprows=[3,4,6]).head() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
También podemos indicarque que solo queremos importar unas pocas columnas, lo que puede ser muy útil cuando estamos haciendo pruebas y explorando los datos y queremos evitar importar un larga lista de datos. | pd.read_csv('datos/microbioma.csv', nrows=4) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Pandas ofrece la capacidad de leer varios otros formatos incluyendo archivos xls, xlsx, JSON, XML, HDF5, etc. Para más información leer la documentación de Pandas o Python for Data Analysis.
Agregando datos
Se llama agregación de datos a las operaciones que reducen un conjunto de números a uno (o unos pocos) números. Entre estas operaciones se encuentran la media, mediana, desviación estándar, mínimo, máximo, conteo, suma, producto, etc.
Para averiguar el total de bacterias encontradas en tejido en nuestro conjunto de datos podemos hacer: | mb['Tejido'].sum() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Pandas ofrece además un método que describe un DataFrame utilizando varias de estas operaciones de agregado: | mb.describe() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Es común al analizar datos, que nos interese agregar datos respecto de alguna variable en particular por ejemplo podríamos querer obtener los valores promedios por Grupo. Para ello podemos usar el método groupby. | mb.groupby('Grupo').mean().round(0) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Conceptualmente podemos pensar que groupby realiza los siguientes pasos:
Dividir el DataFrame en subgrupos según las variables que le pasemos.
Aplicar la operación especificada sobre cada subgrupo.
Combinar los subgrupos en un solo DataFrame. | mb.groupby('Paciente').mean() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
No estamos limitados a una sola variable | mb.groupby(['Grupo', 'Paciente']).mean() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Al aplicar el método groupby se obtiene un objeto sobre el cual se puede operar de forma flexible | mb.groupby('Grupo') | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Por ejemplo podemos indexarlo usando los nombres de las columnas, podríamos querer hacer esto para saber cuantos pacientes tenemos en cada grupo | mb.groupby('Grupo')['Paciente'].count()
mb.groupby('Grupo')['Heces'].describe().round(2) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
El método aggregate permite agregar datos de forma muy flexible. Este método acepta una lista de funciones (o incluso algunos strings asocidados a ciertas funciones), siempre y cuando estas funciones agreguen datos. | mb.groupby('Grupo')['Heces'].aggregate([min, np.median, 'max']) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Incluso es posible pasar un diccionario indicando que operaciones (values) se aplican sobre cuales columnas (keys). | mb.groupby('Grupo').aggregate({'Heces': [min, max], 'Paciente': 'count'})
da = mb.groupby('Grupo').aggregate({'Heces': [min, max], 'Paciente': 'count'}) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Otro método que se puede aplicar sobre un objeto groupby es filter. Este método permite filtrar el resultado mediante una función arbitraria. Supongamos que fuese de interés saber cuales pacientes tuvieron un conteo mayor a 120 bacterias para todas las categorías taxonómicas medidas. | def filtro(x):
return np.all(x['Tejido'] > 120)
mb.groupby('Paciente').filter(filtro) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Para mayor claridad de los resultados podríamos querer ordenar el DataFrame resultante en función de la columna 'Paciente' | mb.groupby('Paciente').filter(filtro).sort_values('Paciente') | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
La función que pasamos a filter debe ser una función que devuelva un booleano. Los grupos para los cuales esta función evaluen como True serán los que observaremos como resultado.
Otro método disponible es transform. A diferencia de aggregate y de filter la función que pasamos debe devolver un resultado con el mismo shape de los datos que le pasamos. Una transformación que es común al analizar datos es estandarizarlos (esto facilita el desempeño de muchos métodos y algoritmos). | def estandarizar(x):
return (x - x.mean()) / x.std()
mb.groupby('Paciente')[['Tejido', 'Heces']].transform(estandarizar) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Una característica de Python que no vimos en la primer notebook es la posibilidad de escribir funciones anónimas, es decir funciones que no tienen nombre. Esto se conoce como funciones lambda. Siguiendo el ejemplo anterior la sintaxis para una función anónima que estandariza datos es:
lambda x: (x - x.mean()) / x.std()
Por lo que podríamos escribir. | mb.groupby('Paciente')[['Tejido', 'Heces']].transform(lambda x: (x - x.mean()) / x.std()) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Por último tenemos al método apply, el cual nos permite aplicar una función arbitraria a los subgrupos. La función debe tomar un DataFrame y devolver un DataFrame, Series o un escalar.
Si necesitaramos normalizar el conteo en las Heces usando el conteo en el Tejido. | def norm(x):
x['Heces'] /= x['Tejido'].sum()
return x
mb.groupby('Grupo').apply(norm) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Vamos a cerrar esta sección con un ejemplo tomado de Python Data Science Handbook. Este ejemplo combina varias de las operaciones vistas hasta ahora. El objetivo es obtener un listado por década de la cantidad de exoplanetas descubiertos con diversos métodos.
Primero cargamos los datos | planets = sns.load_dataset('planets')
planets.head() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Luego, apartir de la columna year creamos una Series llamada decades. Es importante notar que no estamos modificando el DataFrame planets | decade = (10 * (planets['year'] // 10)).astype(str) + 's'
decade.name = 'decade'
decade.head(8) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Y por último aplicamos una combinación de operaciones en una sola linea! | planets.groupby(['method', decade])['number'].sum().unstack().fillna(0) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Antes de continuar conviene detenerse a estudiar que es lo que hace cada elemento de la expresión anterior
<br>
<br>
<br>
<br>
Datos faltantes
Es común al analizar datos encontrarnos con datos faltantes. Las razones son variadas desde errores de transcripción, errores en la toma de muestra, observaciones incompletas, etc. En algunos casos estos datos faltantes quedan registrados simplemente como huecos en el conjunto de datos o usando algunos valores sentinelas como NaN, None o valores que esten claramente fuera del rango de los datos como podrían ser -9999 para valores de datos positivos o 999 para valores que, estamos seguros, son inferiores a 100. | !head datos/microbioma_faltantes.csv
mbm = pd.read_csv('datos/microbioma_faltantes.csv')
mbm.head(14) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
En el ejemplo anterior Pandas reconoció correctamente a NA y a un campo vacío como datos faltantes, pero pasó por alto a ? y a -99999. Es facil pasar por alto estos errores, por lo que siempre es buena idea hacer gráficos de los datos y resúmenes como el siguiente: | mbm.describe() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Se puede ver que el conteo (count) para Paciente y Heces no coinciden, que el valor más pequeño para Heces es un número negativo cuando debería ser mayor o igual a cero. Y vemos que no tenemos descripción para Tejido!
¿Se te ocurre por que falta la columna para Tejido?
<br>
<br>
<br>
<br>
Podemos indicarle a Pandas que valores debe considerar como datos faltantes. Para eso usamos el argumento na_values. | mbm = pd.read_csv('datos/microbioma_faltantes.csv', na_values=['?', -99999])
mbm.describe() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Si fuese necesario especificar valores distintos para distintas columnas es posible pasar un diccionario a na_values, indicando los nombres de las columnas y los valores a usar como indicadores.
Este es un buen momento para que pruebes como hacer esto antes de seguir con la nueva sección.
<br>
<br>
<br>
<br>
Operaciones con datos faltantes
Pandas ofrece métodos que nos permiten detectar, remover y reemplazar datos faltantes. Podemos preguntar a Pandas cuales son los valores null. | mbm.isnull()[:3] # y su opuesto .notnull() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
O podríamos querer eliminar los valores nulos. Esto es posible usando dropna(). En el caso de una Series es posible eliminar solo los valores nulos. En el caso de DataFrames esto no es posible, a menos que eliminemos toda la fila (o columna) donde aparece ese valor nulo. Por defecto dropna() eliminará todas las filas que contengan al menos un valor nulo. | mbm.dropna().head(11) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Es posible que no estemos interesados en remover los valores nulos si no que en cambio nos interese rellenar los valores nulos con algún número que tenga sentido para nuestro análisis. | mbm.fillna(42).head(11) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
O simplemente completando con otros valores del propio DataFrame. | mbm.fillna(method='ffill').head(11)
dada = pd.read_csv('datos/microbioma.csv')
dada.head() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Combinación de DataFrames
concat
Así como NumPy tiene una función concatenate que permite concatenar arrays, Pandas tiene una función llamada concat que esencialmente permite concatenar Series o DataFrame. | ser1 = pd.Series(['A', 'B', 'C'], index=[1, 2, 3])
ser2 = pd.Series(['D', 'E', 'F'], index=[4, 5, 6])
pd.concat([ser1, ser2])
df0 = pd.DataFrame({'A': [0, 2], 'B': [1, 3]})
df0
df1 = pd.DataFrame({'A': [4, 6], 'B': [5, 7]})
df1 | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Al concatenar los índices se preservan incluso si esto da origen a duplicados | pd.concat([df0, df1]) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Es posible concatenar ignorando los índices originales. En este caso Pandas generará un nuevo índice. | pd.concat([df0, df1], ignore_index=True) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Como vimos al concatenar arrays es posible pasar el argumento axis | pd.concat([df0, df1], axis=1) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
En caso que sea necesario verificar que los índices no se superponen es posible pasar el argumento verify_integrity=True. | df2 = pd.DataFrame({'A': [2, 6], 'B': [0, 1], 'C': [9, -1]})
df2 | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
En caso de que los nombre de las columnas no coincidan al contenar Pandas completará los espacios faltantes con NaN. | pd.concat([df0, df2]) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
concat tiene un argumento llamado join que por defecto toma el valor outer, en este caso la concatenación funciona como una unión de los nombres de las columnas. Si cambiamos el valor de join por inner, entonces la concatenación se comporta como una intersección. | pd.concat([df0, df2], join='inner') | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Una alternativa es especificar cuales son las columnas que queremos concatenar, para ello debemos pasarle al argumento join_axes una lista de Index. | pd.concat([df0, df2], join_axes=[pd.Index(['B', 'C'])]) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
append
La concatenación directa de de Series y DataFrame es tan común que en vez llamar pd.concat([df0, df1]) es posible obtener el mismo resultado haciendo: | df0.append(df1) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Una diferencia importante entre este append() y el que vimos para listas de Python es que Pandas no modifica el objeto original (como sucedía con las listas) si no que cada vez que hacemos un append() estamos creando un nuevo objeto con un nuevo índice. Esto hace que este método no sea muy eficiente. Dicho de otras forma mientras las listas están pensadas para hacer uso repetido del método append() los DataFrames no. Por lo tanto en caso de ser necesario hacer varios append() sobre DataFrames es mejor crear una lista de DataFrames y concatenar esa lista una sola vez.
Merge and join
Pandas ofrece operaciones del tipo merge y join que son familiares para quienes hayan trabajado con bases de datos. merge tiene implementado un subconjunto de lo que se conoce como algebra relacional que son un conjunto de reglas formales para manipular datos relacionales. Este conjunto de reglas funciona como los bloques básicos (o primitivas) con los que se construyen operaciones más complejas sobre los datos. Pandas implementa varios de estos bloques básicos.
Para mayor información por favor referirse a la documentación de Pandas y/o libros como Python Data Science Handbook y Python for Data Analysis
Indexado jerárquico
Hasta ahora hemos visto como trabajar con datos uni y bi-dimensionales. El indexado jerárquico (o multi-indexado) permite usar más de un índice en un DataFrame, de esta forma podemos trabajar en más de dos dimensiones pero usando un DataFrame. | index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
names=['año', 'visita'])
columns = pd.MultiIndex.from_product([['Ana', 'Brian', 'Carlos'], ['RC', 'Temp']],
names=['sujeto', 'tipo'])
datos = np.zeros((4, 6))
datos[:, 1::2] += np.random.normal(37, 0.5, (4, 3))
datos[:, ::2] += np.random.normal(65, 1, (4, 3))
datos_médicos = pd.DataFrame(np.round(datos, 1), index=index, columns=columns)
datos_médicos
datos_médicos['Brian'] | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Recordemos que son las columnas quienes tiene prioridad en un DataFrame, si quisieramos el ritmo cardíaco de Ana: | datos_médicos['Ana', 'RC'] | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
También es posible usar los idexadores iloc o loc. | datos_médicos.iloc[:2, :2] | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
A cada índice individual en loc e iloc se le puede pasar una tupla con índices. | datos_médicos.loc[:, ('Ana', 'RC')] | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Es necesario ser cuidadosos al intentar tomar slices por ejemplo intentar algo como
datos_médicos.loc[(:, 1), (:, 'RC')]
Daría un error de syntaxis. El resultado deseado se puede obtener empleando el objeto IndexSlice object, que Pandas provee para este tipo de situación. | idx = pd.IndexSlice
datos_médicos.loc[idx[:, 1], idx[:, 'RC']]
datos_médicos | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Así como en arrays y DataFrames es posible agregar datos (médias, sumas, etc) a lo largo de axes es posible en DataFrame multi-indexados agregar datos a lo largo de niveles. Dado que tenemos registros de dos visitas por año podríamos querer saber el promedio anual, es decir promediar a lo largo del nivel año. | media_anual = datos_médicos.mean(level='año')
media_anual | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Es posible hacer uso combinado del argumento level y axis. En el siguiente ejemplo promediamos a lo largo de las columnas, axis=1 y a lo largo del nivel 'tipo'. | media_anual.mean(axis=1, level='tipo').round(1) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Gráficos
Pandas tiene la capacidad de generar gráficos a partir de DataFrames (y Series) mediante el método plot. | mbm[['Tejido', 'Heces']].plot(kind='kde', xlim=(0)); | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Internamente los gráficos son generados usando MatplotLib por lo que tenemos libertad para modificarlos, usando la misma sintáxis de Matplotlib. | mbm[['Tejido', 'Heces']].plot(kind='kde')
plt.xlim(0); | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Caso de estudio: El Titanic
Hasta ahora hemos visto algunas de las funciones más básicas de Pandas, equipados con estos conocimientos haremos un análisis de un conjunto de datos muy usando en Ciencia de Datos, estos datos tienen información sobre el famoso y trágico viaje del transatlántico Titanic.
Usando este conjunto de datos intentaremos contestar una serie de preguntas relacionadas con las chances de supervivencia:
¿Qué porcentaje de las personas a bordo sobrevivieron?
¿Existió alguna relación entre la tasa de supervivencia y el costo del pasaje?
¿Se salvaron mujeres y niños primero como dice la conocida frase?
Podemos tomarnos un momento para pensar sobre estas preguntas y tratar de aventurar algunas respuestas, luego veremos si los datos se condicen con nuestras sospechas.
<br>
<br>
<br>
<br>
Empecemos cargando los datos | titanic = pd.read_csv('datos/Titanic.csv')
print(titanic.shape)
titanic.head() | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Se puede ver que tenemos información sobre 1310 personas (filas) que estuvieron a bordo y para cada persona tenemos 14 variables (columnas). En machinelearngua se le suele llamar features a las variables.
¿Qué tipos de variables se corresponden con cada columna?
<br>
<br>
<br>
<br>
Recordemos que podemos acceder a los nombres de las variables mediante el atributo columns. | titanic.columns | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Para algunas de estas variables veamos que porcentaje de datos faltantes tenemos: | for i in ['fare', 'pclass', 'age', 'sex']:
print('{:8s}{:4.1f} % datos faltantes'.format(i, titanic[i].isnull().mean() * 100)) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Podemos ver que los registros están casi completos excepto para la edad (age), variable para la cual el 20% de los datos son faltantes. Luego volveremos sobre esto, por ahora tratemos de constestar cual fue el porcentaje de sobrevivientes. Dado que los sobrevivientes están indicados con 1.0 y los fallecidos con 0.0, podemos obtener el porcentaje de sobrevivientes haciendo: | round(titanic['survived'].mean() * 100, 0) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Pero esta no es la única forma de hacerlo, una forma alternativa de calcular el número de sobrevivientes y fallecidos es: | (titanic['survived'].value_counts(normalize=True) * 100).round(0) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
¿Habrá alguna diferencia para los sobrevivientes en función del costo del boleto que pagaron? | boleto_fallecidos = titanic['fare'][titanic['survived'] == 0]
boleto_sobrevivientes = titanic['fare'][titanic['survived'] == 1]
'£{:.0f}, £{:.0f}'.format(boleto_fallecidos.mean(), boleto_sobrevivientes.mean()) | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Podemos ver que en promedio el grupo de fallecidos pagó menos que el grupo de sobrevivientes.
Veamos estos mismos datos, pero de forma gráfica. | boleto_fallecidos.plot(kind='kde')
boleto_sobrevivientes.plot(kind='kde')
plt.xlim(0); # valores por debajo de 0 no tienen sentido
sns.violinplot(x="survived", y="fare", data=titanic[titanic['fare'] < 200]); | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Veamos que además de la variable continua fare tenemos la variable discreta pclass que toma 3 valores de acuerdo a si las personas viajaban en primera (1), segunda (2) o tercera (3) clase. Veamos que nos dicen los datos cuando exploramos la tasa de supervivencia en función de la clase. | sns.barplot(x="pclass", y="survived", data=titanic); | 03_Manipulación_de_datos_y_Pandas.ipynb | PrACiDa/intro_ciencia_de_datos | gpl-3.0 |
Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:
- Lookup Table
- Tokenize Punctuation
Lookup Table
To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:
- Dictionary to go from the words to an id, we'll call vocab_to_int
- Dictionary to go from the id to word, we'll call int_to_vocab
Return these dictionaries in the following tuple (vocab_to_int, int_to_vocab) | import numpy as np
import problem_unittests as tests
def create_lookup_tables(text):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
"""
words = set(text)
vocab_to_int = {}
int_to_vocab = {}
for i, word in enumerate(words):
vocab_to_int[word] = i
int_to_vocab[i] = word
return vocab_to_int, int_to_vocab
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_create_lookup_tables(create_lookup_tables) | tv-script-generation/dlnd_tv_script_generation.ipynb | cranium/deep-learning | mit |
Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". Create a dictionary for the following symbols where the symbol is the key and value is the token:
- Period ( . )
- Comma ( , )
- Quotation Mark ( " )
- Semicolon ( ; )
- Exclamation mark ( ! )
- Question mark ( ? )
- Left Parentheses ( ( )
- Right Parentheses ( ) )
- Dash ( -- )
- Return ( \n )
This dictionary will be used to token the symbols and add the delimiter (space) around it. This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token "dash", try using something like "||dash||". | def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
"""
return {
'.': '%%dash%%',
',': '%%comma%%',
'"': '%%quote%%',
';': '%%semicolon%%',
'!': '%%exclamation%%',
'?': '%%questionmark%%',
'(': '%%leftparen%%',
')': '%%rightparen%%',
'--': '%%dash%%',
'\n': '%%newline%%'
}
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_tokenize(token_lookup) | tv-script-generation/dlnd_tv_script_generation.ipynb | cranium/deep-learning | mit |
Input
Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Input text placeholder named "input" using the TF Placeholder name parameter.
- Targets placeholder
- Learning Rate placeholder
Return the placeholders in the following tuple (Input, Targets, LearningRate) | def get_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
"""
return tf.placeholder(tf.int32, shape=[None, None], name='input'), tf.placeholder(tf.int32, shape=[None, None], name='target'), tf.placeholder(tf.float32, name='learning_rate')
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_inputs(get_inputs) | tv-script-generation/dlnd_tv_script_generation.ipynb | cranium/deep-learning | mit |
Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the following tuple (Cell, InitialState) | def get_init_cell(batch_size, rnn_size):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
"""
lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
cell = tf.contrib.rnn.MultiRNNCell([lstm])
initial_state = tf.identity(cell.zero_state(batch_size, tf.int32), name="initial_state")
return cell, initial_state
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_init_cell(get_init_cell) | tv-script-generation/dlnd_tv_script_generation.ipynb | cranium/deep-learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
- Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.
- Build RNN using cell and your build_rnn(cell, inputs) function.
- Apply a fully connected layer with a linear activation and vocab_size as the number of outputs.
Return the logits and final state in the following tuple (Logits, FinalState) | def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):
"""
Build part of the neural network
:param cell: RNN cell
:param rnn_size: Size of rnns
:param input_data: Input data
:param vocab_size: Vocabulary size
:param embed_dim: Number of embedding dimensions
:return: Tuple (Logits, FinalState)
"""
embed = get_embed(input_data,vocab_size,rnn_size)
rnn, final_state = build_rnn(cell, embed)
logits = tf.contrib.layers.fully_connected(rnn, vocab_size, activation_fn=None)
return logits, final_state
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_build_nn(build_nn) | tv-script-generation/dlnd_tv_script_generation.ipynb | cranium/deep-learning | mit |
Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:
- The first element is a single batch of input with the shape [batch size, sequence length]
- The second element is a single batch of targets with the shape [batch size, sequence length]
If you can't fill the last batch with enough data, drop the last batch.
For exmple, get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 3, 2) would return a Numpy array of the following:
```
[
# First Batch
[
# Batch of Input
[[ 1 2], [ 7 8], [13 14]]
# Batch of targets
[[ 2 3], [ 8 9], [14 15]]
]
# Second Batch
[
# Batch of Input
[[ 3 4], [ 9 10], [15 16]]
# Batch of targets
[[ 4 5], [10 11], [16 17]]
]
# Third Batch
[
# Batch of Input
[[ 5 6], [11 12], [17 18]]
# Batch of targets
[[ 6 7], [12 13], [18 1]]
]
]
```
Notice that the last target value in the last batch is the first input value of the first batch. In this case, 1. This is a common technique used when creating sequence batches, although it is rather unintuitive. | def get_batches(int_text, batch_size, seq_length):
"""
Return batches of input and target
:param int_text: Text with the words replaced by their ids
:param batch_size: The size of batch
:param seq_length: The length of sequence
:return: Batches as a Numpy array
"""
# TODO: Implement Function
n_batches = int(len(int_text) / (batch_size * seq_length))
# Drop the last few characters to make only full batches
xdata = np.array(int_text[: n_batches * batch_size * seq_length])
ydata = np.array(int_text[1: n_batches * batch_size * seq_length + 1])
ydata[-1] = int_text[0]
x_batches = np.split(xdata.reshape(batch_size, -1), n_batches, 1)
y_batches = np.split(ydata.reshape(batch_size, -1), n_batches, 1)
return np.array(list(zip(x_batches, y_batches)))
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_batches(get_batches) | tv-script-generation/dlnd_tv_script_generation.ipynb | cranium/deep-learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set embed_dim to the size of the embedding.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.
Set show_every_n_batches to the number of batches the neural network should print progress. | # Number of Epochs
num_epochs = 100
# Batch Size
batch_size = 1024
# RNN Size
rnn_size = 512
# Embedding Dimension Size
embed_dim = 2
# Sequence Length
seq_length = 10
# Learning Rate
learning_rate = 0.01
# Show stats for every n number of batches
show_every_n_batches = 1
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
save_dir = './save' | tv-script-generation/dlnd_tv_script_generation.ipynb | cranium/deep-learning | mit |
Implement Generate Functions
Get Tensors
Get tensors from loaded_graph using the function get_tensor_by_name(). Get the tensors using the following names:
- "input:0"
- "initial_state:0"
- "final_state:0"
- "probs:0"
Return the tensors in the following tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor) | def get_tensors(loaded_graph):
"""
Get input, initial state, final state, and probabilities tensor from <loaded_graph>
:param loaded_graph: TensorFlow graph loaded from file
:return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
"""
return loaded_graph.get_tensor_by_name('input:0'), loaded_graph.get_tensor_by_name('initial_state:0'), loaded_graph.get_tensor_by_name('final_state:0'), loaded_graph.get_tensor_by_name('probs:0')
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_tensors(get_tensors) | tv-script-generation/dlnd_tv_script_generation.ipynb | cranium/deep-learning | mit |
Bike share
This chapter presents a simple model of a bike share system and
demonstrates the features of Python we'll use to develop simulations of
real-world systems.
Along the way, we'll make decisions about how to model the system. In
the next chapter we'll review these decisions and gradually improve the
model.
Modeling
Imagine a bike share system for students traveling between Olin College
and Wellesley College, which are about 3 miles apart in eastern
Massachusetts.
Suppose the system contains 12 bikes and two bike racks, one at Olin and
one at Wellesley, each with the capacity to hold 12 bikes.
As students arrive, check out a bike, and ride to the other campus, the
number of bikes in each location changes. In the simulation, we'll need
to keep track of where the bikes are. To do that, we'll use a function called State, which is defined in the ModSim library.
We can import it like this. | from modsim import State | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
Now we can call it like this: | bikeshare = State(olin=10, wellesley=2) | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
These values make up the state of the system.
We can update the state by assigning new values to the variables.
For example, if a student moves a bike from Olin to Wellesley, we can figure out the new values and assign them: | bikeshare.olin = 9
bikeshare.wellesley = 3 | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
One benefit of defining functions is that you avoid repeating chunks of
code, which makes programs smaller. Another benefit is that the name you
give the function documents what it does, which makes programs more
readable.
If statements
The ModSim library provides a function called flip, which we can import like this: | from modsim import flip | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
When you call it, you provide a probability between 0 and 1, like 0.7, as an example: | flip(0.7) | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
The result is one of two values: True with probability 0.7 or False
with probability 0.3. If you run flip like this 100 times, you should
get True about 70 times and False about 30 times. But the results
are random, so they might differ from these expectations.
True and False are special values defined by Python. Note that they
are not strings. There is a difference between True, which is a
special value, and 'True', which is a string.
True and False are called boolean values because they are
related to Boolean algebra (https://modsimpy.com/boolean).
We can use boolean values to control the behavior of the program, using
an if statement: | if flip(0.5):
print('heads') | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
We can create a new, empty TimeSeries like this: | from modsim import TimeSeries
results = TimeSeries() | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
The left column is the time stamps; the right column is the quantities (which might be negative, depending on the state of the system).
At the bottom, dtype is the type of the data in the TimeSeries; you can ignore this for now.
ModSim provides a function called show that displays the TimeSeries as a table: | from modsim import show
show(results) | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
You don't have to use show, but I think it looks better.
Plotting
results provides a function called plot we can use to plot
the results, and the ModSim library provides decorate, which we can use to label the axes and give the figure a title: | from modsim import decorate
results.plot()
decorate(title='Olin-Wellesley Bikeshare',
xlabel='Time step (min)',
ylabel='Number of bikes') | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
Exercise: Make a State object with a third state variable, called babson, with initial value 0, and display the state of the system. | # Solution
bikeshare = State(olin=10, wellesley=2, babson=0)
bikeshare | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
Opening the hood
This section contains additional information about the functions we've used an pointers to their documentation.
You don't need to know anything in these sections, so if you are already feeling overwhelmed, you might want to skip them. But if you are curious, read on.
The State object defined in the ModSim library, is based on the SimpleNamespace object defined in a standard Python library called types; the documentation is at https://docs.python.org/3.7/library/types.html#types.SimpleNamespace.
The TimeSeries object is based on the Series object defined by a library called Pandas.
The documentation is at https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html.
show works by creating another Pandas object, called a DataFrame, which can be displayed as a table.
We'll use DataFrame objects in future chapters.
Series objects provide their own plot function, but the syntax is different from the other functions we've used, so ModSim provides a function called plot just to make it consistent.
decorate is based on Matplotlib, which is most widely-used plotting function for Python. Matplotlib provides separate functions for title, xlabel, and ylabel.
decorate makes them a little easier to use.
The flip function uses NumPy's random function to generate a random number between 0 and 1, then returns True or False with the given probability.
You can get the source code for flip by running the following cell. | from modsim import source_code
source_code(flip) | soln/chap02.ipynb | AllenDowney/ModSim | gpl-2.0 |
a) We load the breast cancer data set. | url = "https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data"
dataset = pandas.read_csv(url) | notebooks/robin_ue1/04_Preprocessing_and_pipelines.ipynb | hhain/sdap17 | mit |
b) We split the data into features X and labels y. After that we transform the binary labels to numerical values. | array = dataset.values
X = array[:,[0] + list(range(2,32))]
# transform binary labels to numerical values
# benign -> 0, malignant -> 1
le = LabelEncoder()
le.fit(["M", "B"])
y = le.transform(array[:,1]) | notebooks/robin_ue1/04_Preprocessing_and_pipelines.ipynb | hhain/sdap17 | mit |
c) Next we split the data into a training and a validation set. | random_state = 1
test_size = 0.20
train_size = 0.80
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size,
train_size=train_size, random_state=random_state) | notebooks/robin_ue1/04_Preprocessing_and_pipelines.ipynb | hhain/sdap17 | mit |
d) Now we set up and train a pipeline which contains a scaler, dimensionality reduction and a classificator. | scaler = StandardScaler()
pca = PCA(n_components=2)
logistic = LogisticRegression(random_state=1)
pipeline = Pipeline(steps=[('StandardScaler', scaler), ('PCA', pca),
('LogisticRegression', logistic)])
pipeline.fit(X_train, y_train) | notebooks/robin_ue1/04_Preprocessing_and_pipelines.ipynb | hhain/sdap17 | mit |
e) Now we evaluate the score of our pipeline. | accuracy = pipeline.score(X_test, y_test)
print("Pipelines reaches with PCA an accuracy of:", accuracy) | notebooks/robin_ue1/04_Preprocessing_and_pipelines.ipynb | hhain/sdap17 | mit |
f) Now we use RFE instead of PCA for feature selection. | # set up and train pipeline with RFE
scaler = StandardScaler()
logistic = LogisticRegression(random_state=1)
rfe = RFECV(logistic, scoring='accuracy')
pipeline = Pipeline(steps=[('StandardScaler', scaler), ('rfe', rfe),
('LogisticRegression', logistic)])
pipeline.fit(X_train, y_train) | notebooks/robin_ue1/04_Preprocessing_and_pipelines.ipynb | hhain/sdap17 | mit |
And look at our findings. | plt.plot(range(1, len(rfe.grid_scores_) + 1), rfe.grid_scores_, "ro")
plt.xlabel("selected features")
plt.ylabel("accuracy")
plt.show()
print("Highest accuracy is achieved with:", rfe.n_features_, "features")
print()
print("From the given 31 features numbered from 0 to 30 these are:")
i = 0
while i < len(rfe.support_):
if rfe.support_[i]:
print(i)
i += 1
print()
accuracy = pipeline.score(X_test, y_test)
print("The pipeline reaches with RFE a maximum accuracy of:", accuracy) | notebooks/robin_ue1/04_Preprocessing_and_pipelines.ipynb | hhain/sdap17 | mit |
数据载入
dataset | df = pd.read_csv('breast-cancer-wisconsin.data', names=[
'Sample code number',
'Clump Thickness',
'Uniformity of Cell Size',
'Uniformity of Cell Shape',
'Marginal Adhesion',
'Single Epithelial Cell Size'
'Bare Nuclei',
'Bland Chromatin',
'Normal Nucleoli',
'Mitoses',
'Class'
])
df.head()
df.shape
df.info()
df = df.replace(to_replace='?', value=np.nan)
df.isnull().sum()
df.dropna(how='any', inplace=True)
df.shape
df.isnull().sum() | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
测试样本 | from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df[df.columns[0:9]], df[df.columns[9]], test_size=0.25, random_state=33)
y_train.value_counts()
y_test.value_counts()
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.fit_transform(X_test)
X_train
lr = LogisticRegression()
sgdb = SGDClassifier()
lr.fit(X_train, y_train)
lr_y_predict = lr.predict(X_test)
lr_y_predict
y_test
sgdb.fit(X_train, y_train)
sgdb_y_predict = sgdb.predict(X_test)
sgdb_y_predict | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
性能评测 | from sklearn.metrics import classification_report
print 'Accuracy of LR', lr.score(X_test, y_test)
print classification_report(y_test, lr_y_predict, target_names=['Benign', 'Malignant'])
print 'Accuracy of SGDC', sgdb.score(X_test, y_test)
print classification_report(y_test, sgdb_y_predict, target_names=['Benign', 'Malignant']) | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
手写体 SVM
加载数据 | from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
测试数据 | from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.25, random_state=33)
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.fit_transform(X_test) | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
模型训练 | lsvc = LinearSVC()
lsvc.fit(X_train, y_train)
y_predict = lsvc.predict(X_test)
y_predict
from sklearn.metrics import classification_report
print 'Accuracy of SVM', lsvc.score(X_test, y_test)
print classification_report(y_test, y_predict, target_names=digits.target_names.astype(str)) | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
监督方法
KNN | from sklearn.datasets import load_iris
iris = load_iris()
iris.data.shape
iris.DESCR
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.25, random_state=33)
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.fit_transform(X_test)
knc = KNeighborsClassifier()
knc.fit(X_train, y_train)
y_predict = knc.predict(X_test)
from sklearn.metrics import classification_report
print 'Accuracy of K-Nearest Neighbor', knc.score(X_test, y_test)
print classification_report(y_test, y_predict, target_names=digits.target_names.astype(str)) | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
K-Means
dataset | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
digits_train = pd.read_csv('optdigits.tra', header=None)
digits_test = pd.read_csv('optdigits.tes', header=None)
X_train = digits_train[np.arange(64)]
y_train = digits_train[64]
X_test = digits_test[np.arange(64)]
y_test = digits_test[64]
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=10)
kmeans.fit(X_train)
y_pred = kmeans.predict(X_test)
from sklearn import metrics
print metrics.adjusted_rand_score(y_test, y_pred) | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
NLTK | sent1 = 'The cat is walking in the bedroom'
sent2 = 'A dog was running across the kitchen.'
from sklearn.feature_extraction.text import CountVectorizer
count_vec = CountVectorizer()
sentences = [sent1, sent2]
print count_vec.fit_transform(sentences).toarray()
print count_vec.get_feature_names()
import nltk
#nltk.download() # download tokenizers/punkt/english.pickle
tokens_l = nltk.word_tokenize(sent1)
print tokens_l | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
Titanic
dataset
Variable Definition Key
survival Survival 0 = No, 1 = Yes
pclass Ticket class 1 = 1st, 2 = 2nd, 3 = 3rd
sex Sex
Age Age in years
sibsp # of siblings / spouses aboard the Titanic
parch # of parents / children aboard the Titanic
ticket Ticket number
fare Passenger fare
cabin Cabin number
embarked Port of Embarkation C = Cherbourg, Q = Queenstown, S = Southampton
Variable Notes
pclass: A proxy for socio-economic status (SES)
1st = Upper
2nd = Middle
3rd = Lower
age: Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5
sibsp: The dataset defines family relations in this way...
Sibling = brother, sister, stepbrother, stepsister
Spouse = husband, wife (mistresses and fiancés were ignored)
parch: The dataset defines family relations in this way...
Parent = mother, father
Child = daughter, son, stepdaughter, stepson
Some children travelled only with a nanny, therefore parch=0 for them. | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
train = pd.read_csv('titanic/train.csv')
#print train.info()
test = pd.read_csv('titanic/test.csv')
#print test.info()
train.isnull().any()
features = ['Pclass','Sex','Age','SibSp','Parch','Embarked','Fare']
X_train = train[features]
X_test = test[features]
X_train['Age'].fillna(train['Age'].mean(), inplace=True)
X_train['Embarked'].fillna('S', inplace=True)
X_test['Age'].fillna(train['Age'].mean(), inplace=True)
X_test['Embarked'].fillna('S', inplace=True)
y_train = train['Survived']
X_train.isnull().any()
X_train.shape
from sklearn.feature_extraction import DictVectorizer
dict_vec = DictVectorizer(sparse=False)
X_train = dict_vec.fit_transform(X_train.to_dict(orient='record'))
print dict_vec.feature_names_
print X_train
X_test = dict_vec.transform(X_test.to_dict(orient='record'))
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier()
from sklearn.cross_validation import cross_val_score
#cross_val_score(rfc, X_train, y_train, cv=5).mean()
cross_val_score(rfc, X_train, y_train, cv=5).mean()
#print test['PassengerId']
rfc.fit(X_train, y_train)
#rfc_submission = pd.DataFrame({'PassengerId':test['PassengerId'], 'Survived':rfc_y_predict})
X_test = X_test.astype(np.int)
# rfc_y_predict = rfc.predict(X_test)
rfc_y_predict = rfc.predict(X_test)
rfc_y_predict
rfc_submisson = pd.DataFrame({'PassengerId': test['PassengerId'], 'Survived': rfc_y_predict})
rfc_submisson.to_csv('rfc_submission.csv', index=False) | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
IMDB
dataset | import pandas as pd
import re
from bs4 import BeautifulSoup
train = pd.read_csv('imdb/labeledTrainData.tsv', header=0,
delimiter="\t", quoting=3)
test = pd.read_csv('imdb/testData.tsv', header=0, delimiter="\t",
quoting=3 )
y_train = train['sentiment']
def review_to_wordlist(review):
'''
Meant for converting each of the IMDB reviews into a list of words.
'''
# First remove the HTML.
review_text = BeautifulSoup(review, "html5lib").get_text()
# Use regular expressions to only include words.
review_text = re.sub("[^a-zA-Z]"," ", review_text)
# Convert words to lower case and split them into separate words.
words = review_text.lower().split()
# Return a list of words
return(words)
print train.head()
traindata = []
for i in xrange(0,len(train['review'])):
traindata.append(" ".join(review_to_wordlist(train['review'][i])))
testdata = []
print test.head()
for i in xrange(0,len(test['review'])):
testdata.append(" ".join(review_to_wordlist(test['review'][i])))
from sklearn.feature_extraction.text import TfidfVectorizer as TFIV
tfv = TFIV(min_df=3, max_features=None,
strip_accents='unicode', analyzer='word',token_pattern=r'\w{1,}',
ngram_range=(1, 2), use_idf=1,smooth_idf=1,sublinear_tf=1,
stop_words = 'english')
X_all = traindata + testdata # Combine both to fit the TFIDF vectorization.
lentrain = len(traindata)
tfv.fit(X_all) # This is the slow part!
X_all = tfv.transform(X_all)
X = X_all[:lentrain] # Separate back into training and test sets.
X_test = X_all[lentrain:]
from sklearn.linear_model import LogisticRegression as LR
from sklearn.grid_search import GridSearchCV
grid_values = {'C':[30]} # Decide which settings you want for the grid search.
model_LR = GridSearchCV(LR(dual = True, random_state = 0),
grid_values, scoring = 'roc_auc', cv = 20)
# Try to set the scoring on what the contest is asking for.
# The contest says scoring is for area under the ROC curve, so use this.
model_LR.fit(X,y_train) # Fit the model.
model_LR.grid_scores_
model_LR.best_estimator_ | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
MNIST | import pandas as pd
train = pd.read_csv('minst/train.csv')
test = pd.read_csv('minst/test.csv')
print train.shape
print test.shape
y_train = train['label']
X_train = train.drop('label', axis=1)
X_test = test
import tensorflow as tf
import tensorlayer as tl
sess = tf.InteractiveSession()
# 准备数据
X_train, y_train, X_val, y_val, X_test, y_test = \
tl.files.load_mnist_dataset(shape=(-1,784))
# 定义 placeholder
x = tf.placeholder(tf.float32, shape=[None, 784], name='x')
y_ = tf.placeholder(tf.int64, shape=[None, ], name='y_')
# 定义模型
network = tl.layers.InputLayer(x, name='input_layer')
network = tl.layers.DropoutLayer(network, keep=0.8, name='drop1')
network = tl.layers.DenseLayer(network, n_units=800,
act = tf.nn.relu, name='relu1')
network = tl.layers.DropoutLayer(network, keep=0.5, name='drop2')
network = tl.layers.DenseLayer(network, n_units=800,
act = tf.nn.relu, name='relu2')
network = tl.layers.DropoutLayer(network, keep=0.5, name='drop3')
network = tl.layers.DenseLayer(network, n_units=10,
act = tf.identity,
name='output_layer')
# 定义损失函数和衡量指标
# tl.cost.cross_entropy 在内部使用 tf.nn.sparse_softmax_cross_entropy_with_logits() 实现 softmax
y = network.outputs
cost = tl.cost.cross_entropy(y, y_, name = 'cost')
correct_prediction = tf.equal(tf.argmax(y, 1), y_)
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
y_op = tf.argmax(tf.nn.softmax(y), 1)
# 定义 optimizer
train_params = network.all_params
train_op = tf.train.AdamOptimizer(learning_rate=0.0001, beta1=0.9, beta2=0.999,
epsilon=1e-08, use_locking=False).minimize(cost, var_list=train_params)
# 初始化 session 中的所有参数
tl.layers.initialize_global_variables(sess)
# 列出模型信息
network.print_params()
network.print_layers()
# 训练模型
tl.utils.fit(sess, network, train_op, cost, X_train, y_train, x, y_,
acc=acc, batch_size=500, n_epoch=500, print_freq=5,
X_val=X_val, y_val=y_val, eval_train=False)
# 评估模型
tl.utils.test(sess, network, acc, X_test, y_test, x, y_, batch_size=None, cost=cost)
# 把模型保存成 .npz 文件
tl.files.save_npz(network.all_params , name='model.npz')
sess.close() | Lesson10.ipynb | shenlanxueyuan/pythoncourse | mit |
Install dependencies
Next, we'll install a GPU build of TensorFlow, so we can use GPU acceleration for training. | # Replace Colab's default TensorFlow install with a more recent
# build that contains the operations that are needed for training
!pip uninstall -y tensorflow tensorflow_estimator
!pip install -q tf-estimator-nightly==1.14.0.dev2019072901 tf-nightly-gpu==1.15.0.dev20190729 | tensorflow/lite/experimental/micro/examples/micro_speech/train_speech_model.ipynb | DavidNorman/tensorflow | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.