<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Araceli Manzano Chicano on Medium]]></title>
        <description><![CDATA[Stories by Araceli Manzano Chicano on Medium]]></description>
        <link>https://medium.com/@aracelimanzano?source=rss-26e1e63003a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Zw8iL0ZRoQ4yjhPK.jpg</url>
            <title>Stories by Araceli Manzano Chicano on Medium</title>
            <link>https://medium.com/@aracelimanzano?source=rss-26e1e63003a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:39:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aracelimanzano/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introducción a los sistemas de recomendación basados en filtrado colaborativo con PySpark]]></title>
            <link>https://medium.com/datos-y-ciencia/intro-als-pyspark-7de7f3ba3b0a?source=rss-26e1e63003a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de7f3ba3b0a</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[sistemas-de-recomendación]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <dc:creator><![CDATA[Araceli Manzano Chicano]]></dc:creator>
            <pubDate>Tue, 22 May 2018 13:07:32 GMT</pubDate>
            <atom:updated>2018-05-28T14:55:43.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*rdZyNc8--fw3aXCVM5_evQ.jpeg" /></figure><h4>Filtrado colaborativo y sistemas de recomendación con Apache Spark</h4><p>Los sistemas de recomendación son ampliamente utilizados por las plataformas de servicios online y de E-Commerce para solventar, de manera eficaz, el problema de sobreinformación, aportando sugerencias personalizadas a cada usuario de la plataforma, en función de sus intereses y valoraciones, así como de las de usuarios similares.</p><p>Un enfoque trivial en el desarrollo de un sistema de recomendación consistiría en sugerir a todos los usuarios los productos o servicios mejor valorados de la plataforma. Sin embargo, este enfoque no tiene en cuenta los diferentes intereses y perfiles de cada usuario ni rentabiliza aquellos productos menos populares pero con un nicho potencial mucho más específico.</p><p>Las técnicas de <a href="https://es.wikipedia.org/wiki/Filtrado_colaborativo">Filtrado Colaborativo (<em>Collaborative Filtering</em>)</a> obtienen predicciones automáticas (filtrado) sobre los intereses de cada usuario a partir de información de múltiples usuarios (colaborativo). En particular, los algoritmos basados en la factorización implícita de la <em>matriz de interacciones usuarios-ítems</em> permiten desarrollar sistemas de recomendación basados en conjuntos de datos que, en el caso más básico, se componen de usuarios, <em>ítems</em> y valoraciones (<em>ratings</em>) realizadas por los usuarios sobre múltiples<em> ítems</em>. Este caso básico es el que vamos a implementar en este artículo, utilizando la versión distribuida del algoritmo de factorización matricial con regularización, ALS (<em>Alternating Least Squares</em>), que ofrece la librería <a href="https://spark.apache.org/docs/2.2.0/ml-collaborative-filtering.html">MLlib de Apache Spark</a>, teniendo como objetivo clarificar los conceptos fundamentales de este modelo aplicado a la predicción de <em>ratings</em>.</p><h4>Algoritmo ALS (Alternating Least Squares)</h4><p>El algoritmo ALS presenta una alternativa altamente paralelizable para la optimización de la función de coste que implica la factorización de la <em>matriz de interacciones usuarios-ítems </em>con regularización de pesos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*SVgAXmUZjBal1-NXAoB_fA.jpeg" /></figure><p>Esta alternativa se basa en el hecho de que la optimización no convexa que tiene lugar puede abordarse como dos problemas cuadráticos obtenidos fijando, de forma alternativa, los términos <strong><em>p</em></strong><em>u</em> y <strong><em>q</em></strong><em>i</em>, en principio desconocidos. Cuando todos los términos <strong><em>p</em></strong><em>u</em> han sido fijados, el sistema optimiza los términos <strong><em>q</em></strong><em>i</em> por mínimos cuadrados y vice versa [<a href="https://datajobs.com/data-science-repo/Recommender-Systems-%5BNetflix%5D.pdf">Koren, Y., Bell, R., Volinsky, C., 2009</a>].</p><p>La API de <a href="https://spark.apache.org/">Apache Spark</a> para Python, PySpark, en su librería MLlib ofrece una implementación paralelizada del modelo ALS para Filtrado Colaborativo que usaremos en el desarrollo del sistema de recomendación basado en predicción de <em>ratings</em>. Se usará la implementación correspondiente a la API basada en Dataframes de Apache Spark 2.0, la cual optimiza el rendimiento permitiendo trabajar con una abstracción de datos ampliamente conocida en la ciencia de datos, los Dataframes, de manera similar a como se haría utilizando otras librerías de Python como Pandas.</p><p>El flujo de trabajo a seguir, como en cualquier otra aplicación de Machine Learning, es el siguiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*Y7KaUWqxlZ5Hr3qJXnOUjg.jpeg" /></figure><h4>Dataset</h4><p>El dataset utilizado para esta implementación de un sistema de recomendación con PySpark MLlib basada en predicción de ratings es el que se propone en [<a href="https://arxiv.org/abs/cs/0703042)">Brozovsky, L., Petricek, V., 2007</a>] disponible en <a href="http://www.occamslab.com/petricek/data/">http://www.occamslab.com/petricek/data/</a>. Este dataset, tal como se indica en el enlace anterior, consiste en una base de datos con <em>17,359,346 ratings</em> anónimos de <em>168,791 perfiles de usuario</em> realizados por <em>135,359 usuarios</em> de la web de citas <a href="http://www.libimseti.cz/">http://www.libimseti.cz/</a>. Los <em>ratings</em> son valores enteros comprendidos en el intervalo <em>[1, 10]</em>. También se encuentra disponible información sobre el género de algunos perfiles de usuario de la plataforma. De esta forma, el sistema de recomendación que se va a implementar puede describirse como una regresión de valoraciones de perfiles, <em>ratings</em>, que trata de predecir los valores no observados en la <em>matriz de interacciones usuarios-ítems</em>, como aparece en este esquema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*PzJiPtb5vk4XOmFMqFGFQg.png" /></figure><h4>Paso 1: Importar librerías e instanciar una nueva sesión Spark.</h4><pre># Import needed packages<br>from __future__ import absolute_import, print_function, division<br>import numpy as np<br>import pandas as pd<br>import seaborn as sns<br>from pyspark.sql import SparkSession, Row<br>import pyspark.sql.functions as F<br>from pyspark.sql.types import IntegerType, StructType, StructField, StringType<br>from pyspark.ml import Pipeline<br>from pyspark.ml.evaluation import RegressionEvaluator<br>from pyspark.ml.recommendation import ALS<br>from pyspark.ml.tuning import CrossValidator, ParamGridBuilder<br>from pyspark.ml.feature import VectorAssembler</pre><pre># Set Spark Session as entry point<br>spark = SparkSession.builder\<br>       .appName(&quot;Simple recommendation engine using Spark MLlib&quot;)\<br>       .config(&quot;spark.some.config.option&quot;, &quot;config-value&quot;)\<br>       .getOrCreate()\</pre><h4>Paso 2: Cargar el dataset en un dataframe de Spark, limpiar las filas con valores vacíos y normalizar los datos de ratings.</h4><pre># Parse dating agency ratings data as a Spark dataframe<br>ratings = &quot;ratings.dat&quot;<br>schema = StructType([StructField(&quot;user_id&quot;, IntegerType(), False),<br>                     StructField(&quot;profile_id&quot;, IntegerType(), False),<br>                     StructField(&quot;rating&quot;, IntegerType(), True)])<br>ratings_df = spark.read.format(&quot;csv&quot;).option(&quot;header&quot;, &quot;false&quot;).option(&quot;delimiter&quot;, &quot;,&quot;).schema(schema).load(ratings)<br>ratings_df = ratings_df.na.drop(how=&quot;any&quot;)</pre><pre>ratings_df.show(3)<br>ratings_df.printSchema()</pre><pre>------------------------------------------------------------------</pre><pre>+-------+----------+------+<br>|user_id|profile_id|rating|<br>+-------+----------+------+<br>|      1|       133|     8|<br>|      1|       720|     6|<br>|      1|       971|    10|<br>+-------+----------+------+<br>only showing top 3 rows</pre><pre>root<br> |-- user_id: integer (nullable = true)<br> |-- profile_id: integer (nullable = true)<br> |-- rating: integer (nullable = true)</pre><pre>------------------------------------------------------------------</pre><pre># Parse profiles gender data as a Spark dataframe<br>gender_data = &quot;gender.dat&quot;<br>schema = StructType([StructField(&quot;profile_id&quot;, IntegerType(), False),<br>                     StructField(&quot;gender&quot;, StringType(), False)])<br>gender_df = spark.read.format(&quot;csv&quot;).option(&quot;header&quot;, &quot;false&quot;).option(&quot;delimiter&quot;, &quot;,&quot;).schema(schema).load(gender_data)<br>gender_df.show(3)</pre><pre>------------------------------------------------------------------</pre><pre>+----------+------+<br>|profile_id|gender|<br>+----------+------+<br>|         1|     F|<br>|         2|     F|<br>|         3|     U|<br>+----------+------+<br>only showing top 3 rows</pre><pre>------------------------------------------------------------------</pre><pre># Normalize rating column<br>min_rating = 1<br>max_rating = 10<br>ratings_df = ratings_df.withColumn(&#39;norm_rating&#39;, (ratings_df.rating-min_rating)/(max_rating-min_rating))<br>df = ratings_df\<br>     .select(&quot;user_id&quot;,&quot;profile_id&quot;,&quot;norm_rating&quot;)\<br>     .withColumnRenamed(&quot;norm_rating&quot;, &quot;label&quot;)<br>df.show(5)<a href="https://medium.com/p/21f8dc1f43c8/edit">https://medium.com/p/21f8dc1f43c8/edit</a></pre><pre>------------------------------------------------------------------</pre><pre>+-------+----------+------------------+<br>|user_id|profile_id|             label|<br>+-------+----------+------------------+<br>|      1|       133|0.7777777777777778|<br>|      1|       720|0.5555555555555556|<br>|      1|       971|               1.0|<br>|      1|      1095|0.6666666666666666|<br>|      1|      1616|               1.0|<br>+-------+----------+------------------+<br>only showing top 5 rows</pre><h4>Paso 3: Breve análisis descriptivo del dataset.</h4><p>En este paso se realizan algunas consultas simples sobre la base de datos, combinando la información disponible sobre el género de los usuarios de la plataforma y sus distintas valoraciones. Finalmente, se visualiza la distribucion de los datos de <em>ratings</em> para la muestra correspondiente a los <em>10000</em> primeros perfiles almacenados en la base de datos, para lo que será necesario convertir el dataframe de Spark a Pandas <a href="https://medium.com/p/21f8dc1f43c8/edit">https://medium.com/p/21f8dc1f43c8/edit</a>as.</p><pre># Get top 10 most rated profiles (most popular profiles)</pre><pre>top_most_rated_profiles = ratings_df.groupBy(&quot;profile_id&quot;).count().sort(F.col(&quot;count&quot;).desc()).limit(50000)<br>top_most_rated_profiles = top_most_rated_profiles.withColumnRenamed(&quot;profile_id&quot;, &quot;popular_profile_id&quot;)<br>top_most_rated_profiles.show(10)</pre><pre>------------------------------------------------------------------</pre><pre>|popular_profile_id|count|<br>+------------------+-----+<br>|            156148|33389|<br>|             31116|28398|<br>|            193687|23649|<br>|            121859|23639|<br>|             83773|23113|<br>|             22319|21387|<br>|             71636|21284|<br>|             89855|20634|<br>|             20737|18550|<br>|            162707|18224|<br>+------------------+-----+<br>only showing top 10 rows</pre><pre>------------------------------------------------------------------</pre><pre># Get top 10 better rated profiles<br>avg_rating_by_profile = ratings_df.groupBy(&quot;profile_id&quot;).agg(F.avg(&#39;rating&#39;).alias(&#39;avg_rating&#39;)).sort(F.col(&quot;avg_rating&quot;).desc())<br>avg_rating_by_profile.show(10)</pre><pre>------------------------------------------------------------------</pre><pre>+----------+----------+<br>|profile_id|avg_rating|<br>+----------+----------+<br>|    112101|      10.0|<br>|       898|      10.0|<br>|    186236|      10.0|<br>|     36930|      10.0|<br>|     67625|      10.0|<br>|     49914|      10.0|<br>|    159678|      10.0|<br>|    129824|      10.0|<br>|     39488|      10.0|<br>|     66810|      10.0|<br>+----------+----------+<br>only showing top 10 rows</pre><pre>------------------------------------------------------------------</pre><pre># Compute a ration between rating value and popularity</pre><pre>top_profiles = top_most_rated_profiles.join(avg_rating_by_profile, top_most_rated_profiles[&quot;popular_profile_id&quot;] == avg_rating_by_profile[&quot;profile_id&quot;], &quot;left_outer&quot;).drop(&#39;profile_id&#39;).withColumn(&quot;ratio&quot;, F.col(&quot;avg_rating&quot;) / F.col(&quot;count&quot;))</pre><pre># Top profiles sorted by the relation average rating - number of times rated</pre><pre>top_profiles.select(&quot;popular_profile_id&quot;, &quot;ratio&quot;).sort(F.col(&quot;ratio&quot;).desc()).show(5)</pre><pre>------------------------------------------------------------------</pre><pre>+------------------+------------------+<br>|popular_profile_id|             ratio|<br>+------------------+------------------+<br>|            141167|0.1724137931034483|<br>|            214508|0.1724137931034483|<br>|            121533|0.1724137931034483|<br>|            159206|0.1724137931034483|<br>|             78319|0.1724137931034483|<br>+------------------+------------------+<br>only showing top 5 rows</pre><pre>------------------------------------------------------------------</pre><pre># Gender of the most popular profile, avoiding Unknown gender profiles</pre><pre>print(&quot;ID and gender of the most popular profile:&quot;)<br>top_profiles_gender.filter(gender_df.gender != &quot;U&quot;).select(&quot;popular_profile_id&quot;, &quot;gender&quot;, &quot;count&quot;, &quot;avg_rating&quot;).sort(F.col(&quot;count&quot;).desc()).show(1)</pre><pre>------------------------------------------------------------------</pre><pre>ID and gender of the most popular profile:<br>+------------------+------+-----+-----------------+<br>|popular_profile_id|gender|count|       avg_rating|<br>+------------------+------+-----+-----------------+<br>|             31116|     M|28398|7.790583843932671|<br>+------------------+------+-----+-----------------+<br>only showing top 1 row</pre><pre>------------------------------------------------------------------</pre><pre># Gender of the best rated profile</pre><pre>print(&quot;ID and gender of the best rated profile:&quot;)<br>top_profiles_gender.filter(gender_df.gender != &quot;U&quot;).select(&quot;popular_profile_id&quot;, &quot;gender&quot;, &quot;count&quot;, &quot;avg_rating&quot;).sort(F.col(&quot;avg_rating&quot;).desc()).show(1)</pre><pre>------------------------------------------------------------------</pre><pre>ID and gender of the best rated profile:<br>+------------------+------+-----+----------+<br>|popular_profile_id|gender|count|avg_rating|<br>+------------------+------+-----+----------+<br>|             67169|     M|  102|      10.0|<br>+------------------+------+-----+----------+<br>only showing top 1 row</pre><pre>------------------------------------------------------------------</pre><pre># Average rating by gender</pre><pre>avg_rating_by_gender = top_profiles_gender.filter(gender_df.gender != &quot;U&quot;).groupBy(&quot;gender&quot;).agg(F.avg(&#39;avg_rating&#39;).alias(&#39;avg_rating_by_gender&#39;)).sort(F.col(&quot;avg_rating_by_gender&quot;).desc())<br>avg_rating_by_gender.show()</pre><pre>------------------------------------------------------------------</pre><pre>+------+--------------------+<br>|gender|avg_rating_by_gender|<br>+------+--------------------+<br>|     M|     6.1910968513945|<br>|     F|   5.161122966430577|<br>+------+--------------------+</pre><pre>------------------------------------------------------------------</pre><pre># Total rates by gender</pre><pre>total_votes_by_gender = top_profiles_gender.filter(gender_df.gender != &quot;U&quot;).groupBy(&quot;gender&quot;).agg(F.sum(&#39;count&#39;).alias(&#39;total_rates_by_gender&#39;)).sort(F.col(&quot;total_rates_by_gender&quot;).desc())<br>total_votes_by_gender.show()</pre><pre>------------------------------------------------------------------</pre><pre>+------+---------------------+<br>|gender|total_rates_by_gender|<br>+------+---------------------+<br>|     M|              8156451|<br>|     F|              4509053|<br>+------+---------------------+</pre><pre>------------------------------------------------------------------</pre><pre># Convert Spark dataframe to Pandas to plot data distribution<br>pandas_df = df.limit(10000).toPandas()</pre><pre># Ratings distribution for a sample of 10000 users<br>sns.violinplot([pandas_df.label])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*u4c6oeVcb8t7vc-7IVshnQ.png" /></figure><h4>Paso 4: Selección del modelo y ajuste de hiperparámetros.</h4><p>El proceso de selección del modelo se realizará a través del análisis de validación cruzada (<em>cross-validation</em>) con ajuste automático de hiperparámetros. Este ajuste se hace definiendo los posibles valores de los hiperparámetros del modelo y ejecutando una búsqueda en rejilla (<em>grid-search</em>) sobre éstas, para comparar la respuesta de los modelos resultantes y finalmente obtener el óptimo. Los hiperparámetros del modelo ALS son:</p><ul><li><strong><em>rank</em></strong> = la cantidad de factores latentes en el modelo (4, 8 y 12 como valores seleccionados)</li><li><strong><em>maxIter</em></strong> = el número máximo de iteraciones (valor predeterminado)</li><li><strong><em>regParam</em></strong> = el parámetro de regularización (0.1, 0.05 y 0.01 como valores seleccionados)</li></ul><p>El proceso anterior puede implementarse de forma sencilla utilizando la clase de Spark <em>CrossValidator</em>.</p><p>Para realizar una comparativa entre los modelos obtenidos con el proceso anterior se establece como método de evaluación el cálculo del Error cuadrático medio (<em>RMSE</em>) ya que se usa comúnmente como principal métrica de evaluación en problemas de regresión y está disponible en la API de Spark. <em>RMSE</em> compara los valores predichos del conjunto de entrenamiento con los valores reales presentes en el conjunto de validación, al agregar el error absoluto de las diferencias y tomar el promedio de esos valores obtenemos una medida del error del modelo. Cuanto menor es el error, mejor es la capacidad de pronóstico de ese modelo según el criterio <em>RMSE</em>. También se obtendrán otras métricas del error como <em>MSE</em>, <em>R2</em> y <em>MAE</em>.</p><p>Sin embargo, los libros de texto y artículos de investigación en el campo <a href="https://ac.els-cdn.com/S1110866515000341/1-s2.0-S1110866515000341-main.pdf?_tid=c6864687-4a8f-45cb-ad27-d8c0b6ff58cc&amp;acdnat=1526400969_04e6762edfb3fcebebc42652fcf9636f">[F.O. Isinkayea, Y.O. Folajimib, B.A. Ojokohc, 2015</a>] recomiendan usar evaluaciones similares a las de <em>RankMetrics</em> para calcular métricas como la precisión promedio en <em>K</em> o <em>MAP</em>.</p><pre># Split into train and test subsets</pre><pre>(training, test) = df.randomSplit([0.8, 0.2])<br>cv_data = training.withColumnRenamed(&quot;norm_rating&quot;, &quot;label&quot;)</pre><pre># Set model</pre><pre>als = ALS(userCol=&quot;user_id&quot;, itemCol=&quot;profile_id&quot;, ratingCol=&quot;label&quot;, coldStartStrategy=&quot;drop&quot;, seed=0, nonnegative=True)</pre><pre># Set considered parameter grid</pre><pre>paramGrid = ParamGridBuilder().addGrid(als.regParam, [0.1, 0.05, 0.01]).addGrid(als.rank, [4, 8, 12]).build()</pre><pre># Set evaluator</pre><pre>modelEvaluator = RegressionEvaluator(metricName=&quot;rmse&quot;)</pre><pre># Set cross validator instance</pre><pre>crossval = CrossValidator(estimator=als,<br>                          estimatorParamMaps=paramGrid,<br>                          evaluator=modelEvaluator,<br>                          numFolds=10)</pre><pre># Perform cross-validation</pre><pre>cvModel = crossval.fit(cv_data)</pre><pre># Select best model and get its parameters</pre><pre>best_als_model = cvModel.bestModel<br>print(&quot;Best number of latent factors (rank parameter): &quot; + str(best_als_model.rank))<br>print(&quot;Best value of regularization factor: &quot; + str(best_als_model._java_obj.parent().getRegParam()))<br>print(&quot;Max Iterations: &quot; + str(best_als_model._java_obj.parent().getMaxIter()))</pre><pre>------------------------------------------------------------------</pre><pre>Best number of latent factors (rank parameter): 8<br>Best value of regularization factor: 0.01<br>Max Iterations: 10</pre><pre>------------------------------------------------------------------</pre><pre># Make predictions on a random test subset obtained through <br>randomSplit()</pre><pre>print(&quot;Predictions based on a random test subset:&quot;)<br>predictions = best_als_model.transform(test)<br>predictions.show(5)</pre><pre># Evaluate model&#39;s performance on test (evaluate overfitting)</pre><pre>def overfitting_evaluation(predictions):<br>    # Model evaluation in test - ratings regression evaluation<br>    print(&quot;Model evaluation on test data:&quot;)<br>    predictions = predictions.na.drop()<br>    # RMSE<br>    rmse_evaluator = RegressionEvaluator(metricName=&quot;rmse&quot;, labelCol=&quot;label&quot;, predictionCol=&quot;prediction&quot;)<br>    rmse = rmse_evaluator.evaluate(predictions)<br>    print(&quot;Root-mean-square error (RMSE) = &quot; + str(rmse))<br>    # MSE<br>    mse_evaluator = RegressionEvaluator(metricName=&quot;mse&quot;, labelCol=&quot;label&quot;, predictionCol=&quot;prediction&quot;)<br>    mse = mse_evaluator.evaluate(predictions)<br>    print(&quot;Mean-square error (MSE) = &quot; + str(mse))<br>    # R2<br>    r2_evaluator = RegressionEvaluator(metricName=&quot;r2&quot;, labelCol=&quot;label&quot;, predictionCol=&quot;prediction&quot;)<br>    r2 = r2_evaluator.evaluate(predictions)<br>    print(&quot;r² metric = &quot; + str(r2))<br>    # MAE<br>    mae_evaluator = RegressionEvaluator(metricName=&quot;mae&quot;, labelCol=&quot;label&quot;, predictionCol=&quot;prediction&quot;)<br>    mae = mae_evaluator.evaluate(predictions)<br>    print(&quot;Mean Absolute Error (MAE) = &quot; + str(mae))</pre><pre>return [rmse, mse, r2, mae]</pre><pre>random_test_eval = overfitting_evaluation(predictions)</pre><pre>------------------------------------------------------------------</pre><pre>Predictions based on a random test subset:<br>+-------+----------+------------------+----------+<br>|user_id|profile_id|             label|prediction|<br>+-------+----------+------------------+----------+<br>|  83775|       496|0.6666666666666666| 0.5487299|<br>|  83524|       496|               1.0| 0.9750136|<br>|  28584|       833|               1.0| 0.7296401|<br>| 114979|      1238|0.6666666666666666| 0.5668328|<br>|  96625|      1238|0.6666666666666666|0.43366265|<br>+-------+----------+------------------+----------+<br>only showing top 5 rows</pre><pre>Model evaluation on test data:<br>Root-mean-square error (RMSE) = 0.204187073287<br>Mean-square error (MSE) = 0.0416923608976<br>r² metric = 0.650955563635<br>Mean Absolute Error (MAE) = 0.140817836752</pre><p>Para obtener una evaluación más precisa del sobreajuste (<em>overfitting</em>) del modelo y del error real (en test), una buena práctica es, una vez que se ha seleccionado el modelo ALS con el mejor ajuste de hiperparámetros (proceso de selección del modelo, realizado por validación cruzada con búsqueda en rejilla), se evalua el modelo ajustado para distintos conjuntos de entrenamiento y test, seleccionados aleatoriamente a través de múltiples <em>K-fold</em> y, finalmente, se promedian los resultados de las distintas métricas de evaluación calculadas en cada <em>K-fold</em>. Este proceso nos proporcionará una evaluación más precisa de nuestro motor de recomendación como predictor o regresor de <em>ratings</em> ante nuevos datos de entrada nunca antes vistos por el sistema.</p><pre>def kfold_test_eval(df, Kfolds=5):<br>    rmse_evaluations = []<br>    mse_evaluations = []<br>    r2_evaluations = []<br>    mae_evaluations = []<br>    <br>    for k in range(0, Kfolds):  <br>        (train, test) = df.randomSplit([0.8, 0.2])<br>        tunned_als = als = ALS(userCol=&quot;user_id&quot;, itemCol=&quot;profile_id&quot;, ratingCol=&quot;label&quot;, coldStartStrategy=&quot;drop&quot;, maxIter=10, regParam=0.01, rank=8)<br>        model = tunned_als.fit(train)<br>        predictions = model.transform(test)<br>        print(&quot;Kfold: &quot; + str(k + 1))<br>        k_test_eval = overfitting_evaluation(predictions)<br>        rmse_evaluations.append(k_test_eval[0])<br>        mse_evaluations.append(k_test_eval[1])<br>        r2_evaluations.append(k_test_eval[2])<br>        mae_evaluations.append(k_test_eval[3])<br>        <br>    average_rmse = sum(rmse_evaluations)/float(len(rmse_evaluations))<br>    average_mse = sum(mse_evaluations)/float(len(mse_evaluations))<br>    average_r2 = sum(r2_evaluations)/float(len(r2_evaluations))<br>    average_mae = sum(mae_evaluations)/float(len(mae_evaluations))<br>    <br>    return [average_rmse, average_mse, average_r2, average_mae]</pre><pre>[average_rmse, average_mse, average_r2, average_mae] = kfold_test_eval(df)</pre><pre># Average performance score of the selected model:</pre><pre>print(&quot;Average Root-mean-square error (RMSE) = &quot; + str(average_rmse))<br>print(&quot;Average Mean-square error (MSE) = &quot; + str(average_mse))<br>print(&quot;Average r² metric = &quot; + str(average_r2))<br>print(&quot;Average Mean Absolute Error (MAE) &quot; + str(average_mae))</pre><pre>------------------------------------------------------------------</pre><pre>Average Root-mean-square error (RMSE) = 0.203900591499<br>Average Mean-square error (MSE) = 0.0415754551043<br>Average r² metric = 0.652060716195<br>Average Mean Absolute Error (MAE) 0.140639479009</pre><h4>Paso 5: Comprobar las predicciones de ratings que se obtienen del modelo final para distintos casos.</h4><pre># Generate top 10 profiles recommendations for each user</pre><pre>userRecs = ratings_predictor.recommendForAllUsers(10)<br>userRecs.show(1, truncate=False)</pre><pre>+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>|user_id|recommendations                                                                                                                                                                                             |<br>+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>|148    |[[159513, 2.6826572], [135056, 2.2142038], [80297, 2.181056], [199770, 2.0491154], [67442, 1.9784403], [22972, 1.9325198], [128646, 1.9314922], [56050, 1.9247315], [96515, 1.8710849], [179283, 1.8512474]]|<br>+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>only showing top 1 row</pre><pre># Generate top 10 user recommendations for each profile</pre><pre>profileRecs = ratings_predictor.recommendForAllItems(10)<br>profileRecs.show(1, truncate=False)</pre><pre>+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>|profile_id|recommendations                                                                                                                                                                                         |<br>+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>|496       |[[10115, 1.7967153], [36243, 1.6167616], [123794, 1.5479522], [79671, 1.5467885], [38123, 1.5259393], [65649, 1.5140268], [66232, 1.4930097], [20044, 1.4844044], [26508, 1.483938], [61468, 1.4789674]]|<br>+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>only showing top 1 row</pre><pre># Generate top 10 profile recommendations for a set of 10 users</pre><pre>users = test.select(als.getUserCol()).distinct().limit(10)<br>userSubsetRecs = ratings_predictor.recommendForUserSubset(users, 10)<br>userSubsetRecs.show(truncate=False)</pre><pre>+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>|user_id|recommendations                                                                                                                                                                                                |<br>+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>|1580   |[[73450, 2.1160717], [196118, 1.9395694], [44768, 1.861454], [46427, 1.8534217], [62877, 1.800837], [121938, 1.7637302], [35786, 1.7616118], [218717, 1.7597885], [185904, 1.7546182], [114965, 1.7449896]]    |<br>|471    |[[56050, 1.8613569], [169405, 1.6265004], [141912, 1.6238357], [199020, 1.5705091], [153801, 1.5702825], [37519, 1.5582786], [168597, 1.5427593], [117322, 1.5213909], [200918, 1.4999101], [90154, 1.4913626]]|<br>|1591   |[[169405, 1.6842599], [216493, 1.6176178], [7782, 1.5960064], [37519, 1.5920119], [168597, 1.5863789], [56050, 1.5832279], [199020, 1.5650901], [107089, 1.5618131], [200918, 1.5434403], [111214, 1.4910805]] |<br>|1342   |[[49049, 1.8087612], [118858, 1.7899785], [219453, 1.7231553], [117973, 1.7054595], [178022, 1.6659847], [143675, 1.652686], [140886, 1.6521295], [159317, 1.6423284], [203180, 1.6299864], [96216, 1.6189286]]|<br>|463    |[[73450, 2.677851], [162209, 1.9098501], [196962, 1.9062479], [179505, 1.8220359], [197634, 1.8119749], [17567, 1.7738258], [219453, 1.7721505], [105422, 1.761188], [47023, 1.7570614], [23472, 1.7502776]]   |<br>|833    |[[80297, 1.6658962], [178535, 1.6586927], [111214, 1.4727457], [21216, 1.4659634], [167313, 1.4581232], [135056, 1.4345964], [56050, 1.4294059], [169405, 1.4051217], [78721, 1.4015284], [49602, 1.395864]]   |<br>|496    |[[167826, 2.0511458], [209453, 1.9527715], [143675, 1.9430621], [205585, 1.939534], [73450, 1.9388179], [219453, 1.9369094], [185904, 1.9364448], [19635, 1.9134604], [141762, 1.8912288], [140446, 1.8898547]]|<br>|148    |[[159513, 2.6826572], [135056, 2.2142038], [80297, 2.181056], [199770, 2.0491154], [67442, 1.9784403], [22972, 1.9325198], [128646, 1.9314922], [56050, 1.9247315], [96515, 1.8710849], [179283, 1.8512474]]   |<br>|1088   |[[190926, 2.1182022], [159513, 2.0326533], [76186, 1.9888866], [80297, 1.954988], [18218, 1.901816], [21662, 1.8908844], [199770, 1.8749667], [155396, 1.8639369], [84832, 1.8371751], [15377, 1.8299328]]     |<br>|1238   |[[127528, 2.096571], [24639, 1.916371], [169405, 1.8475499], [117787, 1.7302287], [168597, 1.7244738], [144968, 1.6855974], [208922, 1.6755896], [187910, 1<a href="https://medium.com/p/21f8dc1f43c8/edit">https://medium.com/p/21f8dc1f43c8/edit</a>.6324193], [213142, 1.619712], [197550, 1.619522]]  |<br>+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</pre><pre># Generate top 10 user recommendations for a set of 10 profiles</pre><pre>profiles = test.select(als.getItemCol()).distinct().limit(10)<br>profileSubSetRecs = ratings_predictor.recommendForItemSubset(profiles, 10)<br>profileSubSetRecs.show(truncate=False)</pre><pre>+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>|profile_id|recommendations                                                                                                                                                                                                  |<br>+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>|128131    |[[88607, 1.2465376], [40188, 1.2444562], [69236, 1.2178707], [82086, 1.2172562], [42639, 1.2150319], [121684, 1.2045647], [91642, 1.1989311], [10115, 1.1987841], [29150, 1.1812139], [66232, 1.1797979]]        |<br>|87462     |[[26871, 1.207882], [81073, 1.2014818], [83148, 1.1523317], [29112, 1.136605], [91642, 1.1039877], [26544, 1.0997831], [118342, 1.0979117], [51208, 1.0882537], [80161, 1.0850104], [121846, 1.0848624]]         |<br>|205392    |[[112652, 1.241207], [29150, 1.228986], [59406, 1.1866542], [79155, 1.1800299], [29996, 1.1729485], [121684, 1.1671597], [1384, 1.1544853], [87323, 1.1533304], [53778, 1.1521593], [25233, 1.14995]]            |<br>|203894    |[[10115, 0.79588294], [36243, 0.7817952], [121684, 0.73701406], [38123, 0.7342589], [88607, 0.73281974], [66232, 0.72805846], [123794, 0.7247406], [34941, 0.72130567], [90661, 0.7179232], [42247, 0.7051606]]  |<br>|44437     |[[101074, 0.68464667], [89420, 0.67187476], [134780, 0.6624583], [29112, 0.6527287], [57924, 0.6328629], [90124, 0.62214154], [90694, 0.6128592], [56006, 0.6121998], [44795, 0.61183506], [79386, 0.609617]]    |<br>|45307     |[[96042, 0.8553329], [93775, 0.84709346], [28601, 0.84427464], [61468, 0.83761144], [67624, 0.8250998], [92606, 0.81036466], [34956, 0.80686474], [18068, 0.80557084], [118820, 0.799636], [53215, 0.7982516]]   |<br>|58797     |[[106893, 1.7288352], [93775, 1.6686077], [49177, 1.6475681], [117178, 1.6382982], [29377, 1.5988771], [44795, 1.5766393], [28601, 1.5587692], [66989, 1.5518527], [79468, 1.5421674], [71088, 1.5284784]]       |<br>|41988     |[[106893, 1.1461915], [96042, 1.1183972], [47540, 1.1158137], [93775, 1.1020718], [95251, 1.0925175], [59908, 1.0858284], [32548, 1.080138], [61468, 1.0478147], [67624, 1.0465776], [28601, 1.0360357]]         |<br>|104508    |[[25233, 0.86325073], [29150, 0.86161196], [15520, 0.82333964], [92621, 0.8047507], [14712, 0.7958485], [72021, 0.77550006], [89329, 0.7706092], [50241, 0.7615911], [51565, 0.7560502], [14114, 0.7536515]]     |<br>|186039    |[[66218, 0.25599483], [128641, 0.25121227], [13264, 0.23711407], [92621, 0.2368906], [12228, 0.2360465], [67624, 0.23511758], [133021, 0.23419699], [115540, 0.23253503], [5568, 0.23180199], [7188, 0.23102544]]|<br>+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</pre><pre># Generate recommendations for a specific user</pre><pre>def profiles4userID(als_model, uid, limit=10):<br>    data = df.select(&quot;profile_id&quot;).distinct().withColumn(&quot;user_id&quot;, F.lit(uid))<br>    rated_profiles = df.filter(df.user_id == uid).select(&quot;profile_id&quot;, &quot;user_id&quot;)<br>    predictions = als_model.transform(data.subtract(rated_profiles)).dropna().orderBy(&quot;prediction&quot;, ascending=False).limit(limit).select(&quot;profile_id&quot;, &quot;prediction&quot;)<br>    predictions.join(gender_df.filter(gender_df.gender != &quot;U&quot;), predictions.profile_id == gender_df.profile_id).select(predictions.profile_id, gender_df.gender, predictions.prediction).show(1)</pre><pre>gender_df.filter(gender_df.profile_id == &quot;1000&quot;).show()<br>print(&quot;Recommended contact for user 1000:&quot;)<br>profiles4userID(best_als_model, 1000)</pre><pre>------------------------------------------------------------------</pre><pre>+----------+------+<br>|profile_id|gender|<br>+----------+------+<br>|      1000|     M|<br>+----------+------+</pre><pre>Recommended contact for user 1000:<br>+----------+------+----------+<br>|profile_id|gender|prediction|<br>+----------+------+----------+<br>|     13308|     F| 1.4781343|<br>+----------+------+----------+<br>only showing top 1 row</pre><h4>Conclusiones</h4><p>Finalmente, hay que señalar que las predicciones obtenidas a través del algoritmo ALS con retroalimentación implícita disponible en PySpark no son valores normalizados, existiendo incluso la posibilidad de forzar a valores no negativos mediante el argumento del constructor de la clase <em>ALS, nonnegative.</em> Asimismo, pueden aparecer valores<em> NaN </em>tras ejecutar el proceso de validación cruzada, a través de la clase de PySpark <em>CrossValidator</em>, haciendo uso de una métrica de evaluación de regresión (<em>RMSE, MSE, R2, MAE</em>), en el caso en que el subconjunto de datos de validación/test contenga usuarios/<em>ítems</em> no presentes en el subconjunto de datos de entrenamiento, las soluciones se proponen en <a href="https://issues.apache.org/jira/browse/SPARK-14489">SPARK-14489</a> y <a href="https://issues.apache.org/jira/browse/SPARK-19345">SPARK-19345</a>.</p><p><a href="https://flink.apache.org/">Apache Flink</a> también ofrece una implementación del algoritmo <a href="https://ci.apache.org/projects/flink/flink-docs-release-1.4/dev/libs/ml/als.html">ALS</a> para filtrado colaborativo, cuya ejecución haciendo uso de éste y <a href="https://gist.github.com/entaroadun/1653794">otros datasets benchmark</a> sería interesante comparar con la realizada aquí en PySpark, disponible en <a href="https://github.com/aracelimanzanoch/simple-pyspark-recommedation-engine/blob/master/simple-pyspark-recommendation-engine.ipynb"><strong><em>mi repositorio de github</em></strong></a>.</p><p>Aunque el sistema en producción requeriría mayor ajuste, complejidad, versatilidad y eficiencia, debiendo actualizar las predicciones en streaming (a través de un framework como Spark o Flink), espero que este primer acercamiento al Filtrado Colaborativo haya sido de utilidad.</p><p>La implementación del Filtrado Colaborativo a partir de modelos neuronales tales como <a href="https://en.wikipedia.org/wiki/Restricted_Boltzmann_machine"><em>RBM</em> (<em>Restricted Boltzmann Machine</em>)</a> y, especialmente, de aprendizaje profundo como los<a href="https://en.wikipedia.org/wiki/Autoencoder"> <em>Deep Autoencoders</em></a>, de forma escalable y distribuida con Apache Spark, a través de sus extensiones para <a href="https://www.tensorflow.org/">TensorFlow</a> y <a href="https://keras.io/">Keras</a>, es el siguiente paso en esta línea de trabajo.</p><p>Estaré encantada de leer comentarios y preguntas, y de estar en contacto a través de mis perfiles en redes sociales, <a href="https://www.linkedin.com/in/manzanochicanoaraceli/"><strong><em>LinkedIn</em></strong></a> y <a href="https://twitter.com/aracelimanzano"><strong><em>Twitter</em></strong></a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRgLWC5cD5JiG4%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fhorror-movie-chopping-mall-RgLWC5cD5JiG4&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRgLWC5cD5JiG4%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="324" frameborder="0" scrolling="no"><a href="https://medium.com/media/8199e48c00eb6554e6b5418cc6d1d2da/href">https://medium.com/media/8199e48c00eb6554e6b5418cc6d1d2da/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de7f3ba3b0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datos-y-ciencia/intro-als-pyspark-7de7f3ba3b0a">Introducción a los sistemas de recomendación basados en filtrado colaborativo con PySpark</a> was originally published in <a href="https://medium.com/datos-y-ciencia">Ciencia y Datos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>