Conteo de palabras en Python usando el algortitmo MapReduce#

  • Última modificación: Octubre 20, 2020

Definición del problema#

Se desea contar la frecuencia de ocurrencia de palabras en un conjunto de documentos. Debido a los requerimientos de diseño (gran volúmen de datos y tiempos rápidos de respuesta) se desea implementar una arquitectura Big Data. Se desea implementar la solución en Python.

Algoritmo Map/Reduce#

assets/map-reduce.jpg

Organización de trabajos#

assets/map-reduce-jobs.jpg

Archivos de prueba#

A continuación se generarán tres archivos de prueba para probar el sistema. Puede usar directamente comandos del sistema operativo en el Terminal y el editor de texto pico para crear los archivos.

[1]:
#
# Se crea el directorio de entrada
#
!rm -rf /tmp/wordcount
!mkdir -p /tmp/wordcount/input
%cd /tmp/wordcount
!ls
/tmp/wordcount
input
[2]:
%%writefile input/text0.txt
Analytics is the discovery, interpretation, and communication of meaningful patterns
in data. Especially valuable in areas rich with recorded information, analytics relies
on the simultaneous application of statistics, computer programming and operations research
to quantify performance.

Organizations may apply analytics to business data to describe, predict, and improve business
performance. Specifically, areas within analytics include predictive analytics, prescriptive
analytics, enterprise decision management, descriptive analytics, cognitive analytics, Big
Data Analytics, retail analytics, store assortment and stock-keeping unit optimization,
marketing optimization and marketing mix modeling, web analytics, call analytics, speech
analytics, sales force sizing and optimization, price and promotion modeling, predictive
science, credit risk analysis, and fraud analytics. Since analytics can require extensive
computation (see big data), the algorithms and software used for analytics harness the most
current methods in computer science, statistics, and mathematics.
Writing input/text0.txt
[3]:
%%writefile input/text1.txt
The field of data analysis. Analytics often involves studying past historical data to
research potential trends, to analyze the effects of certain decisions or events, or to
evaluate the performance of a given tool or scenario. The goal of analytics is to improve
the business by gaining knowledge which can be used to make improvements or changes.
Writing input/text1.txt
[4]:
%%writefile input/text2.txt
Data analytics (DA) is the process of examining data sets in order to draw conclusions
about the information they contain, increasingly with the aid of specialized systems
and software. Data analytics technologies and techniques are widely used in commercial
industries to enable organizations to make more-informed business decisions and by
scientists and researchers to verify or disprove scientific models, theories and
hypotheses.
Writing input/text2.txt

Paso 1#

En un sistema Hadoop, se requiere un programa para realizar el mapeo y otro para la reducción que se ejecutan independientemente; Hadoop se encarga de la coordinación entre ellos. El intercambio de información se hace a traves de texto, que es el lenguaje universal para intercambio de información.

Se implementa la función map en Python y se guarda en el archivo mapper.py. Si esta trabajando en el Terminal puede usar el editor pico con pico mapper.py.

[5]:
!which python3
/usr/bin/python3
[6]:
%%writefile mapper.py
#! /usr/bin/ python3

#
# Esta es la funcion que mapea la entrada a parejas (clave, valor)
#
import sys
if __name__ == "__main__":

    #
    # itera sobre cada linea de codigo recibida
    # a traves del flujo de entrada
    #
    for line in sys.stdin:

        #
        # genera las tuplas palabra \tabulador 1
        # ya que es un conteo de palabras
        #
        for word in line.split():

            #
            # escribe al flujo estandar de salida
            #
            sys.stdout.write("{}\t1\n".format(word))
Writing mapper.py

Paso 2#

[7]:
%%writefile app.sh
cat /tmp/wordcount/input/text*.txt \
    | python3 mapper.py \
    | head
Writing app.sh
[8]:
!bash app.sh
Analytics       1
is      1
the     1
discovery,      1
interpretation, 1
and     1
communication   1
of      1
meaningful      1
patterns        1

Paso 3#

Se implementa la función reduce y se salva en el archivo reducer.py.

[9]:
%%writefile reducer.py
#! /usr/bin python3

import sys

#
# Esta funcion reduce los elementos que tienen la misma clave
#
if __name__ == '__main__':

    curkey = None
    total = 0

    #
    # cada linea de texto recibida es una entrada clave \tabulador valor
    #
    for line in sys.stdin:

        key, val = line.split("\t")
        val = int(val)

        if key == curkey:
            #
            # No se ha cambiado de clave. Aca se acumulan los valores para la misma
            # clave.
            #
            total += val
        else:
            #
            # Se cambio de clave. Se reinicia el acumulador.
            #
            if curkey is not None:
                #
                # una vez se han reducido todos los elementos
                # con la misma clave se imprime el resultado en
                # el flujo de salida
                #
                sys.stdout.write("{}\t{}\n".format(curkey, total))

            curkey = key
            total = val

    sys.stdout.write("{}\t{}\n".format(curkey, total))
Writing reducer.py

Paso 4#

Se realiza la prueba de la implementación en el directorio actual antes de realizar la ejecución en el modo pseudo-distribuido. En este caso, se simula el comportamiento de Hadoop mediante la función sort del sistema operativo Linux.

[10]:
%%writefile app.sh
#
# La función sort hace que todos los elementos con
# la misma clave queden en lineas consecutivas.
# Hace el papel del módulo Shuffle & Sort
#
cat /tmp/wordcount/input/text*.txt \
    | python3 /tmp/wordcount/mapper.py \
    | sort \
    | python3 /tmp/reducer.py | head
Overwriting app.sh
[11]:
!bash app.sh
(DA)    1
(see    1
Analytics       2
Analytics,      1
Big     1
Data    3
Especially      1
Organizations   1
Since   1
Specifically,   1