<?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 Jeffery chiang on Medium]]></title>
        <description><![CDATA[Stories by Jeffery chiang on Medium]]></description>
        <link>https://medium.com/@jchiang1225?source=rss-d4f328ac999d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DLXCvvz2NLNar5BN</url>
            <title>Stories by Jeffery chiang on Medium</title>
            <link>https://medium.com/@jchiang1225?source=rss-d4f328ac999d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 07:33:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jchiang1225/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[Apache Iceberg: The Data Engineer’s Secret Weapon for Scalable, Cost-Efficient Analytics]]></title>
            <link>https://jchiang1225.medium.com/apache-iceberg-the-data-engineers-secret-weapon-for-scalable-cost-efficient-analytics-29b1601dc15a?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b1601dc15a</guid>
            <category><![CDATA[lakehouse-architecture]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[icebergs]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Sun, 04 May 2025 14:04:18 GMT</pubDate>
            <atom:updated>2025-05-04T14:04:18.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hZgUmPEaZZsw_Psd" /><figcaption>Photo by <a href="https://unsplash.com/@zekedrone?utm_source=medium&amp;utm_medium=referral">Martin Sanchez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As data engineers, we constantly juggle performance, flexibility, and cost. We’re building pipelines that must be robust enough for production, agile enough to evolve with changing schemas, and optimized enough to avoid blowing through compute budgets.</p><p>If you’re still relying on Hive tables or managing partitions manually in S3, it’s time to meet <strong>Apache Iceberg</strong> — a modern table format purpose-built for the data lake era.</p><p>In this post, we’ll focus on why Iceberg matters for data engineers, especially around:</p><ul><li>Reducing data scanned in queries</li><li>Supporting time travel for reproducibility and recovery</li><li>Enabling safe schema evolution</li><li>Cutting query costs without sacrificing flexibility</li></ul><p>In addition, we will build an example iceberg table and compare with normal external table on Athena.</p><p><strong>DataSet</strong>: <a href="https://cseweb.ucsd.edu/~jmcauley/datasets.html#multi_aspect">https://cseweb.ucsd.edu/~jmcauley/datasets.html#multi_aspect</a></p><h3>Iceberg in a Nutshell</h3><p>Apache Iceberg brings <strong>database-like table management</strong> to cloud object storage. It gives you ACID transactions, scalable metadata, schema tracking, and full compatibility with engines like Spark, Flink, Trino, Presto, Athena, and Snowflake (read-only).</p><p>Unlike Hive tables, Iceberg separates physical storage layout from logical table structure, and stores rich metadata that enables optimization at read time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/0*1-QcpGHJQPifDTox.png" /><figcaption>Figure 1: apache iceberg architecture from <a href="https://www.dremio.com/resources/guides/apache-iceberg-an-architectural-look-under-the-covers/">Link</a></figcaption></figure><p>The metadata layer in Apache Iceberg is the core engine that enables its powerful features like time travel, schema evolution, and efficient query pruning. Instead of scanning the entire dataset, Iceberg maintains a hierarchy of metadata files: <strong>table metadata</strong>, <strong>snapshots</strong>, <strong>manifests</strong>, and <strong>manifest lists</strong>. These files track what data files exist, which columns and partitions they cover, and statistical summaries like min/max values. This allows query engines to skip irrelevant files based on filters, reducing I/O and cost. The metadata is stored in JSON and Avro formats, making it compact, versioned, and fully accessible for auditing or rollback.</p><h3>Query Less, Pay Less</h3><p>we know that in platforms like <strong>Athena</strong> or <strong>BigQuery</strong>, costs scale linearly with data scanned. Iceberg fights this in three major ways:</p><h4>Metadata Filtering (Manifest Pruning)</h4><p>Iceberg stores per-file metadata — like partition values and <strong>column-level stats</strong> (min/max) — in compact <strong>manifest files</strong>. This allows query engines to skip irrelevant files <em>before</em> reading data.</p><pre>-- Only scans files where order_date &gt;= &#39;2024-01-01&#39;<br>SELECT * FROM orders WHERE order_date &gt;= &#39;2024-01-01&#39;;</pre><p>Without Iceberg: full table scan.<br> With Iceberg: manifest filtering → file skipping → less I/O → lower cost.</p><h4>Partition Pruning Without Manual Partition Columns</h4><p>Forget dt=&#39;2024-01-01&#39; in your WHERE clause. Iceberg understands hidden partitions and can still prune data even when you don’t explicitly filter on the partition column.</p><h4>Column Pruning</h4><p>Iceberg works seamlessly with Parquet to read only the necessary columns, reducing disk I/O and memory pressure.</p><h3>Let’s dig in</h3><p>We first need to load the data into S3 bucket and split the data with partitioned by <strong>review_year.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*DY-_3qFgdJiB4KuKXpocfQ.png" /><figcaption>Figure 2: folder of the s3 bucket</figcaption></figure><p>Let’s create the external table and the iceberg table, then we can compare the difference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf2d57d5da40df4c76f8a1d5f17b1aed/href">https://medium.com/media/cf2d57d5da40df4c76f8a1d5f17b1aed/href</a></iframe><p>Next, we need to load data into the iceberg table, which will generate the data into the data layer under the S3 folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f743b5be9eb992953b311a374ce58c9a/href">https://medium.com/media/f743b5be9eb992953b311a374ce58c9a/href</a></iframe><p>Now, we have data in both table, and we can compare the data scanned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*gNLK7_NGssmIw7Xrvcc_hA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*71Vc5Y99aP5-qJHbzbP9dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*cIy5cBqbbG5DBsnX1wDitA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*tlS_IA4WFVWfkFln0leuLw.png" /></figure><p>From the sample, we can actually see how powerful Apache Iceberg is.</p><p><strong>Cost Analysis</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*Ds6U_cG7brDjw7-G.gif" /></figure><ul><li>Iceberg will scan <strong>40–80%</strong> less data when querying.</li><li>Iceberg will add <strong>~10%</strong> extra storage in S3 bucket to store the metadata.</li></ul><h3>Time Travel for Free: Debug, Audit, and Reproduce</h3><p>Another important feature about Iceberg is the time travel mechanism.</p><p>Iceberg gives you <strong>time travel</strong> capabilities out of the box by retaining metadata snapshots. As a data engineer, this means:</p><ul><li>You can roll back tables after a bad write.</li><li>You can let analysts query consistent historical views.</li><li>You can audit changes without relying on complex logging or CDC layers.</li></ul><pre>SELECT * FROM beer_review_iceberg TIMESTAMP AS OF &#39;2025-04-01T10:00:00&#39;;</pre><h3>Schema Evolution</h3><p>Forget brittle Hive schemas. Iceberg supports real, production-grade <strong>schema evolution</strong>, with field-level tracking.</p><p>Supported changes:</p><ul><li>Add/drop columns</li><li>Rename columns (no breaking changes)</li><li>Reorder columns</li><li>Evolve types (if compatible)</li></ul><p>Internally, Iceberg assigns stable <strong>field IDs</strong>, so column name changes don’t corrupt the table or break downstream tools.</p><p>This makes it easier to:</p><ul><li>Avoid data rewrites after minor schema updates</li><li>Decouple producer and consumer teams</li><li>Evolve your model safely over time</li></ul><p><strong>Apache Iceberg</strong> is more than just a table format — it’s a foundational upgrade for any modern data platform. For data engineers, it brings the best of both data lakes and warehouses: reliable schema evolution, safe time travel, and intelligent query pruning that directly translates to lower cloud costs. Whether you’re building batch pipelines, streaming ingestion, or self-serve analytics layers, Iceberg offers the flexibility, scalability, and performance you need without locking you into a specific vendor or engine. If you’re serious about building a future-proof, cost-efficient data stack, Iceberg deserves a top spot in your toolkit.</p><p>Thank you for reading, have a great day!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b1601dc15a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Recommendation with Retrieval Augmented Generation — Part I]]></title>
            <link>https://jchiang1225.medium.com/book-recommendation-with-retrieval-augmented-generation-part-i-d1b415aff558?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1b415aff558</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[recommendations]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Thu, 30 May 2024 04:38:20 GMT</pubDate>
            <atom:updated>2024-05-30T04:38:20.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>Book Recommendation with Retrieval Augmented Generation — Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jpgbZAUWBVHfqoDY" /><figcaption>Photo by <a href="https://unsplash.com/@syinq?utm_source=medium&amp;utm_medium=referral">Susan Q Yin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the ever-evolving landscape of book discovery, traditional recommendation systems often fall short. Large language models (LLMs) offer a promising new approach. By leveraging their ability to process vast amounts of text data, LLMs can delve into the intricacies of different genres, writing styles, and reader preferences. This newfound depth holds the potential to revolutionize book recommendations, leading readers not just to familiar tropes, but to truly personalized literary journeys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TTWE55so56-tL-KH.png" /><figcaption>Figure 1. Retrieval Augmented Generation (Image taken from LangChain <a href="https://python.langchain.com/v0.1/docs/use_cases/question_answering/">https://python.langchain.com/v0.1/docs/use_cases/question_answering</a>)</figcaption></figure><p>One of the exciting advancements in LLM-powered book recommendation systems is the integration of Retrieval-Augmented Generation (RAG). RAG functions as a sophisticated information retrieval tool for the LLM. By efficiently searching vast datasets of book information, RAG identifies titles with similar content and stylistic elements. This retrieved data empowers the LLM to move beyond simple similarity-based recommendations. RAG allows the LLM to grasp the underlying themes and narrative approaches that resonated with the user, enabling it to generate highly personalized suggestions that cater to the user’s specific literary preferences.</p><p>In this post, we are going to demonstrate how to build a simple vector store and retrieve the documents that are semantically relevant.</p><h3>Data Set</h3><p>We will use a dataset from Kaggle</p><p>Source : <a href="https://www.kaggle.com/datasets/ishikajohari/best-books-10k-multi-genre-data/">https://www.kaggle.com/datasets/ishikajohari/best-books-10k-multi-genre-data/</a></p><h3>Setup</h3><p>Vector Store: <strong>FAISS</strong></p><p>Embedding model: <strong>bert-base-uncased</strong> from <strong>Hugging face</strong> — <a href="https://huggingface.co/google-bert/bert-base-uncased">here</a></p><h4>Github Code</h4><p>Link: <a href="https://github.com/chiang9/Medium_blog/tree/main/llm_bookreco">https://github.com/chiang9/Medium_blog/tree/main/llm_bookreco</a></p><h3><strong>Let’s Get Started</strong></h3><p>You will need to first get the API key from Hugging face, which you can find <a href="https://huggingface.co/">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22b7ed77fbbb9c70324e860deb721fa0/href">https://medium.com/media/22b7ed77fbbb9c70324e860deb721fa0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzfZf-6Ne-dcaotZchGCCg.png" /></figure><p>Next we can start creating the vector embedding from the csv file we just created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56f40e309762f46cef8090ac969282f0/href">https://medium.com/media/56f40e309762f46cef8090ac969282f0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3epxg_j8PGOOseh7kvx5w.png" /></figure><p>The embedding process might take a while. In this example, we will only sample the top 1000 documents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6a536b74d7f22a7031bdc1546c51e19/href">https://medium.com/media/a6a536b74d7f22a7031bdc1546c51e19/href</a></iframe><pre>CPU times: total: 58min 47s<br>Wall time: 6min 3s</pre><p>Langchain provides various of different abstraction for data loader and vector store loader. Documentation can be found <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/document_loaders/">here</a>. With Langchain, we will be able to <strong>save, load, merge</strong> the vector embedding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9617179cc937453434f0a5941b3c2a9/href">https://medium.com/media/c9617179cc937453434f0a5941b3c2a9/href</a></iframe><pre>Book: Eleanor &amp; Park<br>Genres: [&#39;Young Adult&#39;, &#39;Romance&#39;, &#39;Contemporary&#39;, &#39;Fiction&#39;, &#39;Realistic Fiction&#39;, &#39;Audiobook&#39;, &#39;Teen&#39;]<br><br>Book: Are You There God? It&#39;s Me, Margaret<br>Genres: [&#39;Young Adult&#39;, &#39;Fiction&#39;, &#39;Childrens&#39;, &#39;Classics&#39;, &#39;Middle Grade&#39;, &#39;Coming Of Age&#39;, &#39;Realistic Fiction&#39;]<br><br>Book: The Paper Bag Princess<br>Genres: [&#39;Picture Books&#39;, &#39;Childrens&#39;, &#39;Fantasy&#39;, &#39;Fiction&#39;, &#39;Dragons&#39;, &#39;Classics&#39;, &#39;Fairy Tales&#39;]<br><br>Book: The Velveteen Rabbit<br>Genres: [&#39;Classics&#39;, &#39;Childrens&#39;, &#39;Fiction&#39;, &#39;Picture Books&#39;, &#39;Fantasy&#39;, &#39;Animals&#39;, &#39;Young Adult&#39;]<br><br>CPU times: total: 578 ms<br>Wall time: 69 ms</pre><h3>NLP Data Preprocessing</h3><p>Performing NLP data cleaning for texts when creating a vector store is generally recommended, but the extent of cleaning depends on your specific use case.</p><ul><li><strong>Improved Vector Representation:</strong> Raw text with inconsistencies like punctuation, special characters, and typos can lead to noisy and inaccurate vector representations. Cleaning helps the model focus on the core meaning of the text.</li><li><strong>Enhanced Similarity Search:</strong> When searching for similar vectors in your store, a cleaner representation allows for more accurate comparisons. Imagine searching for documents about “cooking” — you wouldn’t want results dominated by entries with typos like “coking”.</li><li><strong>Reduced Storage Requirements:</strong> Removing unnecessary elements like stop words (common words like “the” or “a”) can help reduce the size of your vector representations, leading to more efficient storage.</li></ul><p>In this session, we are going to perform some Natural Language Processing (NLP) data preprocessing to the description part, and we can compare the result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77c8c85bb2ef9e6c1533d7a5186a8a4a/href">https://medium.com/media/77c8c85bb2ef9e6c1533d7a5186a8a4a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14439d414783013b9ccacad516ad0a13/href">https://medium.com/media/14439d414783013b9ccacad516ad0a13/href</a></iframe><pre>Average length of description before and after data cleaning<br>956.1368537740602, 915.5401592260405<br>Average length of description before and after preprocessing<br>915.5401592260405, 900.0581477375794</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qskMeEeYS5WHmdmxGbhqg.png" /></figure><p>Next, we perform similar step as what we previously have for the original data to generate the docsearch. We noticed that the embedding processing time is <strong>shorter</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6a66bbd1bda7104d60b2a53a6d3e28f/href">https://medium.com/media/e6a66bbd1bda7104d60b2a53a6d3e28f/href</a></iframe><pre>CPU times: total: 44min 29s<br>Wall time: 4min 35s</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/795cd655c0ebb2cb3f4f2e7960d69314/href">https://medium.com/media/795cd655c0ebb2cb3f4f2e7960d69314/href</a></iframe><pre>Book: Inkheart (Inkworld, #1)<br>Genres: [&#39;Fantasy&#39;, &#39;Young Adult&#39;, &#39;Fiction&#39;, &#39;Middle Grade&#39;, &#39;Childrens&#39;, &#39;Adventure&#39;, &#39;Magic&#39;]<br><br>Book: Artemis Fowl (Artemis Fowl, #1)<br>Genres: [&#39;Fantasy&#39;, &#39;Young Adult&#39;, &#39;Fiction&#39;, &#39;Middle Grade&#39;, &#39;Childrens&#39;, &#39;Science Fiction&#39;, &#39;Adventure&#39;]<br><br>Book: Alexander and the Terrible, Horrible, No Good, Very Bad Day<br>Genres: [&#39;Picture Books&#39;, &#39;Childrens&#39;, &#39;Fiction&#39;, &#39;Classics&#39;, &#39;Realistic Fiction&#39;, &#39;Humor&#39;, &#39;Kids&#39;]<br><br>Book: Are You There God? It&#39;s Me, Margaret<br>Genres: [&#39;Young Adult&#39;, &#39;Fiction&#39;, &#39;Childrens&#39;, &#39;Classics&#39;, &#39;Middle Grade&#39;, &#39;Coming Of Age&#39;, &#39;Realistic Fiction&#39;]<br><br>CPU times: total: 469 ms<br>Wall time: 43 ms</pre><p>Let’s compare the two embedding created from original description and the preprocessed description.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bbca9a1320fb26aa11334d4b5c2636f/href">https://medium.com/media/0bbca9a1320fb26aa11334d4b5c2636f/href</a></iframe><pre>original docsearch: <br>Book: Eleanor &amp; Park<br>Genres: [&#39;Young Adult&#39;, &#39;Romance&#39;, &#39;Contemporary&#39;, &#39;Fiction&#39;, &#39;Realistic Fiction&#39;, &#39;Audiobook&#39;, &#39;Teen&#39;]<br>score = 63.062381744384766<br><br><br>Book: Are You There God? It&#39;s Me, Margaret<br>Genres: [&#39;Young Adult&#39;, &#39;Fiction&#39;, &#39;Childrens&#39;, &#39;Classics&#39;, &#39;Middle Grade&#39;, &#39;Coming Of Age&#39;, &#39;Realistic Fiction&#39;]<br>score = 66.79731750488281<br><br><br>Book: The Paper Bag Princess<br>Genres: [&#39;Picture Books&#39;, &#39;Childrens&#39;, &#39;Fantasy&#39;, &#39;Fiction&#39;, &#39;Dragons&#39;, &#39;Classics&#39;, &#39;Fairy Tales&#39;]<br>score = 67.06227111816406<br><br><br>Book: Looking for Alaska<br>Genres: [&#39;Young Adult&#39;, &#39;Fiction&#39;, &#39;Contemporary&#39;, &#39;Romance&#39;, &#39;Realistic Fiction&#39;, &#39;Coming Of Age&#39;, &#39;Teen&#39;]<br>score = 67.72935485839844<br><br><br>----------------------<br>preprocessed docsearch: <br>Book: Inkheart (Inkworld, #1)<br>Genres: [&#39;Fantasy&#39;, &#39;Young Adult&#39;, &#39;Fiction&#39;, &#39;Middle Grade&#39;, &#39;Childrens&#39;, &#39;Adventure&#39;, &#39;Magic&#39;]<br>score = 65.75355529785156<br><br><br>Book: Charlie and the Chocolate Factory (Charlie Bucket, #1)<br>Genres: [&#39;Childrens&#39;, &#39;Fiction&#39;, &#39;Fantasy&#39;, &#39;Classics&#39;, &#39;Young Adult&#39;, &#39;Middle Grade&#39;, &#39;Humor&#39;]<br>score = 68.92379760742188<br><br><br>Book: The Sea of Monsters (Percy Jackson and the Olympians, #2)<br>Genres: [&#39;Fantasy&#39;, &#39;Young Adult&#39;, &#39;Mythology&#39;, &#39;Fiction&#39;, &#39;Middle Grade&#39;, &#39;Adventure&#39;, &#39;Greek Mythology&#39;]<br>score = 69.14126586914062<br><br><br>Book: The Magician&#39;s Nephew (Chronicles of Narnia, #6)<br>Genres: [&#39;Fantasy&#39;, &#39;Classics&#39;, &#39;Fiction&#39;, &#39;Young Adult&#39;, &#39;Childrens&#39;, &#39;Middle Grade&#39;, &#39;Adventure&#39;]<br>score = 70.03553771972656</pre><h3>Conclusion</h3><p>The document retrieval is an essential component of RAG, and vector store provides the functionality to do the semantic search efficiently. Langchain is a very powerful abstraction tool in helping us build the vector store, retrieve the relevant document and also provides the functionality to communicate with the LLMs.</p><p>Different embedding model and similarity calculation method will give different result. We need to examine the business need to tune the embedding model to find the relevant documents to the given query.</p><p>Next we will communicate with the LLMs to complete the RAG book recommendation.</p><p>Thank you for reading, and have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1b415aff558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Repeating Pattern Enhanced Music Recommendation]]></title>
            <link>https://medium.com/analytics-vidhya/repeating-pattern-enhanced-music-recommendation-b97bed31a1bb?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b97bed31a1bb</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 05:16:30 GMT</pubDate>
            <atom:updated>2024-03-07T05:16:30.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0wS_BiIjz98hLk8r" /><figcaption>Photo by <a href="https://unsplash.com/@sickhews?utm_source=medium&amp;utm_medium=referral">Wes Hicks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever found yourself repeatedly listening to the same song, only to discover later that other music you might enjoy exists? Recommending music that aligns with individual preferences can be a complex task. <br>The current state-of-the-art music recommendation systems primarily focus on the user’s listening history, recommending similar artists and songs based on past preferences. However, this approach can lead to repetitive suggestions and hinder the discovery of truly novel and exciting music.</p><p>This post is to review a recommendation system paper from 2024 on repeating recommendations — <strong>Integrating Repeat Listening Patterns for Enhanced Music Recommendation. </strong>We’ll examine the research methodology, key findings, and the potential implications for the future of music recommendation systems.</p><blockquote><em>Reference:<br></em>R. Shigetomi, H. Nishida, K. -i. Sawai and T. Ushiama, “Integrating Repeat Listening Patterns for Enhanced Music Recommendation,” 2024 18th International Conference on Ubiquitous Information Management and Communication (IMCOM), Kuala Lumpur, Malaysia, 2024, pp. 1–7, doi: 10.1109/IMCOM60618.2024.10418302</blockquote><h3>Background</h3><p>Existing research suggests a consistent cognitive response to repeated stimuli, including music. This response is characterized by an <strong>inverted U-shaped curve</strong> in hedonic value, or the level of pleasure derived from the experience. As depicted in Figure 1, the initial exposure to a stimulus typically elicits a positive response that intensifies with subsequent exposures, reaching a peak of enjoyment. However, continued repetition can lead to a gradual decline in pleasure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*EXWOi1cvi3k6OUQakh2mDA.png" /><figcaption>Figure 1. inverse-U curve of hedonic value by repeat listening (taken from 1)</figcaption></figure><p>People tends to listen to the same music, read the same genre of book, or watch the same tv show over and over again. The repeating pattern can be a key factor in building the recommendation models.</p><p>The authors proposed <strong>Repeat-aware Self-Attention Networks </strong>(ReSANs), which is similar to a model we previously discuss Self-Attention based Sequential Recommendation model (<em>SASRec</em>). Both models employed the self attention mechanism but ReSANs further modify and attention layer and emphasize on the repeating feature.</p><blockquote>SASRec Review: <a href="https://medium.com/analytics-vidhya/self-attention-on-recommendation-system-self-attentive-sequential-recommendation-review-c94796dde001">https://medium.com/analytics-vidhya/self-attention-on-recommendation-system-self-attentive-sequential-recommendation-review-c94796dde001</a></blockquote><h3>Methodology</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*3VdUDOzQ0vf0f17j7MVBrg.png" /><figcaption>Figure 2. Repeat-aware self-attention layer (taken from [1])</figcaption></figure><p>Similar to the sequential recommendation from SASRec, the model takes a user’s recent listening history as input, represented by a sequence of tracks (i_1, i_2, …, i_t) spanning one week. It then attempts to predict the next song (i_t+1) that the user is likely to listen to based on their previous listening patterns within that timeframe.</p><p>While the overall architecture of ReSANs bears a strong resemblance to the existing SASRec model [2], it introduces key modifications in the <strong>embedding and self-attention layers</strong>, the heart of the model. Unlike SASRec, ReSANs place a specific emphasis on capturing <strong>repetition patterns</strong> in listening behavior. To achieve this, they introduce a <strong>repetition layer (RE) </strong>and <strong>positional embedding layer</strong> (PE) that enriches the representation of user and music items during the process of combining query and key elements within the self-attention mechanism. These modifications aim to improve the model’s ability to understand and leverage the nuances of user listening patterns, specifically those related to repeated listening behavior.</p><h4>Data Preprocessing</h4><p>The researchers used a dataset containing music listening history from <strong>Last.fm</strong> between January 1st, 2020 and March 20th, 2020. They filtered the data to ensure user and track diversity by removing outliers and only keeping users who interacted with a significant number of tracks and tracks with a decent number of listener interactions. Additionally, the authors defined listening sessions based on time intervals and excluded sessions with too few or too many songs. Finally, the data is aggregated into weekly listening sets for each user to be used as input for their model.</p><h4><strong>Embedding Layer</strong></h4><p>The study utilized an embedding layer similar to SASRec. This layer processes the user’s one-week listening history, capturing the inherent features and patterns. However, their approach introduced key advancement:</p><ul><li><strong>Repeat embedding:</strong> This captures the frequency of each track was listened to within the week.</li><li><strong>Positional embedding:</strong> This considers the order in which tracks were listened to within the week.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*7rVWVK3EZes99CWstR7mFw.png" /><figcaption>Figure 3. formula of comprehensive repeat embedding (taken from [1])</figcaption></figure><p>These embeddings are then combined to create a <strong>comprehensive repeat embedding</strong> that considers both how many times a track was listened to and the order in which it was listened to. This enriched representation is then used as input for the next layer of the model.</p><h4>Repeat-aware Self-Attention Layer</h4><p>The <strong>Repeat-aware Self-Attention Layer</strong> is the key advancement of the proposed model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*myZbjcIWZWy7O61dpgVF2w.png" /><figcaption>Figure 4. Repeat-aware self attention (taken from [1])</figcaption></figure><p>Unlike traditional methods, this layer considers both the content of the tracks (from IE) and the <strong>repetition count</strong> (from RE_hat) when calculating attention scores. These scores determine how relevant one track is to another within the sequence. The key idea is that the model considers <strong>how many times</strong> a user has listened to a track (i) when evaluating its connection to another track (j).</p><p>Imagine two songs, i and j. Their connection is calculated differently based on how many times song i was listened to: a single listen might lead to a stronger connection with j compared to ten listens. This dynamic approach ensures recommendations that are more responsive to user listening habits. Additionally, the model doesn’t solely prioritize songs with the strongest contextual fit. It considers factors like a user frequently listening to a particular song (i) and might even recommend a different song (j) instead, showcasing a more nuanced understanding of user preferences.</p><h4>Feed Forward Network and Stacking Self-Attention Blocks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*2vcKk6jRYdYIgGL6wEhr4g.png" /><figcaption>Figure 5. FFN layer (taken from [1])</figcaption></figure><p>The authors proposed to stacked the self-attention blocks and add the feed forward network to output to the next stage. This layer adds non-linearity to the model, and followed by the normalization and dropout layer to regularize the output.</p><h3>Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*A5ba0PjlyokVghrnY3ZQwg.png" /><figcaption>Table 1. Model Comparison (taken from [1])</figcaption></figure><p>To evaluate the effectiveness of their proposed model, the authors compared ReSANs with three other models. All four models utilized the <strong>self-attention mechanism</strong> to recommend music tracks based on user listening sequences. This allows for a direct comparison of how each model leverages this technique for recommendation purposes.</p><ul><li><strong>SASRec:</strong> This is the foundation for many sequential recommendation systems, including ReSANs. It excels at capturing the order in which users listen to music.</li><li><strong>SASRec+R:</strong> This builds upon SASRec by incorporating <strong>repeat information</strong>. Similar to how position matters, this model considers how many times a user listens to a specific track, potentially leading to more accurate recommendations.</li><li><strong>LightSANs:</strong> This model also builds on SASRec but uses a <strong>reduced dimensional space</strong> to represent user interests. This allows the model to learn item-interest interactions more efficiently while maintaining good performance.</li></ul><p>The results presented in Table 1 reveal a significant improvement in music recommendation performance achieved by ReSANs. Compared to the other models, ReSANs demonstrated a remarkable <strong>performance increase of 30–40%</strong>, highlighting its effectiveness in capturing the nuances of user listening behavior through its innovative consideration of repeat listening patterns.</p><h3>Final Words</h3><p>We see that ReSANs outperformed a lot of previous sequential recommendation models on music recommendation. This success suggests that incorporating repetition patterns into recommender systems has broader potential. Similar models could be developed for other applications, like book recommendations, taking into account our tendency to revisit preferred items. This opens doors for building more personalized and engaging recommender systems across various domains.</p><p>Thank you for reading, and have a nice day!</p><h3>Reference</h3><ol><li>R. Shigetomi, H. Nishida, K. -i. Sawai and T. Ushiama, “Integrating Repeat Listening Patterns for Enhanced Music Recommendation,” 2024 18th International Conference on Ubiquitous Information Management and Communication (IMCOM), Kuala Lumpur, Malaysia, 2024, pp. 1–7, doi: 10.1109/IMCOM60618.2024.10418302</li><li>Kang, Wang-Cheng and McAuley, Julian, “Self-Attentive Sequential Recommendation”, in arXiv, 2018, <a href="https://doi.org/10.48550/arxiv.1808.09781">https://doi.org/10.48550/arxiv.1808.09781</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b97bed31a1bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/repeating-pattern-enhanced-music-recommendation-b97bed31a1bb">Repeating Pattern Enhanced Music Recommendation</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self Attention on Recommendation System — Self-Attentive Sequential Recommendation Review]]></title>
            <link>https://medium.com/analytics-vidhya/self-attention-on-recommendation-system-self-attentive-sequential-recommendation-review-c94796dde001?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94796dde001</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[literature-review]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 23:02:46 GMT</pubDate>
            <atom:updated>2024-02-16T23:02:46.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Self Attention on Recommendation System — Self-Attentive Sequential Recommendation Review</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CMgE_gpsXWvIV3qH" /><figcaption>Photo by <a href="https://unsplash.com/@tamara_photography?utm_source=medium&amp;utm_medium=referral">Tamara Gak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recommendation systems are powerful tools used in many industries, analyzing how people interact with items to predict their preferences. One common method, Collaborative Filtering, looks at user-item interactions to score items. However, the order in which users rate items matters! Understanding this hidden pattern helps us build better recommendation systems that deliver personalized suggestions across different fields.</p><p>This post is to review of “<strong><em>Self-Attentive Sequential Recommendation</em></strong>”. Even though this is a article from 2018, directly applying attention mechanism on the user context in recommendation system is an interesting approach.</p><blockquote>Reference:<br> Kang, Wang-Cheng and McAuley, Julian, “Self-Attentive Sequential Recommendation”, in arXiv, 2018, <a href="https://doi.org/10.48550/arxiv.1808.09781">https://doi.org/10.48550/arxiv.1808.09781</a></blockquote><h3>Background</h3><p>Recommendation systems usually rely on users’ recent activities as a basis for prediction. However, traditional collaborative filtering models struggle to capture intricate action patterns effectively. Unveiling these patterns holds the key to enhancing our recommendation systems. Similar to natural language processing (NLP) and image processing, every detail within the data influences the subsequent prediction or data points. Markov Chain and Recurrent Neural Network methodologies have emerged as effective tools in processing such data, enabling us to extract valuable insights and refine our recommendation algorithms for better user experiences.</p><p>In the study, the author proposed the Self-Attention based Sequential Recommendation model (<em>SASRec</em>), where the self-attention block tends to capture sequential information where the user made in each time step as shown in figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*LsyfN8h1rnbIAAi_FHUPMg.png" /><figcaption>Figure 1: Simplified diagram of SASRec (taken from [1])</figcaption></figure><h3>Methodology</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*Ilg8osqdt7kOK3rRP86PgA.png" /><figcaption>Figure 2: Simple diagram of SASRec</figcaption></figure><h4>Data Preprocessing</h4><p>In order to process the sequential user-item interaction data, the study is transforming the data into a time series like data, e.g.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*e1wltvZSc6Ew7eXusHryNw.png" /></figure><p>where <em>S</em> is the historical interaction sequence for a user <em>u</em>.</p><p>The model will use series from 1 to t-1 to predict the shifted data of 2 to t during the training process.</p><h4>Embedding Layer</h4><p>In the dataset, users vary in the length of their item interaction history, however, the data input dimension need to be uniform before passing in the model. The embedding layer in SASRec addresses this by ensuring consistency in the length of user-item interaction sequences. It achieves this by padding zeros to adjust dimensions, facilitating seamless processing within the model.</p><p>The author also attempted to incorporate a learnable positional embedding by concatenating it with this embedding layer, but the performance didn’t go as expected.</p><h4>Attention Mechanisms</h4><p>Self-attention is a powerful mechanism used in deep learning to process sequential data, such as sentences or time-series data, by considering the relationship between different elements within the sequence. Unlike traditional attention mechanisms that focus on aligning different parts of the input sequence, self-attention allows each element to attend to all other elements, capturing long-range dependencies effectively. By assigning different weights to different elements based on their relevance to each other, self-attention enables the model to dynamically weigh the importance of each element in generating context-aware representations. This flexible and adaptive mechanism has gained widespread popularity in natural language processing tasks, where understanding the contextual relationships between words is crucial for tasks like translation and summarization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*5q4Numtf63Rkw6TaJLVRaw.png" /></figure><p>where <br>Q refers to the queries<br>K refers to the keys<br>V refers to the values<br>square root d is used to scale and avoid having large value from the inner product</p><p>the attention layer computes a weighted total of all values, in which the weight for a given query i and the value j corresponds to the connection between query i and key j.</p><h4>Point-Wise Feed-Forward Network</h4><p>The attention output from the multi-head layer is passed through this network, transforming it into a higher-dimensional representation. This layer adds non-linearity to the model, and followed by the normalization and dropout layer to regularize the output.</p><h4>Prediction Layer</h4><p>The prediction layer in the SASRec model acts as a dual-purpose unit. During training, it calculates the loss function, guiding the model’s learning by comparing the predicted relevance (dot product with sequence representation) of positive and negative items to their actual relevance. This difference is fed into a loss function like binary cross-entropy, prompting the model to adjust its parameters and improve its ability to distinguish relevant items. During testing, the prediction layer takes the test item’s embedding, calculates its dot product with the sequence representation, and uses the resulting score to assess its relevance to the user’s preferences. This score directly influences the recommendation output, suggesting items with the highest scores as the most likely to interest the user.</p><h3>Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*Ly-ld9BOMBig8H_o5_O6gg.png" /><figcaption>Table 1: Recommendation Model comparison (taken from [1])</figcaption></figure><p>The author presents a comparison of the SASRec model with 8 other recommendation models, evaluating their performance on 4 datasets. The results suggest potential advantages of the SASRec approach.</p><h3>Final words</h3><p>Prioritizing its publication year and impact, the SASRec model is acknowledged for its pioneering use of self-attention in recommendation systems. With over 1500 citations, it serves as a prominent reference point for subsequent research.</p><p>Thank you for reading, and have a nice day!</p><h3>Reference</h3><ol><li>Kang, Wang-Cheng and McAuley, Julian, “Self-Attentive Sequential Recommendation”, in arXiv, 2018, <a href="https://doi.org/10.48550/arxiv.1808.09781">https://doi.org/10.48550/arxiv.1808.09781</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94796dde001" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/self-attention-on-recommendation-system-self-attentive-sequential-recommendation-review-c94796dde001">Self Attention on Recommendation System — Self-Attentive Sequential Recommendation Review</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommender System Literature Review 2019–2023]]></title>
            <link>https://medium.com/analytics-vidhya/recommender-system-literature-review-2019-2023-2b481bd39c0c?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b481bd39c0c</guid>
            <category><![CDATA[literature]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 00:20:33 GMT</pubDate>
            <atom:updated>2024-02-05T00:20:33.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SSDqJ_0nwjmDZ9Ho" /><figcaption>Photo by <a href="https://unsplash.com/@impatrickt?utm_source=medium&amp;utm_medium=referral">Patrick Tomasso</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the ever-expanding realm of digital information, recommendation systems have become the unsung heroes that guide us through the vast seas of content. Whether it’s suggesting our next favorite movie, helping us discover a new book, or recommending products tailored to our preferences, these systems play a pivotal role in shaping our online experiences.</p><p>This post is to share a summarization of a literature review I recently read on the recommender system. The author strictly select the recent research from 2019 to 2023 which focusing on novel approaches, evaluation techniques and common problems we might face in building the recommender system.</p><blockquote>Reference: <br>I. Saifudin and T. Widiyaningtyas, “Systematic Literature Review on Recommender System: Approach, Problem, Evaluation Techniques, Datasets,” in IEEE Access, doi: 10.1109/ACCESS.2024.3359274.</blockquote><h3>Background</h3><p>The paper select 72 researches which focus on different approaches, where Collaborative Filtering (CF) was the major approach and used in 46 studies, Content-Based Filtering (CBF) and Hybrid Filtering (HBF) were used in 11 and 15 studies respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*6FjmBwNnW0TU3p9NRGDxdA.png" /><figcaption>Figure 1: Distribution of References by Year (taken from [1])</figcaption></figure><p>The following four research questions served as the foundational framework for the entire literature review (1):</p><ul><li><strong><em>What approach is suitable for solving problems in recommender systems?</em></strong></li><li><strong><em>What problems arise in solving problems in recommender systems?</em></strong></li><li><strong><em>What evaluation techniques are suitable for solving problems in recommender systems?</em></strong></li><li><strong><em>What datasets are currently popular for research in recommender system?</em></strong></li></ul><h3>Approach</h3><p>The study separate the recommender system built by the 72 researches into 3 major category — Content Based Filtering (CBF), Collaborative Filtering (CF) and Hybrid Filtering (HBF). The author emphasized three associated studies for each approach, and I will only delve into one from each category.</p><h4><strong>Content Based Filtering</strong></h4><p>The Content-Based Filtering (CBF) technique leverages product descriptions and user profiles, conducting product characteristics analysis to generate recommendations. User profiles are shaped by both interaction history and individual preferences. CBF research spans diverse domains like movies and tourist attractions, utilizing a similarity metric in vector space to calculate item similarity for precise recommendations. While CBF stands out for its flexibility, not relying on additional user information, it demands domain expertise for optimal results.</p><p>CBF’s reliance on product features and user profiles, coupled with its independence from changing user information, underscores its flexibility compared to other methods. However, this approach comes with the caveat of requiring domain-specific skills to achieve optimal performance, showcasing the dual nature of advantages and challenges within the realm of CBF research.</p><p>In the study “Movie Popularity and Target Audience Prediction Using the Content-Based Recommender System”, S. Sahu et al. (2) proposed a multiclass CNN movie recommendation model. There are three major components in the proposed model.</p><ol><li>Content-based recommendation model</li><li>Movie hit prediction model</li><li>Audience targeting model</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*gIJMO76PWruLlCT0khzszg.png" /><figcaption>Figure 2: Content-based recommendation model (taken from [2])</figcaption></figure><p>The first module will preprocess the data and create a multi-dimensional KNN cluster based on the movie meta data and cosine similarity. The result will be passed into the second module to predict movie rating using 1D-CNN module. The audience targeting model will generate recommendations based on the user age group and biography.</p><p>Utilizing a multiclass classification model, researchers have attained an impressive accuracy of <strong>96.8%</strong>, surpassing benchmarks and emphasizing the capabilities of predictive and prescriptive data analysis in bolstering industrial decisions within information systems. Nonetheless, the literature reviewer acknowledges certain limitations of the model, particularly the necessity for an expert system to predict a movie’s probability of success with reasonable accuracy, a requirement recognized by both moviemakers and researchers in the field.</p><blockquote>Reference:<br>S. Sahu, R. Kumar, M. S. Pathan, J. Shafi, Y. Kumar, and M. F. Ijaz, “Movie Popularity and Target Audience Prediction Using the Content-Based Recommender System,” IEEE Access, vol. 10, pp. 42030–42046, 2022, doi: 10.1109/ACCESS.2022.3168161.</blockquote><h4>Collaborative Filtering</h4><p>Different from Content based filtering approach, Collaborative Filtering (CF) approach utilize the utility matrix based on the user to item interaction to estimate the user preference, and the item profile is necessary required. Within collaborative filtering, the collective input of all users is considered, identifying individuals with comparable tastes to suggest new and tailored products to the main customer. This approach is assuming people with similar item interaction will have similar taste.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrPuYc_ZG5norl0cxExFyQ.png" /><figcaption>Figure 4: similar profile user will be used to predict the result</figcaption></figure><p>CF is a powerful approach in recommender system, however, this approach often suffer from the challenge of execution time and scalability. Matrix decomposition algorithm becomes essential in this method. T. Widiyaningtyas et al. (3) is able to process the MovieLens 100k dataset within 13.502 second by utilizing the SVD-WPR approach they proposed.</p><p>The study integrated the Singular Value Decomposition (SVD) method to predict unrated items from the user-item utility matrix. To optimize the time complexity, the rating aggregation method, Weighted Point Rating (WPR), is utilized to obtain the recommendation items.</p><p>WPR process consists of four steps:</p><ol><li>Calculating the equal rating items</li><li>Calculating item points</li><li>Calculating weight points</li><li>Calculating weight points rating</li></ol><p>The rating aggregation method is brilliant and very effective, however, we are not going into the math formula detail at the moment.</p><blockquote>Reference:<br>T. Widiyaningtyas, M. I. Ardiansyah, and T. B. Adji, “Recommendation Algorithm Using SVD and Weight Point Rank (SVD-WPR),” Big Data and Cognitive Computing, vol. 6, no. 4, 2022, doi: 10.3390/bdcc6040121.</blockquote><h4>Hybrid Filtering</h4><p>Unlike singular methods such as Content-Based or Collaborative Filtering, Hybrid Filtering leverages a combination of approaches, often incorporating both user-item interactions and item characteristics. H. Tahmasebi et al. (4) implemented the recommender system based on autoencoder neural network.</p><p>In the research, deep learning models in recommender systems are categorized into two main types: neural network models and deep hybrid models. The former includes diverse architectures such as multilayer perceptron (MLP), autoencoder (AE), convolutional neural network (CNN), recurrent neural network (RNN), restricted Boltzmann machine (RBM), neural autoregressive distribution estimation (NADEs), attentional model (AM), adversarial network (AN), and deep reinforcement learning (DRL). On the other hand, hybrid models combine two or more deep learning techniques, utilizing the flexibility of deep neural networks to create a more robust recommendation system. The range of options showcases the adaptability and versatility of deploying deep learning in recommender systems.</p><p>The study indicates that the autoencoder network recommender system is able to maintain high accuracy and labeled data is not required. These networks excel at automatically extracting valuable features from the data they process. By reconstructing data and diminishing data dimensions through learned relations, autoencoders prove to be efficient in uncovering meaningful patterns and representations without the need for explicit labeling.</p><p>The author proposed an autoencoder neural network approach — SRDNet (Social Recommender Deep Autoencoder Network), which consists of two recommender engine, collaborative filtering and content based filtering. The model gathers data from MovieTweetings, Twitter and IMDB to built social influence item profile based on movie detail, number of tweets, number of retweets and number of likes.</p><p>The user-movie utility matrix is constructed using the social influence score. Therefore, user ratings and interests with a higher social influence result in a more substantial impact on the training process of the deep autoencoder network. The autoencoder is mainly used in the CF module and the final recommendation result is calculated based on addition of different ratio of the collaborative filtering and content based filtering modules.</p><blockquote>Reference:<br>H. Tahmasebi, R. Ravanmehr, and R. Mohamadrezaei, “Social movie recommender system based on deep autoencoder network using Twitter data,” Neural Comput Appl, vol. 33, no. 5, pp. 1607–1623, 2021, doi: 10.1007/s00521–020–05085–1.</blockquote><h3>Problem</h3><p>The author addressed 5 major problems which the researches faced.</p><ul><li>Accuracy</li><li>Sparsity</li><li>Cold Start</li><li>Running Time</li><li>Scalability</li></ul><p>The findings from the research highlight several crucial challenges in building recommendation systems. The Cold Start Problem represents a significant hurdle, where the system lacks sufficient information about a new user or item, degrading overall performance. The Sparsity Problem arises due to limited user assessments, leading to sparse matrices, difficulty finding resemblances, and weak recommendations. Scalability becomes a concern as regular computing grows linearly with users and items, impacting the system’s ability to produce satisfactory recommendations with an increased dataset. To address this, dimension reduction techniques like Singular Value Decomposition (SVD) are proposed. The Running Time Problem emphasizes the need for algorithmic improvements to enhance the speed of recommendations, and finally, the Accuracy Problem is a recurring challenge. The majority of issues lie in Collaborative Filtering, followed by Content-Based Filtering and Hybrid Filtering, with ongoing efforts to enhance accuracy through diverse research methods. The study underscores the dynamic nature of recommendation system research, where addressing these challenges is an ongoing pursuit for perfection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*0VFFfxvhv-xSDLdOlpud1Q.png" /><figcaption>Figure 5: Distribution of problem found in studies (taken from [1])</figcaption></figure><h3>Evaluation Method</h3><p>The recommender system is a complex system which can involve a lot of different approaches, dataset and contextual information for the user’s profile or item details, however, the recommendation result is based on the user preference and there is no absolute answer in practice. Evaluation methods become an essential question to all recommendation researches.</p><blockquote>Based on the research, the majority of the researches are using <strong>RMSE </strong>and <strong>MAE</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*HcQU-mKTkX228dlWSXFhig.png" /><figcaption>Figure 6: Distribution of Evaluation Methods (taken from [1])</figcaption></figure><p>Probability theory offers a logical resolution to the choice between RMSE and MAE, with one of these metrics proving optimal when applied correctly, although practical scenarios may necessitate the use of multiple metrics. Enhancements in model refinement, data transformation, the adoption of robust statistics, or the construction of improved probabilities can enhance results in specific cases, with the latter being the most versatile option, albeit pragmatic considerations may favor other approaches. Additionally, it is highlighted that RMSE is optimal for normally distributed errors, countering the misconception that MAE is exclusive to uniformly distributed errors. Despite MAE’s greater power, there are superior alternatives, and both metrics lack theoretical justification and fail to introduce the extensive literature on the subject.</p><h3>Dataset</h3><p>Recommendation systems are often tailored to specific problems, for example, book, music or even stock recommendation. Various datasets sometimes contain distinct contextual information, the recommendation system is not generic to all problems most of the time.</p><p>Among 72 researches in the literature review, 44 of the studies are using the Movielens dataset.</p><h3>Final words</h3><p>The author highlighted a lot of recommender system studies, many of them proposed novel approaches, however, accuracy is still the major concern across the recommender system researches.</p><p>Thank you for reading, and have a nice day!<br>Please let me know if there is acknowledgement concern in the post.</p><h3>Reference</h3><ol><li>I. Saifudin and T. Widiyaningtyas, “Systematic Literature Review on Recommender System: Approach, Problem, Evaluation Techniques, Datasets,” in IEEE Access, doi: 10.1109/ACCESS.2024.3359274.</li><li>S. Sahu, R. Kumar, M. S. Pathan, J. Shafi, Y. Kumar, and M. F. Ijaz, “Movie Popularity and Target Audience Prediction Using the Content-Based Recommender System,” IEEE Access, vol. 10, pp. 42030–42046, 2022, doi: 10.1109/ACCESS.2022.3168161.</li><li>T. Widiyaningtyas, M. I. Ardiansyah, and T. B. Adji, “Recommendation Algorithm Using SVD and Weight Point Rank (SVD-WPR),” Big Data and Cognitive Computing, vol. 6, no. 4, 2022, doi: 10.3390/bdcc6040121.</li><li>H. Tahmasebi, R. Ravanmehr, and R. Mohamadrezaei, “Social movie recommender system based on deep autoencoder network using Twitter data,” Neural Comput Appl, vol. 33, no. 5, pp. 1607–1623, 2021, doi: 10.1007/s00521–020–05085–1.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b481bd39c0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/recommender-system-literature-review-2019-2023-2b481bd39c0c">Recommender System Literature Review 2019–2023</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to ETL and GCP basic]]></title>
            <link>https://jchiang1225.medium.com/introduction-to-etl-and-gcp-basic-80f26a677669?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/80f26a677669</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 01:44:29 GMT</pubDate>
            <atom:updated>2023-06-09T01:44:29.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSw9dknxpAdrNUa6" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@uxindo?utm_source=medium&amp;utm_medium=referral">UX Indonesia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s data-driven world, organizations are continuously grappling with massive amounts of information scattered across multiple systems. Extracting valuable insights from such diverse data sources can be a daunting task. This is where ETL (Extract, Transform, Load) comes to the rescue. ETL serves as the backbone of data integration, offering a robust framework for extracting, transforming, and loading data into a consolidated and actionable format. In this blog post, we delve into the world of ETL and how can we integrate the Google Cloud Platform services to do the data ingestion.</p><h3>So, What is ETL?</h3><p>ETL stands for <strong>Extract, Transform, Load</strong>. It refers to a process in data management and data integration that involves extracting data from various sources, transforming it into a desired format or structure, and loading it into a target system or data repository for analysis, reporting, or other purposes.</p><ul><li><strong>Extract</strong>: Data is extracted from multiple sources, such as databases, files, APIs, or external systems. The extraction process involves connecting to the source systems, identifying the data to be extracted, and retrieving it. The extracted data can be from structured, semi-structured, or unstructured sources.</li><li><strong>Transform</strong>: Once the data is extracted, it undergoes a series of transformations to convert it into a consistent format, standardize values, clean and validate the data, and apply any necessary calculations or business rules. Transformations can include filtering, aggregating, sorting, joining, or applying complex algorithms to the data. The goal is to prepare the data for analysis or loading into the target system.</li><li><strong>Load</strong>: Transformed data is loaded into a target system or data repository, such as a data warehouse, data mart, or database. The loading process involves mapping the transformed data to the target schema and structure, applying any necessary data mappings or conversions, and inserting or updating the data in the target system.</li></ul><h3>ETL vs ELT</h3><p>In ETL, the transformation step occurs after data extraction and before loading into the target system. This means that the extracted data is transformed and cleaned in a separate processing engine or environment before being loaded into the target system. The transformed data is typically loaded into a structured format, such as a data warehouse, for subsequent analysis and reporting.</p><p>ELT, on the other hand, is an alternative approach to data integration and processing. Data is extracted from source systems and loaded into the target system in its raw or near-raw form, often without significant transformations. The loading process takes place first, directly into a scalable storage system, such as a data lake or a cloud-based storage service. Once the data is loaded, the transformations are performed directly within the target system using its built-in processing capabilities or specialized tools. This approach leverages the power of modern cloud-based data processing engines that can handle large volumes of data and perform transformations at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Z8PkrN0_mlgXRSC1y9wFew.png" /></figure><h3>How can we utilize GCP service to build a data ingestion pipeline?</h3><p>Google Cloud Platform (GCP) provides a range of services and tools that can greatly assist in building ETL pipelines. Here are some key GCP services and features that can be leveraged for ETL:</p><ol><li><strong>Cloud Storage</strong>: GCP’s Cloud Storage offers a highly scalable and durable storage solution for storing raw data, intermediate files, and transformed data. It can be used as a landing zone for ingesting and staging data before processing.</li><li><strong>BigQuery</strong>: BigQuery is a fully managed, serverless data warehouse service on GCP. It provides powerful querying and analysis capabilities, making it an excellent choice for loading and analyzing transformed data. BigQuery supports batch and streaming ingestion methods and can handle large-scale data processing.</li><li><strong>Dataflow</strong>: Google Dataflow is a managed service for building scalable data pipelines. It offers a unified programming model for both batch and stream processing and integrates well with other GCP services. Dataflow simplifies the development and execution of ETL workflows, supporting data transformations and parallel processing.</li><li><strong>Cloud Pub/Sub</strong>: Pub/Sub is a messaging service that allows you to decouple data producers and consumers. It can be used to ingest real-time data streams, providing reliable messaging between different components of the ETL pipeline.</li><li><strong>Cloud Functions/Cloud Run</strong>: GCP’s serverless compute platforms, such as Cloud Functions and Cloud Run, can be used to perform lightweight data transformations or execute specific tasks within the ETL pipeline. They enable scalable and event-driven execution of code without worrying about infrastructure management.</li></ol><p>These services can be combined to build a robust and scalable ETL pipeline on GCP. The choice of services depends on your specific requirements, data sources, transformation logic, and target systems. GCP’s integrated ecosystem and managed services make it a powerful platform for designing, deploying, and maintaining ETL workflows in a cloud environment.</p><h3>Conclusion</h3><p>In conclusion, ETL is a critical process for organizations seeking to leverage their data for strategic insights and decision-making. By extracting, transforming, and loading data into a target system, businesses can derive meaningful information and drive actionable outcomes. Google Cloud Platform (GCP) offers a powerful suite of services and tools that greatly facilitate the development and implementation of ETL pipelines. With GCP’s robust data storage, processing, and analytics capabilities, organizations can streamline their ETL workflows, improve data quality and consistency, and achieve scalable and efficient data processing. Whether it’s the cloud storage and messaging capabilities of Cloud Storage and Pub/Sub, the data transformation capabilities of Dataflow, or the analytical power of BigQuery, GCP provides a comprehensive ecosystem for building end-to-end ETL pipelines. By harnessing the potential of ETL and GCP, organizations can unlock valuable insights, make data-driven decisions, and stay ahead in today’s data-driven business landscape.</p><p>I plan to write a series of post about ETL by utilizing GCP. we will mainly focus on building a robust, reliable data ingestion pipeline via python and terraform to build on the cloud service.</p><p>Thank you for reading, and have a great day!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80f26a677669" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Project Structure Beginner Guide 2022]]></title>
            <link>https://medium.com/analytics-vidhya/golang-project-structure-beginner-guide-2022-b18285ddc1be?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b18285ddc1be</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 03:15:53 GMT</pubDate>
            <atom:updated>2022-10-08T03:44:16.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Formatted project lowers the maintenance cost and learning curve</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lcCLitbxdCud5aaF" /><figcaption>Photo by <a href="https://unsplash.com/@thisisengineering?utm_source=medium&amp;utm_medium=referral">ThisisEngineering RAEng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Golang is an open source programming language supported by Google with a growing user community. Golang is easy to learn and fast to get started with. To compile the program smoothly without problem, it is good to start the Golang project structure. A structured project will make our life easier and reduce the maintenance cost.</p><p>In this guide, we will talk about the following topics, feel free to jump to the topic you are looking for.</p><ul><li>Simple Project</li><li>Multi-Package Project</li><li>Multi-Main Project</li><li>Multi-Project Workspace (Golang &gt; 1.18)</li><li>Vendor? Go Mod?</li></ul><p><strong>You can find all the code on Github. Please clone or fork the project, and try it locally. You will have a better picture of the structure.</strong></p><p><a href="https://github.com/chiang9/golang_project_structure">https://github.com/chiang9/golang_project_structure</a></p><h3>Simple Project</h3><p>To begin, we will start with a simple project with a main file which imports some external functions.</p><pre>simple_project/<br>├── function1.go<br>├── go.mod<br>├── go.sum<br>└── hello.go</pre><p>In <em>hello.go</em>, we import the function from <em>function1.go</em> and a third party module, <em>golang.org/x/example. </em>The third party module will be automatically downloaded when running</p><p><strong><em>go mod tidy</em></strong></p><pre>&gt; go run simple_project<br>Hello, world<br>Hello, world From function1.go - package = main<br>egakcap ytrap dr3 morf dlrow ,olleH</pre><blockquote>Note: we are able to use the function from the same module without importing even it is from a different file</blockquote><h3>Multi-Package Project</h3><p>In this example, we will showcase a project with multiple packages. It is possible to use various packages in the project.</p><pre>multi_module_project/<br>├── cmd<br>│   ├── mod2<br>│   │   └── mod2.go<br>│   └── mod3<br>│       ├── mod3.go<br>│       └── mod3_sub<br>│           └── mod3_sub.go<br>├── go.mod<br>├── main.go<br>└── mod1<br>    └── mod1.go</pre><p><strong>main.go:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c516f49ee32c3128f02456c2fd847b7f/href">https://medium.com/media/c516f49ee32c3128f02456c2fd847b7f/href</a></iframe><pre>&gt; go run main.go<br>Hello, world<br>Hello, world From mod1.go - package = mod1<br>Hello, world From mod2.go - package = cmd/mod2<br>Hello, world From mod3.go - package = cmd/mod3<br>Hello, world From mod3_sub.go - package = cmd/mod3/mod3_sub</pre><h3>Multi-Main Project</h3><p>Most of the time, we will need multiple functions for a project. We are also able to have multiple main functions under different modules and we can further build the functions into executables.</p><pre>multi_main_project/<br>├── cmd<br>│   ├── func1<br>│   │   └── func1.go<br>│   ├── mod1<br>│   │   ├── mod1_func<br>│   │   │   └── mod1.go<br>│   │   └── mod1_main.go<br>│   └── mod2<br>│       └── mod2_main.go<br>└── go.mod</pre><p><strong>mod1_main.go:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3e27f120c75373401d1e6b02824986d/href">https://medium.com/media/c3e27f120c75373401d1e6b02824986d/href</a></iframe><pre>&gt; go run multi_main_project/cmd/mod1<br>Hello, world from mod1<br>Hello, world From func1.go - package = cmd/func1<br>Hello, world From mod1.go - package = cmd/mod1/mod1_func</pre><pre>&gt; go run multi_main_project/cmd/mod2<br>Hello, world from mod2<br>Hello, world From func1.go - package = cmd/func1<br>Hello, world From mod1.go - package = cmd/mod1/mod1_func</pre><p>In this project, we have to specify the module we want to run. Simply running <em>go run .</em><strong><em> </em></strong>will return error.</p><blockquote>Note: all the files under the same folder must be in the same package, otherwise it will return error. For example, all files in cmd/mod1 must be the same package, but the package can be different in cmd/mod1/mod1_func</blockquote><h3>Multi-Project Workspace</h3><p>Starting from Golang 1.18, the <strong>workspace </strong>mode has been added. The workspace mode gives us the power to develop the Go project across multiple projects.</p><p><a href="https://go.dev/blog/get-familiar-with-workspaces"><strong>Get familiar with workspaces</strong></a></p><p>In this example, we will showcase a basic usage of <strong>go work. </strong>To begin, we can use the following code to generate the work file.</p><p><strong><em>go work init</em></strong></p><p>After the projects are ready, the project can be importable by running</p><p><strong><em>go work use &lt;project_name&gt;</em></strong></p><pre>workspace_project/<br>├── go.work<br>├── project1<br>│   ├── go.mod<br>│   ├── main.go<br>│   └── mod1<br>│       └── mod1.go<br>└── project2<br>    ├── go.mod<br>    ├── main.go<br>    └── mod1<br>        └── mod1.go</pre><p><strong>go.work:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d807d81c7ee55cf2a95b7931a62dfa/href">https://medium.com/media/80d807d81c7ee55cf2a95b7931a62dfa/href</a></iframe><p><strong>project2/main.go:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4038046fa78bd8085b2b4ae91e6ba38f/href">https://medium.com/media/4038046fa78bd8085b2b4ae91e6ba38f/href</a></iframe><pre>&gt; go run project2<br>Hello, world<br>Hello, world From mod1.go - package = mod1, project = project1<br>Hello, world From mod1.go - package = mod1, project = project2</pre><h3>Vendor? Go Mod?</h3><p>Sometimes we will see a vendor folder in a Golang project, so what exactly is the vendor folder and why do we have it?</p><p>When Go language was first published, <strong><em>go get</em></strong> was prebuild to download the third party package, however, the tool was not able to specify the version of the package to download, it will always download the latest version. As you can imagine, this will definitely cause issue when the author of the package makes some major changes to the function, our program will no longer work.</p><p>The solution to this issue was the <strong>Vendor. </strong>The community creates several package management tools, for example, gvt, govendor, godep, glide……etc. The tool will specify the version of the package and download the source code, which will ensure the stability of your project.</p><p>Since Golang 1.13, Go starts supporting the vendor feature, and we can start using the vendor feature which is supported officially.</p><p>Since Golang 1.15, Go starts supporting the Module feature, which allow us to specify the version when installing the third party package.</p><p><a href="https://github.com/golang/go/wiki/Modules">Go Modules</a></p><p>So, do we still need the vendor folder since we are able to specify the package version?</p><p>Golang is still able to work with the vendor feature, and people are still using it, but we should look forward to deprecate the feature unless there are special needs for the vendor folder.</p><p>Thank you for reading, and have a great day!!</p><blockquote>Note: this is not an official standard defined structure by the core Go dev team.</blockquote><p>Reference:</p><p><a href="https://github.com/golang-standards/project-layout">GitHub - golang-standards/project-layout: Standard Go Project Layout</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b18285ddc1be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/golang-project-structure-beginner-guide-2022-b18285ddc1be">Golang Project Structure Beginner Guide 2022</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Modelling with a New Data Approach]]></title>
            <link>https://jchiang1225.medium.com/time-series-modelling-with-a-new-data-approach-e5a8e385a5be?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5a8e385a5be</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Mon, 04 Jul 2022 00:08:14 GMT</pubDate>
            <atom:updated>2022-07-04T21:55:50.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Empower the data structure, Enhance the data process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MQuA6jYPTg06vsuq" /><figcaption>Photo by <a href="https://unsplash.com/@peiobty?utm_source=medium&amp;utm_medium=referral">Pierre Borthiry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Time Series data is a sequence of data points indexed in time order. The most common example of time series data is the daily closing price of the stock market. Time series analysis can help organizations understand the underlying causes of trends or systemic patterns over time.</p><p>In this post, we will showcase the <strong>Time_Series_Transform</strong> package with practical Machine Learning Model on the Stock Market. Time-Series-Transform can help us to reformat the time series data, and simplify the feature engineering process.</p><p><a href="https://pypi.org/project/time-series-transform/"><strong>Time-Series-Transform</strong></a></p><p>You can find more details about the package from the previous post, please take a look!!</p><p><a href="https://jchiang1225.medium.com/a-new-data-approach-in-time-series-analysis-2d6c97f209cd">A New Data Approach in Time Series Analysis</a></p><h3>Installation</h3><pre>pip install time-series-transform</pre><p><em>Note: Make sure tensorflow and plotly are installed on your machine</em></p><h3>Let’s get started</h3><p>Machine Learning is known to be one of the branch of artificial intelligence and one of the most common methods to provide mathematics models to forecast the data. <strong>Feature Engineering</strong> is an essential steps of transforming the raw data into desired features for models. We are able to generate new features from the raw data in order to simplify, speeding up, and enhance the model accuracy.</p><p>This demo is going to train a machine learning model using sklearn, Stock_Transformer, and Time_Series_Transformer to predict the momentum of stock on daily basis. Subsequently, we will use the momentum to generate buy/sell signals and make a plot using Time_Series_Transformer.</p><p><em>Note: This tutorial is aim to demonstrate how to use time_series_transformer, instead of showing how to invest in stock</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faddf3b1bf243243154deed39dae9fa2/href">https://medium.com/media/faddf3b1bf243243154deed39dae9fa2/href</a></iframe><p>By using Nasdaq and Gold, we can enrich the features. we expand the Nasdaq and Gold into feature columns. Next, we use make_lead features combining with the up_down_transform function to generate the pricing moment for the next time period.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e574bd7f76df20eed9ef83c96750c053/href">https://medium.com/media/e574bd7f76df20eed9ef83c96750c053/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*netPn4NVvm3luRFnXUkL2g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be96825c1e0f4805a8077ef2673c95d8/href">https://medium.com/media/be96825c1e0f4805a8077ef2673c95d8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*rmh-f5JoL3FxcjlcuAlAww.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f320b9024095199dad7216ab20934b9e/href">https://medium.com/media/f320b9024095199dad7216ab20934b9e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWejmvvOWTn5f3AT3hxKsA.png" /></figure><p>By separating the data into train and test set, we are ready to build our machine learning pipeline. In this example, we will only build a simple model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f61bfa2a6fa0971369ac81522a5909a/href">https://medium.com/media/3f61bfa2a6fa0971369ac81522a5909a/href</a></iframe><pre>                 precision    recall  f1-score   support<br><br>        down       0.40      0.12      0.19        33<br>    unchange       0.00      0.00      0.00         1<br>          up       0.40      0.77      0.53        26<br><br>    accuracy                           0.40        60<br>   macro avg       0.27      0.30      0.24        60<br>weighted avg       0.39      0.40      0.33        60<br><br>[[ 4  0 29]<br> [ 0  0  1]<br> [ 6  0 20]]</pre><p>We generate the prediction based on our machine learning model. <strong>Time_Series_Transform</strong> can also give us a hand on visualization.</p><p>Before we create the plot, we need to process our result to generate some buy/sell signal. To generate the signals, we use the following rules:</p><ol><li>the first period should be buy.</li><li>buy and then hold until sell</li><li>buy when the predict value is up</li><li>sell when the predict value is down</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/320c15ea1d1b80906bca78e1a15eb36a/href">https://medium.com/media/320c15ea1d1b80906bca78e1a15eb36a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6H7e5jyGxDtkpPFuf_-Tvw.png" /></figure><p>Even though the model is not giving a very promising outcome, but the package helps us in processing the data and to visualize the result easily.</p><h3>What’s Next…</h3><p>In this example, we build the machine learning model by utilizing the <strong>time_series_transform </strong>package. This package can also help us in building the <strong>Neural Network</strong> model features with the power of tensorflow. We are able to transform the data into tfRecord in one line of code.</p><p>You can find more detail in the <a href="https://allen-chiang.github.io/Time-Series-Transformer/introduction.html">documentation</a>.</p><p>Thank you for reading, have a great day!!</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5a8e385a5be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A New Data Approach in Time Series Analysis]]></title>
            <link>https://medium.com/analytics-vidhya/a-new-data-approach-in-time-series-analysis-2d6c97f209cd?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d6c97f209cd</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Sun, 29 May 2022 02:40:13 GMT</pubDate>
            <atom:updated>2022-08-13T16:27:53.581Z</atom:updated>
            <content:encoded><![CDATA[<p>Empower the data structure, Enhance the data process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ix1eL_jB-inRqCf-" /><figcaption>Photo by <a href="https://unsplash.com/@peiobty?utm_source=medium&amp;utm_medium=referral">Pierre Borthiry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Time Series data is a sequence of data points indexed in time order. The most common example of time series data is the daily closing price of the stock market. Beside the stock market, we do encounter a lot of different time series data, for instance, the climate changes across time or the sales revenue of a company. Time series analysis helps organizations understand the underlying causes of trends or systemic patterns over time.</p><p>Today, we want to dive into a fancy and powerful time series data structure engine.</p><p><a href="https://pypi.org/project/time-series-transform/"><strong>Time-Series-Transformer</strong></a></p><p>The package not only provides functionalities to process the time series data, but it shines when we need to process <strong>multi-dimensional</strong> time series data. Moreover, the submodule, <strong>Stock_Transformer</strong>, is able to extract the stock data and calculate the technical indicators in just a few lines of code.</p><h3>Installation</h3><pre>pip install time-series-transform</pre><p><em>Note: Make sure tensorflow and plotly are installed</em></p><h3>Data</h3><p>In this example, we will use the climate time series data in Delhi from Kaggle</p><p><a href="https://www.kaggle.com/datasets/sumanthvrao/daily-climate-time-series-data?resource=download">https://www.kaggle.com/datasets/sumanthvrao/daily-climate-time-series-data?resource=download</a></p><h3>Let’s get started</h3><p>When we are processing the time series data, we always need to take extra attention on the time order, and it is not easy to do so with solely numpy or even pandas. The <strong>Time_Series_Transform </strong>makes the task easier than ever.</p><p>There are two main modules in the package.</p><ul><li>Time_Series_Transformer: the core module and it is compatible with user defined time series data</li><li>Stock_Transformer: helps us to extract stock data and provide operation to embed the technical indicator calculation library (pandas-ta)</li></ul><h3>Time Series Transformer Core</h3><p><strong>Time_Series_Transformer </strong>can helps us to format the time series data and we are able to manipulate the time series data easily.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a7c8db85b0cc1e39950341e5cb59cbb/href">https://medium.com/media/3a7c8db85b0cc1e39950341e5cb59cbb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*N7nILyEBLbj_t-eD_wHY-w.png" /><figcaption>Figure 1. climate data</figcaption></figure><p>From the dataset, we can see there are 4 different features, and we can load the data into our package from pandas.dataFrame. The <strong>timeSeriesCol </strong>will be the column of the time index, and the mainCategory field allows us to handle multi-dimensional data, we will talk about it later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/648024c6bda90871da8acf72461607b2/href">https://medium.com/media/648024c6bda90871da8acf72461607b2/href</a></iframe><pre>ime_Series_Transformer data<br>data column<br>-----------<br>date<br>meantemp<br>humidity<br>wind_speed<br>meanpressure<br>time length: 1462<br>category: None<br><br><br>We can slice the data from the time_series_data as below<br>{&#39;date&#39;: array([&#39;2013-01-01&#39;, &#39;2013-01-02&#39;, &#39;2013-01-03&#39;], dtype=object),<br> &#39;meantemp&#39;: array([10.        ,  7.4       ,  7.16666667]),<br> &#39;humidity&#39;: array([84.5, 92. , 87. ]),<br> &#39;wind_speed&#39;: array([0.        , 2.98      , 4.63333333]),<br> &#39;meanpressure&#39;: array([1015.66666667, 1017.8, 1018.66666667])}</pre><h4>Data Manipulation</h4><p>Most of the time, we need to preprocess the data before entering the model. In time series analysis, making lag or lead data (shifting data) is one of the most common methods. The package also provide the function to shift data.</p><ul><li>make_lead</li><li>make_lag</li><li>make_lead_sequence</li><li>make_lag_sequence</li></ul><p><em>make_lead</em> and <em>make_lag</em> shift the data</p><p><em>make_lead_sequence</em> and <em>make_lag_sequence</em> shift the data and return a window list data as feature. It is useful in producing Deep learning feature</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/994e347e694a303e9fc5f026aad27cdd/href">https://medium.com/media/994e347e694a303e9fc5f026aad27cdd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*xrILPRwBltujwlqmsfs7-w.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4b16ee277e0bfea66ee5c6938e3558c/href">https://medium.com/media/e4b16ee277e0bfea66ee5c6938e3558c/href</a></iframe><pre>{&#39;date&#39;: array([&#39;2013-01-01&#39;, &#39;2013-01-02&#39;, &#39;2013-01-03&#39;], dtype=object),<br> &#39;meantemp&#39;: array([10.        ,  7.4       ,  7.16666667]),<br> &#39;humidity&#39;: array([84.5, 92. , 87. ]),<br> &#39;wind_speed&#39;: array([0.        , 2.98      , 4.63333333]),<br> &#39;meanpressure&#39;: array([1015.66666667, 1017.8, 1018.66666667]),<br> &#39;meantemp_lead_3&#39;: array([8.66666667, 6.        , 7.        ]),<br> &#39;wind_speed_lead_3&#39;: array([1.23333333, 3.7       , 1.48      ]),<br> &#39;meantemp_lead_seq_3&#39;: array([[7.4       , 7.16666667, 8.66666667],<br>        [7.16666667, 8.66666667, 6.        ],<br>        [8.66666667, 6.        , 7.        ]]),<br> &#39;meanpressure_lead_seq_3&#39;: array([[1017.8, 1018.6667, 1017.1667],<br>        [1018.66666667, 1017.16666667, 1016.5       ],<br>        [1017.16666667, 1016.5       , 1018.        ]])}</pre><h4>User defined function</h4><p>It is also possible to use the user defined function. We can use the <strong>transform</strong> function to customize the data process.</p><p>Restriction of the customize function:</p><ul><li>the function must take an array</li><li>output must be an array with the same size as the original data length</li></ul><p>Note: time_series_transform.transform_core_api.util provides some general functions as we imported at the beginning</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f906d5d0995e9a31b03d82c0f3fed80a/href">https://medium.com/media/f906d5d0995e9a31b03d82c0f3fed80a/href</a></iframe><pre>data column<br>-----------<br>date<br>meantemp<br>humidity<br>wind_speed<br>meanpressure<br>meantemp_lead_3<br>wind_speed_lead_3<br>meantemp_lead_seq_3<br>meanpressure_lead_seq_3<br>wind_cust_10<br>time length: 1462<br>category: None</pre><h4>Plot</h4><p>The package also provides function to draw plot and it supports several functions customize the plot.</p><ul><li>add_line</li><li>remove_line</li><li>update_layout</li><li>add_marker</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ad95455863a1cdf733fe8d18b9179fc/href">https://medium.com/media/8ad95455863a1cdf733fe8d18b9179fc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*MljE5HMlKT7oTTqAgl8y8A.png" /><figcaption>Figure 2. plot function</figcaption></figure><h3>Multi-Dimensional Time Series Data</h3><p>Sometimes when we are doing Exploratory Data Analysis or preprocessing the time series data before entering the model, we might want to separate the data by their features. Handling multi-dimensional time series data is the strong point of the package.</p><p>Time_Series_Transformer can specify the <strong>mainCategoryCol</strong> parameter to point out the main category. This class only provide one columns for main category because multiple dimensions can be aggregated into a new column as main category.</p><p>From the <a href="https://allen-chiang.github.io/Time-Series-Transformer/introduction.html#introduction">documentation</a>. With the <strong>mainCategoryCol, </strong>we are able to separate the data by the category and perform same data operations as we did previously.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f79271bc45321e29de86a3765d1fac1a/href">https://medium.com/media/f79271bc45321e29de86a3765d1fac1a/href</a></iframe><p>Next we can further apply the functionality to perform advance preprocessing. To demonstrate the capability of the <strong>Time_Series_Transformer</strong>, we can separate the data by their month and investigate the behavior of the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d6263c91fb658d21c2037aa83645fb/href">https://medium.com/media/68d6263c91fb658d21c2037aa83645fb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*HoF1zgyTpWJjYPC1As9LPA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/427adfd71ad00977ea75f15409b5d8c7/href">https://medium.com/media/427adfd71ad00977ea75f15409b5d8c7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*_8_ajCbUI_6MO0QVfdwpgg.png" /></figure><p>Moreover, we can also use the plot function on the multi-dimension data, and it will generate several lines and we can select which month we want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5627ed0a1ab95e9e40853972ce24bddc/href">https://medium.com/media/5627ed0a1ab95e9e40853972ce24bddc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpcMS_VewGiYn91l1l80CQ.png" /><figcaption>Figure 3. Multi-dimension plot (option to choose category)</figcaption></figure><h3>Stock Transformer</h3><p>Speaking of the time series analysis, the stock market must be the interest of most people. <strong>Stock_Transformer</strong> makes our life easy and simple. Extraction of the stock data can be done in just one line of code, and we can also use the power of the data manipulation like how we did previously.</p><p>Stock extraction methods:</p><ul><li>from_stock_engine_date</li><li>from_stock_engine_period</li><li>from_stock_engine_intraday</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef2794c2c45d20e24ae7be3ad670ac45/href">https://medium.com/media/ef2794c2c45d20e24ae7be3ad670ac45/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*TVNb-b1laTOBPJbZaA_mGw.png" /></figure><p>To calculate the standard technical indicators, we can use the <strong>get_technial_indicator </strong>with <strong>pandas-ta.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ef21580e09fd5fad9da215b2838a715/href">https://medium.com/media/5ef21580e09fd5fad9da215b2838a715/href</a></iframe><pre>Date       Open       High        Low      Close     Volume  \<br>25  2019-02-07  41.725962  42.098690  41.227381  41.372601  126966800   <br>26  2019-02-08  41.076051  41.481974  40.937501  41.421207   95280000   <br>27  2019-02-11  41.576775  41.615667  41.139252  41.183002   83973600   <br>28  2019-02-12  41.345854  41.564614  41.248625  41.537876   89134000   <br>29  2019-02-13  41.659413  41.924356  41.302103  41.365299   89960800   <br><br>    Dividends  Stock Splits  MACD_12_26_9  MACDh_12_26_9  MACDs_12_26_9  \<br>25     0.0000           0.0      1.952193            NaN            NaN   <br>26     0.1825           0.0      1.915505            NaN            NaN   <br>27     0.0000           0.0      1.845929            NaN            NaN   <br>28     0.0000           0.0      1.798691            NaN            NaN   <br>29     0.0000           0.0      1.727417            NaN            NaN   <br><br>       EMA_10        BBL        BBM        BBU  Bandwidth   Percent  <br>25  40.383502  34.842427  38.655327  42.468227  19.727684  0.856326  <br>26  40.572176  34.930402  38.865177  42.799952  20.248332  0.824800  <br>27  40.683235  35.136170  39.081391  43.026611  20.189764  0.766349  <br>28  40.838624  35.475825  39.343060  43.210295  19.659045  0.783771  <br>29  40.934383  35.746722  39.558949  43.371175  19.273650  0.736915</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9b5403ca9c45c13918cba00bffbb995/href">https://medium.com/media/a9b5403ca9c45c13918cba00bffbb995/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehHsTsqKFVdLM82P7bBD5w.png" /><figcaption>Figure 4. Stock candle plot</figcaption></figure><h3><strong>Reference</strong></h3><p>Time Series Transformer:</p><p><a href="https://allen-chiang.github.io/Time-Series-Transformer/introduction.html#">https://allen-chiang.github.io/Time-Series-Transformer/introduction.html</a></p><p><a href="https://github.com/allen-chiang/Time-Series-Transformer">https://github.com/allen-chiang/Time-Series-Transformer</a></p><p>Thank you for reading, have a great day!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d6c97f209cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-new-data-approach-in-time-series-analysis-2d6c97f209cd">A New Data Approach in Time Series Analysis</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PySpark CheatSheet and More]]></title>
            <link>https://medium.com/analytics-vidhya/pyspark-cheatsheet-and-more-a41b338c9d3e?source=rss-d4f328ac999d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a41b338c9d3e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Jeffery chiang]]></dc:creator>
            <pubDate>Thu, 30 Dec 2021 00:35:51 GMT</pubDate>
            <atom:updated>2022-02-25T15:28:25.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X0NdQ2IWPcvVzgIW" /><figcaption>Photo by <a href="https://unsplash.com/@anacruzbaeza?utm_source=medium&amp;utm_medium=referral">Ana Cruz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Apache Spark and Apache Hadoop are both open-source frameworks for big data processing. Spark can be 100x faster than Hadoop for large scale data processing, however, Hadoop has distributed file system (HDFS) while Spark is built on resilient distributed datasets (<strong>RDDs</strong>). Usually, we use Spark for data computation on top of Hadoop.</p><p>In this article, we will focus on the data manipulation of <strong>RDD</strong>.</p><p>All code can be found on <a href="https://github.com/chiang9/Medium_blog/blob/main/pyspark/spark_cheatsheet.ipynb">github</a>.</p><blockquote>Dataset:</blockquote><blockquote>We will be using the <a href="https://grouplens.org/datasets/movielens/">movielens </a>dataset (ml-100k) for demo.</blockquote><blockquote>Datacamp also provides a clear cheat sheet for pyspark.</blockquote><blockquote>More Information: <a href="https://www.datacamp.com/community/blog/pyspark-cheat-sheet-python">https://www.datacamp.com/community/blog/pyspark-cheat-sheet-python</a></blockquote><h3>1. Initializing Spark Environment</h3><p>Whenever we want to use the Spark Engine, we need to first initialize the Spark environment.</p><h4>SparkContext</h4><p>The driver program will use the SparkContext to connect and communicate with the cluster and it coordinate the jobs with the resource management system.</p><h4>SparkSession</h4><p>Starting from Spark 2.0, SparkSession built the gateway to different data sources, such as SQL or Hive. In Spark 1.x, we need to define the SQLContext or HiveContext to communicate with the corresponding sources.</p><p><em>In short, we need to define the SparkSession if we want to use the Spark Dataframe or Dataset, otherwise SparkContext can execute the RDDs</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcffac47ca8c4a3dcd9795426e61eec1/href">https://medium.com/media/fcffac47ca8c4a3dcd9795426e61eec1/href</a></iframe><h3>2. Loading Data</h3><p>We are able to create the <em>rdd</em> with iterable data or external data sources. We will first load the movielen datafile as text string, and do the manipulation later.</p><p><em>Note: SparkSession need to be defined before accessing the </em><strong><em>rdd.toDF()</em></strong><em> function, otherwise exception will be thrown.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a7ec2bead7901ecdb8807c565ec4ba7/href">https://medium.com/media/2a7ec2bead7901ecdb8807c565ec4ba7/href</a></iframe><pre>+------+---+<br>|    _1| _2|<br>+------+---+<br>| apple| 10|<br>|orange| 20|<br>| peach|100|<br>+------+---+</pre><h3>3. Data Retrieval</h3><p>By using the following commands, we are able to retrieve information of the data in the rdd.</p><ul><li>getNumPartitions()</li><li>count(), countByKey(), countByValue()</li><li>collect(), collectAsMap(), take(<em>num</em>), top(<em>num</em>)</li><li>max(), min(), mean(), stdev(), variance(), histogram(<em>num of bin</em>), stats()</li></ul><pre>rdd_movie.take(3)</pre><pre>&gt;&gt; [&#39;196\t242\t3\t881250949&#39;, &#39;186\t302\t3\t891717742&#39;, &#39;22\t377\t1\t878887116&#39;]</pre><h3>4. Data Processing</h3><p>Processing data in PySpark might reminds you about the <strong>Pandas</strong> Dataframe. Similar to Pandas, PySpark also provide the functionality to <em>group, aggregate, sort, and reduce</em>. However, there are some functions which are similar but perform differently.</p><h4>map vs flatMap</h4><p>map and flatMap looks similar but they are different, and worth extra attention.</p><p>The map function is able to maintain the list structure of the original data shape, and the flatMap will unpack the list structure and form a large list data structure.</p><p>In the following cells, we will visualize the difference by separating the rdd_movie rdd with proper delimiter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20fcaffd01cecc070c60bcf38b2b0ce0/href">https://medium.com/media/20fcaffd01cecc070c60bcf38b2b0ce0/href</a></iframe><h4>groupBy vs groupByKey</h4><p>groupBy function will group the data based on the result from the function in the input, groupByKey will group the data based on the key of the original rdd.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a5fbcb1caa0e776e461349f80f87e41/href">https://medium.com/media/7a5fbcb1caa0e776e461349f80f87e41/href</a></iframe><pre>groupby result:</pre><pre>userid last digit = 6<br>[&#39;196&#39;, &#39;242&#39;, &#39;3&#39;, &#39;881250949&#39;]<br>[&#39;186&#39;, &#39;302&#39;, &#39;3&#39;, &#39;891717742&#39;]<br>[&#39;166&#39;, &#39;346&#39;, &#39;1&#39;, &#39;886397596&#39;]<br>[&#39;6&#39;, &#39;86&#39;, &#39;3&#39;, &#39;883603013&#39;]</pre><pre><br>groupByKey result:</pre><pre>rating = 1<br>[&#39;22&#39;, &#39;377&#39;, &#39;1&#39;, &#39;878887116&#39;]<br>[&#39;166&#39;, &#39;346&#39;, &#39;1&#39;, &#39;886397596&#39;]<br>[&#39;181&#39;, &#39;1081&#39;, &#39;1&#39;, &#39;878962623&#39;]<br>[&#39;276&#39;, &#39;796&#39;, &#39;1&#39;, &#39;874791932&#39;]</pre><h4>reduce vs reduceByKey</h4><p>Before we dive into the code, we need to realize that <em>reduce</em> is an action and <em>reduceByKey</em> is transformation.</p><p>Definition on the original document: <a href="https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html">https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html</a></p><p><em>reduce: Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel.</em></p><p><em>reduceByKey: When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V,V) =&gt; V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.</em></p><p>In this section, we will demonstrate some examples of the functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36ca6a53aad8f4f23e058eae33dd4e10/href">https://medium.com/media/36ca6a53aad8f4f23e058eae33dd4e10/href</a></iframe><h3>5. Sample usage on MovieLen dataset</h3><p>In this section, we will use the PySpark RDD to process the data of the movie, and retrieve the corresponding genre.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e185bf0d85ff79918e83402ad4ea3672/href">https://medium.com/media/e185bf0d85ff79918e83402ad4ea3672/href</a></iframe><pre>[[&#39;1&#39;, &#39;Toy Story (1995)&#39;, [&#39;Animation&#39;, &quot;Children&#39;s&quot;, &#39;Comedy&#39;]],<br> [&#39;2&#39;, &#39;GoldenEye (1995)&#39;, [&#39;Action&#39;, &#39;Adventure&#39;, &#39;Thriller&#39;]]]</pre><p>Thank you for reading, Happy new year.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a41b338c9d3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/pyspark-cheatsheet-and-more-a41b338c9d3e">PySpark CheatSheet and More</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>