In [1]:
sc
Out[1]:
In [11]:
# Cargamos el fichero rdd
file_rdd = sc.textFile('/data/titanic/train.csv')
testfile_rdd = sc.textFile('/data/titanic/test.csv')
In [34]:
with open('/data/titanic/README.txt') as readme:
for l in readme:
print l
In [36]:
# Vemos la cabecera con take(1)
file_rdd.take(3)
Out[36]:
In [15]:
# Generamos un nuevo rdd sin la cabecera, primero buscamos la cabecera y
# creamos el rdd de pasajeros por resta
heading = file_rdd.filter(lambda x: 'survived,pclass,' in x)
passengers_rdd = file_rdd.subtract(heading).cache()
In [9]:
# O directamente filtramos la cabecera
passengers_rdd = file_rdd.filter(lambda x: 'survived,pclass,' in x)
Out[9]:
In [20]:
# Contamos cuantos pasajeros hay en el fichero (fichero de train)
# En el titanic, segun yahoo había 2225, de los que fallecieron 1522
passenger_count = passengers_rdd.count()
In [23]:
# Contamos cuantos sobrevivieron
d = passengers_rdd.map(lambda x: (x.split(',')[0], None)).countByKey()
print "Survivors : " + str(d['1']) + ", " + str(round(float(d['1'])/passenger_count, 2))
print "Casualties: " + str(d['0']) + ", " + str(round(float(d['0'])/passenger_count, 2))
In [25]:
# Dibujamos
import matplotlib.pyplot as plt
plt.bar(range(len(d)), d.values(), align='center')
plt.xticks(range(len(d)), d.keys())
plt.show()
In [48]:
def is_number(s):
try:
float(s)
return True
except:
return None
In [53]:
ages = passengers_rdd.filter(lambda x: is_number(x.split(',')[5])).map(lambda x: (float(x.split(',')[5]), None)).countByKey()
In [54]:
# Tenemos un dict agregado
ages
Out[54]:
In [56]:
# Consigamos las edades individuales (no recomendable si el dataset fuese muy grande)
individual_ages = passengers_rdd.filter(lambda x: is_number(x.split(',')[5])).map(lambda x: float(x.split(',')[5])).collect()
In [58]:
plt.hist(individual_ages)
Out[58]:
In [77]:
# Conseguir tasa de supervivencia por genero
def map_supervivencia(line):
gender = line.split(',')[4]
survive = line.split(',')[0]
if survive == '1':
return (gender, (1,0))
else:
return (gender, (0,1))
def reduce_supervivencia(a, b):
return (a[0] + b[0], a[1] + b[1])
supervivencia_genero = passengers_rdd.map(map_supervivencia).reduceByKey(reduce_supervivencia)
In [88]:
surv = supervivencia_genero.collect()
for k in surv:
print k[0] + " survivors: " + str(k[1]) + " (" + str(round(float(k[1][0])/sum(k[1]),2)) + ")"
In [89]:
# Conseguir tasa de supervivencia por clase
def map_supervivencia(line):
clase = line.split(',')[1]
survive = line.split(',')[0]
if survive == '1':
return (clase, (1,0))
else:
return (clase, (0,1))
def reduce_supervivencia(a, b):
return (a[0] + b[0], a[1] + b[1])
supervivencia_clase = passengers_rdd.map(map_supervivencia).reduceByKey(reduce_supervivencia)
In [91]:
surv = sorted(supervivencia_clase.collect())
for k in surv:
print k[0] + " survivors: " + str(k[1]) + " (" + str(round(float(k[1][0])/sum(k[1]),2)) + ")"
In [ ]:
# Mlib