<?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[Machine Learning Reply DACH - Medium]]></title>
        <description><![CDATA[Machine Learning Reply befähigt seine Kunden, neue datenbasierte Geschäftsmodelle erfolgreich einzuführen sowie bereits bestehende Prozesse und Produkte zu optimieren — mit einem Schwerpunkt auf Open-Source- und Cloud-Technologien. - Medium]]></description>
        <link>https://medium.com/machine-learning-reply-dach?source=rss----4e1d53a63327---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Machine Learning Reply DACH - Medium</title>
            <link>https://medium.com/machine-learning-reply-dach?source=rss----4e1d53a63327---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:36:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/machine-learning-reply-dach" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Make Smart Investment Decisions: Stock Analysis and Value-Weighted Index]]></title>
            <link>https://medium.com/machine-learning-reply-dach/how-to-make-smart-investment-decisions-stock-analysis-and-value-weighted-index-6ec1599a43e5?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/6ec1599a43e5</guid>
            <category><![CDATA[value-investing]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[stock-analysis]]></category>
            <dc:creator><![CDATA[Pedro Flores]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 12:03:39 GMT</pubDate>
            <atom:updated>2023-04-25T12:03:39.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHe1IuVKCqNp-v83uNhuPQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bash__profile?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nicholas Cappello</a> on <a href="https://unsplash.com/photos/Wb63zqJ5gnE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>The stock market is a fascinating and complex system where the share prices of companies change constantly, influenced by various factors, such as company performance, market sentiment, and global economic conditions. In this article, the stock data of various companies will be explored and analyzed, and some visualizations will be done for better data understanding. Furthermore, it will be explained how to create a Value-Weighted Index using data from companies with substantial stock market presence that can be used as a reference for a personal portfolio.</p><p>The approach followed have these 4 points:</p><ul><li><strong>Stock Data</strong></li><li><strong>Perform Exploratory Data Analysis</strong></li><li><strong>Compute Technical Indicators</strong></li><li><strong>Create a Value-Weighted Index</strong></li></ul><h3>Stock Data</h3><p>The stock data analyzed will be from companies in the Technology sector: Apple Inc. (AAPL) and Reply S.p.A. (REY.MI), Consumer Cyclical: Tesla, Inc. (TSLA), Healthcare: Pfizer Inc. (PFE) and Financial: JPMorgan Chase &amp; Co. (JPM)</p><p>In order to fetch the data, a popular Python library that allows access to financial data from Yahoo Finance will be used: yfinance. For example, to download Apple’s stock data, the function <em>yf.download()</em> can be used. The parameters needed for the definition are the ticker symbol (AAPL for Apple Inc.), the start and end dates for the data, and the interval at which the data is desired (hourly, daily, etc.).</p><p>Here’s an example that downloads daily stock data for Apple Inc. from January 1, 2018, to April 01, 2023:</p><pre>ticker = &quot;AAPL&quot;<br>start_date = &quot;2018-01-01&quot;<br>end_date = &quot;2023-04-01&quot;<br>interval = &quot;1d&quot;<br>aapl_data = yf.download(ticker, start=start_date, end=end_date, interval=interval)</pre><p>The <em>yf.download()</em> function returns a pandas DataFrame with columns for Open, High, Low, Close, Adjusted Close, and Volume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*E8mVtwDmDhaAkkpQSkl4gg.png" /><figcaption>Stock Data DataFrame</figcaption></figure><h3>Perform Exploratory Data Analysis</h3><p>Exploratory Data Analysis (EDA) is a critical step in the data analysis process, allowing us to understand, summarize, and visualize the main characteristics of a dataset. When working with stock data, EDA can help identify trends, patterns, relationships, and potential outliers.</p><h4>Check Missing Values</h4><p>First, let’s make sure that the data used has no missing values. Identifying and handling these values is an essential step because they can have a significant impact on the quality of the analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*stDWGPp5g1FaaXDvwxpAXg.png" /><figcaption>Count of missing values in the stock data downloaded</figcaption></figure><h4>Visualize Stock Prices</h4><p>Visualizing stock prices is important for several reasons, including better understanding, identifying trends and patterns, and detecting anomalies and outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*520MdPzqwx7IRGynkaOsRA.png" /><figcaption>Closing Prices of stock data</figcaption></figure><p>It can be seen how for example Pfizer Inc. stock seems to be more stable in contrast to Tesla, Inc. Also, in the beginning of 2020 there is a noticeable drop in all prices matching the start of the global pandemic.</p><h4>Visualize Daily Returns</h4><p>Daily returns can be positive (gains) or negative (losses) and are influenced by various factors, including market conditions, company performance, and investor sentiment. Investors use daily returns to assess their investment strategies, evaluate the risk-reward profile of their portfolios, and make informed decisions about buying, holding, or selling stocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*y202-sNQh5OwVWkSAD7xXw.png" /><figcaption>Daily Returns of stock data</figcaption></figure><p>For the studied companies, it can be identified for example that Pfizer Inc. return (in green) was more relevant by the end of 2021, how Tesla, Inc. shows a volatile behavior over time (in orange), or the big returns and losses observed in the beginning of 2020 for all companies.</p><h4>Visualize the Distribution of Stock Returns</h4><p>This step is important for several reasons:</p><p>· Identifying the shape of the distribution, whether it is symmetric or skewed. This information is useful for understanding the general behavior of the stock.</p><p>· Assessing the historical performance, such as its average return and the range of returns it has experienced. This information can be used to gauge the stock’s potential future performance and to make informed investment decisions.</p><p>· Identifying outliers or extreme returns that may have occurred. This can help understand if a stock has been subject to sudden, large price movements or if it has generally been stable over time.</p><p>· Assessing volatility, which is a key measure of risk. A wider distribution of returns indicates higher volatility and, consequently, higher risk, while a narrower distribution suggests lower volatility and risk.</p><p>All this can be observed in the following graphics. Each stock has been represented in a subplot for a better visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Q6joQxRs9cZB7lY2egW8tw.png" /><figcaption>Distribution of Stock Returns</figcaption></figure><p>It can be seen how in general they all follow a symmetric distribution. Regarding outliers, JPMorgan Chase &amp; Co. has several negative daily returns while Reply S.p.A. has an unusual spike as a positive daily return of around 0.04.</p><p>When assessing the volatility, Tesla, Inc. seem to be the riskier value for having daily returns that range between -0.2 and 0.2. On the other hand, Pfizer Inc. shows a more stable behavior with a range between -0.075 and 0.1.</p><h4>Visualize the Correlation Between Stock Returns</h4><p>This is a measure of the degree to which the returns of two stocks move together and is generally more useful than visualizing just the correlation between stock prices, mainly due to the following reasons:</p><p>· Stationarity: Stock prices tend to trend over time and can show high correlations. Stock returns, representing percentage changes, are more stationary and provide a better measure of the relationship between stocks.</p><p>· Diversification: When constructing a portfolio, investors often seek to diversify their holdings to minimize risk. The correlation between stock returns helps to identify stocks that move independently or even in opposite directions, which can be beneficial for reducing the overall risk of the portfolio.</p><p>This can be seen in the following heatmap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*RodBjoPx97GJvPBUYl5cFQ.png" /><figcaption>Correlation Between Stock Returns</figcaption></figure><p>For example, if Apple Inc. shares are part of a portfolio and someone wants to buy a new share that diversifies it, two good options would be Reply S.p.A. (REY.MI) or Pfizer Inc. (PFE) since both are less correlated.</p><h3>Compute Technical Indicators</h3><p>These are essential tools for stock analysis because they help traders and investors make informed decisions by analyzing historical price and volume data. Technical indicators can provide insights into market trends, momentum, volatility, and other aspects.</p><h4>Simple Moving Average (SMA) and Exponential Moving Average (EMA)</h4><p>The SMA is calculated by averaging the stock prices over a specific window of time. It helps identify the overall trend by smoothing out price fluctuations. If the shorter-term SMA (SMA50) is above the longer-term SMA (SMA200), it indicates an uptrend meaning that the value is expected to continue rising.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*wxSflUoMdVYdBSsW9AcL-g.png" /><figcaption>SMA and EMA for Apple Inc.</figcaption></figure><p>Taking a closer look at Apple Inc. SMA50 (orange) between 2020 and 2022, it is over the SMA200 (green) for the whole period, and it shows an uptrend as expected.</p><p>The EMA places more weight on recent data, making it more responsive to short-term price changes. Like the SMA, when the short-term EMA (EMA50) is above the long-term EMA (EMA200), it indicates an uptrend. The same behavior of SMA for Apple Inc. can be seen between EMA50 (red) and EMA200 (purple).</p><h4>Relative Strength Index (RSI)</h4><p>The RSI is a momentum indicator that measures the speed and magnitude of price movements. It ranges from 0 to 100, with values above 70 typically considered overbought (potentially overvalued), and values below 30 considered oversold (potentially undervalued). When the RSI is above 70, the stock may be overbought, suggesting that it might be a good time to sell. Conversely, when the RSI is below 30, the stock may be oversold, suggesting that it might be a good time to buy. However, in a strong trend, the RSI may remain in overbought or oversold territory for an extended period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*SAhpkctQ3nXpR51ZXnpRKw.png" /><figcaption>Relative Strength Index for JPMorgan Chase &amp; Co</figcaption></figure><p>The graphic above depicts the RSI for JPMorgan Chase &amp; Co. It shows how there is a general trend for the RSI to keep values between 30 and 70. Nevertheless, when the trend is strong, RSI remains under 30 or above 70 for some time.</p><h4>Bollinger Bands</h4><p>They are an analysis tool developed by John Bollinger in the 1980s. Bollinger Bands consist of a moving average (typically the 20-day moving average) and two standard deviation bands above and below the moving average. These bands expand and contract based on the stock’s volatility. When the bands are tight, it suggests low volatility, and when they are wide, it indicates high volatility. Prices tend to revert to the mean after touching the upper or lower bands, so traders often use these bands to identify potential entry and exit points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*W9gxr-LPZsgh7ZAjHIc9zw.png" /><figcaption>Bollinger Bands for Tesla, Inc.</figcaption></figure><p>The Bollinger Bands for Tesla, Inc. show a period that suggests low volatility until middle of 2020, then, the bands start having a wider behavior what could be understood as a period of high volatility. It is also remarkable how the Close price (blue) tends to revert to the mean after touching the upper or lower bands.</p><h3>Create a Value-Weighted Index</h3><p>Building a Value-Weighted Index involves selecting a group of stocks that represent a specific market segment or industry, and then weighing them based on their market capitalization. To create a well-diversified value-weighted index using Python, companies form different industries are going to be considered:</p><p>· Technology: Apple Inc. (AAPL) and Microsoft Corporation (MSFT)</p><p>· Healthcare: Johnson &amp; Johnson (JNJ) and Pfizer Inc. (PFE)</p><p>· Financials: JPMorgan Chase &amp; Co. (JPM) and Bank of America Corporation (BAC)</p><p>· Consumer: Coca-Cola (KO) and PepsiCo, Inc. (PEP)</p><p><strong>The steps followed to create a Value-Weighted Index are:</strong></p><p>1. Calculate the number of shares for selected companies by dividing Market Capitalization by Last Sale . The number of shares will be considered constant.</p><pre>num_shares[ticker] = market_caps[ticker] / data[ticker].iloc[-1]</pre><p>2. Calculate the market capitalization on each day by multiplying the number of shares by the close stock price</p><pre>daily_market_caps = data * num_shares</pre><p>3. Sum the Market Capitalization of each day to have the total Market Capitalization per day</p><pre>global_market_cap = daily_market_caps.sum(axis=1)</pre><p>4. Calculate the company weight in the new index by dividing the Market Capitalization of each company by total Market Capitalization per day</p><pre>weights = market_cap.div(global_market_cap)</pre><p>5. Calculate the company weighted returns by multiplying the company weight in the new index by the stock return</p><pre>weighted_returns = weights.mul(index_return)</pre><p>Once this is done it is possible to visualize the Aggregate Market Capitalization and Weighted Returns, compare the Value-Weighted Index created with a reference in the stock market index like the SP500, that tracks the stock performance of 500 of the largest companies listed on stock exchanges in the United States, and finally plot a Correlation Clustermap.</p><h4>Visualize the Aggregate Market Cap and Weighted Returns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*OPLQTN-XcrJe6caX2rt6Dw.png" /><figcaption>Aggregate Market Cap and Weighted Returns</figcaption></figure><p>The left plot represents the total Market Capitalization per day for the chosen companies. In the beginning of 2020, there is a sharp decline in the share price. On the horizontal histogram on the left, the weighted returns show how Apple Inc. and Microsoft Corporation have a bigger weight in the created index than other companies.</p><h4>Compare Index Created with SP500</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*85oqYEhC4dZWHvm3qxaoZw.png" /><figcaption>Value-Weighted Index created vs SP500</figcaption></figure><p>The picture above depicts a comparison of the Normalized Market Capitalization between the custom index created and SP500. If 100€ would have been invested in 2018 in S&amp;P500, this would have grown 25% in 2020 and 75% in 2022. On the other hand, if 100€ would have been invested in the new Value-Weighted Index created, in 2020 the quantity would be 50% higher while in 2022 more than 150% higher. The companies selected for the Value-Weighted Index performed in the last years better than companies in S&amp;P500.</p><h4>Correlation Clustermap</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*VvTIm3F-lgar_8VxJrcMbQ.png" /><figcaption>Correlation Clustermap</figcaption></figure><p>The Clustermap above represents the correlation between stock returns, with lighter colors indicating a stronger correlation and darker colors indicating a weaker correlation. For instance, JPMorgan Chase &amp; Co. (JPM) and Bank of America Corporation (BAC) exhibit a return correlation of 0.92, implying that their stock prices have tended to move together in most cases. In contrast, Apple Inc. (AAPL) and Pfizer Inc. (PFE) have a stock return correlation of only 0.35, indicating that their stock movements are relatively unconnected.</p><h3>Conclusion</h3><p>This analysis has explored the intricate world of the stock market. Different trends, patterns, relationships, and potential outliers have been identified in the data through Exploratory Data Analysis and computing essential technical indicators. Creating a Value-Weighted Index and comparing it with a reference index, such as the S&amp;P 500, has showcased the performance of the selected companies.</p><p>Overall, this article demonstrates the importance of a thorough analysis of stock data and highlights how it can help investors make informed decisions in the complex world of stock markets.</p><p>At Machine Learning Reply, we guide and support all our customers in the development of their IT capabilities towards Machine Learning, data, or cloud Use Cases, regardless of their current phase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ec1599a43e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/how-to-make-smart-investment-decisions-stock-analysis-and-value-weighted-index-6ec1599a43e5">How to Make Smart Investment Decisions: Stock Analysis and Value-Weighted Index</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A general understanding of Recommendation systems and their techniques]]></title>
            <link>https://medium.com/machine-learning-reply-dach/a-general-understanding-of-recommendation-systems-and-their-techniques-bc87d7b10b3d?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/bc87d7b10b3d</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[B Babu]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 09:33:47 GMT</pubDate>
            <atom:updated>2023-02-24T09:33:47.159Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>A general understanding of Recommendation Systems and their techniques</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a57XhWTi-c1AIIgu-XRAWg.jpeg" /></figure><p>Recommendation systems have gained significant importance in the e-commerce industry where a wide range of options is generated for users. It is basically an information filtering system that uses feedback and user details to predict the preference of a user towards an item. A recommendation system can utilize users’ past behavior or specifications to provide them with personalized content and services.</p><p><strong>Implicit and explicit feedback</strong></p><p>For a recommendation system to perform better, it should be allowed to collect and integrate required feedback from its users. This data is related to individual specifications of the users and items, the data generated by the interaction of users with items in the past, and ratings provided by users to an item.</p><p>Explicit feedback is in the form of item ratings, which are explicitly given by a user. This data can be represented in terms of numeric ratings or in a boolean like-dislike format. Ratings are profoundly used in collaborative filtering as they are quantifiable and convey the user’s positive or negative preference towards an item. One of the major disadvantages of explicit rating is that it is not easily obtainable and hence recommendation system usually relies on implicit feedback.</p><p>A lot of user behavior, which is not explicitly expressed by the user, is considered implicit feedback. Even though implicit feedback is more readily available, compared to explicit feedback, it cannot give any information about the negative preferences of users. If a user has not interacted with an item, it is not conclusive that the user dislikes it.</p><p>Both implicit and explicit feedback have their own pros and cons. It depends on the machine learning algorithm and the availability of data to opt for the right feedback for your recommendation system.</p><p><strong>Recommendation system techniques</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Z6kd9-RJOehZINaXy-wP6w.png" /><figcaption>Figure 1: Different techniques to build a recommendation system</figcaption></figure><p>The most common approaches to build a recommendation system are shown in Figure 1 above, namely collaborative filtering, content-based filtering, and hybrid approach. The collaborative filtering is divided into memory-based and model-based approaches. The memory-based approach is further classified into user-based and item-based approaches. When content and collaborative filtering are used in arecommendation systems, then it forms a hybrid system. A combination of memory-based and model-based approaches in a recommendation system is called a hybrid approach in collaborative filtering.</p><p><strong>Content-based filtering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*LlEj_XaWFCCYj75e_vyelA.png" /><figcaption>Figure 2: Content based recommendation system</figcaption></figure><p>Content based filtering uses user and item descriptions or features to filter the information and provide recommendations to the users. It is assumed that, if a user likes an item, then other items with similar attributes might also be of interest to the user. A simple depiction of the content-based filtering is displayed in Figure 2 above. Here Item A and Item B are similar due to their specification and hence grouped together. Since User X has preferred Item A in the past, the similar Item B is recommended to the user. Usually, a user profile is created based on the items liked in the past and then compared with the specification of other items. If the similarity between the user profile and a particular item is strong enough, then the item is recommended to the user.</p><p><strong>Collaborative filtering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*XS5js9QyYJ1ooRt9W2oYlg.png" /><figcaption>Figure 3: Collaborative filtering recommendation system</figcaption></figure><p>The collaborative filtering approach is one of the most popular techniques in the recommender system. The items are recommended to users based on the likeness of user preference. Collaborative filtering analyses different users and their preferences towards an item and tries to identify the correlation among them. If users have given similar ratings and prefer the same set of items in similar way, then they are considered similar users. Here it is assumed that if two users highly prefer the same set of items, then there is a high probability that they may like other items in a similar manner. The similar users are grouped together, and the items preferred by them are recommended to each other. This method is depicted in Figure 3, where Item A and Item B are preferred by both users, User X and User Y, and hence considered similar users. Now the Item C, which has not been rated by the User Y but highly rated by similar User X, is recommended to the User Y.</p><p><strong>Memory and model-based filtering</strong></p><p>The memory-based approach can be classified into user-based, and item-based approaches. In a user-based approach, the users are grouped based on their preferences forming a user neighborhood. An item is recommended to the user if it is highly preferred by users in the same group. The similarity between the users in the same group is calculated using the correlation between the rating vector of the main user and other users. In the item-based approach, similar items are grouped together and form the neighborhood. A user is recommended with items that are in the same group as a highly preferred item.</p><p>In model-based filtering, machine learning algorithms are used, and the model is trained to predict the possible user rating by a user on an item. One of the methods is the latent factor model, which gives the rating based on latent factors which are inferred from the rating pattern. One of the most common methods to implement a latent factor model is by using matrix factorization. It represents items and users in vector format of latent factor. Matrix factorization can be used for both implicit and explicit Feedback.</p><p><strong>Hybrid recommendation system</strong></p><p>A hybrid recommender system combines collaborative and content-based filtering approaches to recommend items to the users with improved accuracy and efficiency. This approach overcomes the shortcoming of other techniques used in the recommender system. For instance, the hybrid approach handles the cold start and sparsity problem of collaborative filtering by providing recommendations using content-based filtering. On the other hand, it also solves the overspecialization problem.</p><p><strong>Conclusion</strong></p><p>In recent years, recommendation systems have generated a large number of benefits such as assisting users with improved decision-making processes in reduced time, enhancing customer experience and increasing conversion rate and revenue for online businesses. Excessive information and choices in today’s digital world has necessitated the implementation of an intelligent system that can recommend items to users based on their preferences, saving time and cost.</p><p>Recommendation systems come with several limitations such as scalability, sparsity, cold start and overspecialization problems. These limitations can cause inaccuracies and poor performance of the recommender system and hence need to be handled and evaluated carefully.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc87d7b10b3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/a-general-understanding-of-recommendation-systems-and-their-techniques-bc87d7b10b3d">A general understanding of Recommendation systems and their techniques</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS EMR Schedulers Explained]]></title>
            <link>https://medium.com/machine-learning-reply-dach/aws-emr-schedulers-explained-a6930335787b?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/a6930335787b</guid>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[emr]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Oleksandr Makarevych]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 09:35:45 GMT</pubDate>
            <atom:updated>2023-02-09T09:35:45.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGHkpxzlnzwfR6yBG1JgWw.jpeg" /></figure><p>AWS (Amazon Web Services) is a popular choice for cloud applications due to its scalability, reliability, and security. AWS offers a wide range of services such as Elastic Compute Cloud (EC2), Simple Storage Service (S3), and Elastic Block Store (EBS), which allows developers to easily build, deploy, and scale their applications. Additionally, AWS offers various security features such as virtual private clouds and identity and access management to ensure that data and applications are protected. Furthermore, AWS provides a global network of data centers, which allows for low latency and fast data transfer, and it guarantees the high availability of services. AWS also offers a pay-as-you-go pricing model, which allows customers to only pay for the resources they use, making it a cost-effective solution for cloud applications. <br> <br>Amazon Elastic MapReduce (EMR) is a fully managed big data processing service in AWS that has come a long way in recent years. It now supports a wide range of big data processing frameworks, including Apache Hadoop, Apache Spark, Apache Hive, Apache Pig, and Apache HBase, among others. This allows users to easily run and process big data workloads on a fully managed cluster without the need for complex infrastructure setup and maintenance. <br>One of the major advancements in EMR is the integration of managed services, such as Amazon S3, Amazon DynamoDB, and Amazon Kinesis, which allows users to easily store and process large amounts of data in a cost-effective and scalable manner. Additionally, EMR now provides built-in support for machine learning and data visualization tools such as Amazon SageMaker and Amazon QuickSight, making it easier for data scientists and analysts to gain insights from big data. <br>EMR also now provides an easy-to-use web interface, the EMR console, which allows users to easily set up, configure, and monitor their clusters without the need for a command line or programming skills. This makes it easy for even non-technical users to set up and run big data workloads on EMR. <br> <br>Another important aspect of EMR is its ability to provide flexible scheduling options. Schedulers play a critical role in managing the allocation of resources in Amazon Elastic MapReduce (EMR), the fully managed big data processing service in AWS. They help ensure that resources are used efficiently and that jobs are completed in a timely manner, thus, providing a stable and reliable environment for running big data workloads. In this article, we will explore the different schedulers available in EMR and their use cases, with a focus on the Hadoop FIFO Scheduler, the Capacity Scheduler, and the Fair Scheduler. <br> <br><strong>The Hadoop FIFO Scheduler</strong> is the default scheduler in EMR and is based on the concept of first in, first out. This means that jobs are executed in the order they are received, with the first job in the queue being executed first. This scheduler is simple and easy to use, but it does not provide any advanced features or capabilities, such as resource allocation or job prioritization. It is best suited for simple, single-user clusters with a small number of jobs where there is no need for advanced features or fine-grained control over resource allocation. For example, if you have a small number of batch jobs running on the cluster and you want to ensure that they are executed in the order they are received, you can use the FIFO scheduler. <br> <br><strong>The Capacity Scheduler</strong>, on the other hand, is designed for use in multi-tenant clusters, where multiple users and applications are running on the same cluster. It allows users to specify their resource requirements and guarantees that each user will receive the resources they need to run their applications. The scheduler also supports the concept of queues, where users can specify their resource requirements at the queue level, rather than at the application level. This allows for better resource utilization and isolation between different users and applications. The capacity scheduler is particularly useful when you have multiple teams or departments sharing the same cluster and you want to ensure that each team has guaranteed resources and no team is affected by the other’s workloads. For example, if you have a large number of users running Spark jobs on the same cluster, you can use the capacity scheduler to ensure that each user gets the resources they need to run their jobs without affecting the performance of other users. <br> <br><strong>The Fair Scheduler</strong> is another popular choice in EMR, and it is designed for use in single-tenant clusters, where only one user or application is running on the cluster. It provides a fair sharing of resources between different jobs, based on the concept of fair sharing. This means that resources are allocated to jobs in a way that is fair to all users and applications, rather than being allocated based on the resources required by a specific job. The fair scheduler also allows configuring minimum and maximum resources for each pool and assigning a job to the pool accordingly. It is particularly useful when you have a single team or department using the cluster and you want to ensure that each job gets a fair share of resources without any specific job taking more resources than it needs. For example, if you have a large number of Hive queries running on the same cluster, you can use the fair scheduler to ensure that each query gets a fair share of resources without any query taking more resources than it needs. <br> <br>All these schedulers can be used in conjunction with different Hadoop applications such as Spark, Hive, and Pig. For example, when running Spark jobs, you can use the fair scheduler to ensure that each Spark application gets a fair share of resources, while also using the capacity scheduler to ensure that each user gets the resources they need to run their applications. Similarly, when running Hive queries, you can use the FIFO scheduler to ensure that queries are executed in the order they are received, while also using the capacity scheduler to ensure that each user gets the resources they need to run their queries. <br> <br>It’s also worth mentioning that all these schedulers can be fine-tuned and customized to better fit the needs of the application. For example, in the case of the Capacity Scheduler, you can configure the minimum and maximum resources for each queue, as well as set priorities for different queues, so that the most important jobs get the resources they need first. Similarly, with the Fair Scheduler, you can configure the minimum and maximum resources for each pool and assign jobs to the pool accordingly. Additionally, you can also configure the weight of each job or user, to ensure that the most important jobs get the resources they need first. <br> <br>Another important aspect to consider is the security of the cluster when using different schedulers. The FIFO scheduler does not provide any advanced features or capabilities in terms of security, while the Capacity Scheduler supports the concept of queues, where users can specify their resource requirements at the queue level, rather than at the application level, which can help in terms of security. The Fair Scheduler also allows to set up of pools for different users or teams and assigning jobs accordingly, which can help in terms of security as well. <br> <br>In addition, it’s important to take into account the scalability of the cluster when using different schedulers. As FIFO is the simplest scheduler, taking into account how it works, one wouldn’t use it when scalability is an important factor. The Capacity Scheduler is designed for use in multi-tenant clusters and it allows users to specify their resource requirements, which can help in terms of scalability. The Fair Scheduler is also designed for single-tenant clusters and it provides a fair sharing of resources between different jobs, which can help in terms of scalability as well. <br> <br>Finally, the monitoring and troubleshooting of the cluster is also an important aspect to consider when using different schedulers. The FIFO scheduler does not provide any advanced features or capabilities for monitoring and troubleshooting. The Capacity Scheduler and the Fair Scheduler both provide advanced features and capabilities for monitoring and troubleshooting, such as the ability to view the status of the cluster and the resources being used, as well as the ability to view the history of the cluster and the resources being used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjuZnAsQiGFIuE_-X-wGPQ.jpeg" /></figure><p><strong>In conclusion</strong>, when using Amazon Elastic MapReduce (EMR), it is important to consider the type of scheduler being used to manage the allocation of resources for the tasks and applications running on the cluster. Different schedulers have their own set of features and capabilities, and the choice of a scheduler will depend on the specific requirements of the applications running on the cluster. The Hadoop FIFO Scheduler is best suited for applications that require a straightforward execution order such as batch jobs, data processing jobs, or simple ETL jobs. The Capacity Scheduler is best suited for applications that have many users running on the same cluster, such as Spark jobs, Hive queries, and other big data processing jobs. The Fair Scheduler is best suited for applications that have a single user or team running on the cluster, such as Hive queries, Pig scripts, and other big data processing jobs. Additionally, it’s important to consider the fine-tuning, security, scalability, monitoring, and troubleshooting aspects when choosing the appropriate scheduler for an application. By understanding the capabilities and use cases of each scheduler, you can make an informed decision on which one to use for your big data workloads in EMR, and ensure optimal performance and resource allocation for your cluster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6930335787b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/aws-emr-schedulers-explained-a6930335787b">AWS EMR Schedulers Explained</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting the most out of Git: Improving your developer experience]]></title>
            <link>https://medium.com/machine-learning-reply-dach/getting-the-most-out-of-git-improving-your-developer-experience-52ca1b05ff70?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/52ca1b05ff70</guid>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Thomas Siedenhans]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 07:56:29 GMT</pubDate>
            <atom:updated>2023-01-26T15:40:14.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V77oXVdXiLpHt_4-HED4Bg.jpeg" /></figure><h3>Why you should care about advanced Git Features</h3><p>Git is a powerful tool that is widely used in the software development industry for version control and collaboration. It allows developers to track and manage changes to their code and maintain a history of all versions of their code. One of the key benefits of using Git in software engineering is its ability to handle large and complex codebases. With Git, developers can easily manage multiple versions of a codebase, making it easier to track and resolve conflicts when working on a project with multiple team members.</p><blockquote>You can think of Git as a tool for effective and efficient collaboration of code.<em><br></em>According to the latest StackOverflow Survey in 2022, more than <strong>96%</strong> of professional Software developers are using Git already.</blockquote><p>While working on different projects, I noticed that most developers are familiar with the basic concepts of Git, such as <strong>git fetch/pull/push/merge</strong>. These concepts are essential for working with Git and allow developers to collaborate on code with others in a very meaningful way already. <strong>However, it is an invaluable skill to gain a deeper understanding of Git and its advanced features.</strong></p><h3>What you could be missing out on</h3><p>As most developers are already familiar with Git, it might be easy to get comfortable with the existing knowledge about the topic and not worry about other approaches or maybe more ideal workflows. <br>In the end, it is important to get to your goal quicker: <em>Get the feature/bugfix/ etc. you worked on merged into the codebase.</em> The following areas are where I identified the biggest gain to be had from improving knowledge about certain Git-Features:</p><p><strong>Efficient Conflict Resolution:</strong> Conflict resolution strategies such as interactive rebasing are a huge help when contributing to a larger codebase and as a result, some people may struggle to resolve conflicts cleanly and effectively when not aware of this feature. As the interactive rebase is one of my favorite git features, I will go into more detail later in this article.</p><p><strong>Better codebase Management:</strong> A lot of developers may not be aware of advanced features such as submodules, git-lfs and git-flow. Those could help them manage and organize their codebase more efficiently, and support the work with large files and multiple versions of the codebase. As these topics are more constrained towards larger and composed repositories, I will focus more on parts where developers can gain more universally applicable knowledge.</p><p><strong>Improved Efficiency:</strong> Features such as stashing and bisecting, can save a lot of time by allowing you to quickly switch between different tasks, and help troubleshoot issues more efficiently. You will be pleased that we explore some of these concepts in the later parts of this article.</p><p><strong>Better Code Auditing:</strong> One lesser-known concept is the idea that the Git SourceTree can be used to understand how the codebase has evolved over time, and to identify the source of bugs or issues. I have to mention one <a href="https://www.youtube.com/watch?v=w9YhmMPLQ4U">amazing talk from Adam Tornhill</a> on this topic and other aspects of technical debt. He goes into further detail on how we can utilize Git for more efficient analysis of complex code pieces, which might be in the need to be refactored and also how to make the offboarding of a valuable team member a way better experience for the teams&#39; efficiency. Amazing and valuable content!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cI4c1lgkfknOokWF423e9w.png" /></figure><h3>Interactive Rebase</h3><p>Personally, this is one of the features I enjoy the most while working with git. You get the possibility to <strong>rearrange, squash, drop, edit, … </strong>commits as you desire.</p><p>Assuming you have the following 4 commits in your branch:</p><pre>6d9c37b HEAD@{0}: commit: badly worded refactoring<br>05f8e5a HEAD@{1}: commit: Important bugfix<br>a9f4c34 HEAD@{2}: commit: just an addition to the bugfix<br>29f2311 HEAD@{3}: commit: this commit can be dropped</pre><p>By running the following command you can start the interactive rebase (in this case you want to rebase your existing branch on the dev branch)</p><pre>git rebase -i origin/dev</pre><p>The following “git-rebase-todo” file will open in your standard text editor (we will close it after inserting our commands):</p><pre>pick 6d9c37b badly worded refactoring<br>pick 05f8e5a Important bugfix<br>pick a9f4c34 just an addition to the bugfix<br>pick 29f2311 this commit can be dropped</pre><p>There is a <a href="https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History">multitude of very useful commands</a> to use when altering these commits, but seeing the changes here I would resort to the following ones: The first commit is worded badly, so we can write “<em>reword</em>” instead of “<em>pick</em>” to get an opportunity to reword this. (Your coworkers and your future self will thank you for this 😊) We also notice that commits 2&amp;3 are both the same bugfix, the 3rd commit is just a small addition we might have forgotten in the first commit. To fix this, I would use the “<em>fixup</em>” command instead of “<em>pick</em>” for the commit <em>a9f4c34</em>. This will merge that commit into the previous one, keeping only the commit message of that branch. If you want to keep the second commit message, use “<em>squash</em>” instead of “<em>fixup</em>”. Furthermore, we notice that the last commit was a failed try and we want to drop these changes without cluttering our commit history any further.<br>For that commit, we change “<em>pick</em>” to “<em>drop</em>” which removes that commit.<br>This is how our file will look after the adjustments:</p><pre>reword 6d9c37b badly worded refactoring<br>pick 05f8e5a Important bugfix<br>fixup a9f4c34 just an addition to the bugfix<br>drop 29f2311 this commit can be dropped</pre><p>Afterwards, save and close this <em>git-rebase-todo</em> file and the rebase will start. You will be prompted with an input to provide an alternative to the badly worded commit, where we stated that we wanted to rename it instead. After closing that file, we are done and have our branch tidied up and up to date with the dev branch!</p><blockquote>We just rewrote Git-history!</blockquote><p>That’s why we have to force-push our changes with</p><pre># &quot;git push -f&quot; works, if you are working in your branch on your own<br># To be sure, we will use the safe option (while working in a team):<br><br>git push --force-with-lease</pre><p>For that reason, some developers have a harsh stance on <strong>merging </strong>vs <strong>rebasing </strong>in Git to streamline different branches. After having engaged in a few of these conversations and having used both merging strategies, I adopted the following approach: <br>In a branch where you are working alone without others depending on your commit history (e.g. a feature or bugfix branch where you work and finish your task usually alone) it is much more comfortable to use the (interactive-)rebase to polish your commit history and to avoid having a merge commit in your own branch when resolving Conflicts with the parent branch.<br><strong>But: </strong>As stated, rebasing is essentially “rewriting history”. I would not do it in a branch where other developers are basing their work off. A very good example of this is the development branch. I would not squash/drop/rewrite commits for that branch, as it would be confusing to other developers when they want to merge their changes back into this “common ancestor” branch.</p><h3>Git reflog</h3><p>The Git reflog command is a valuable tool for viewing the history of a Git repository. It shows a list of all the recent changes to the <strong>local </strong>repository, including branch updates, changes to the HEAD reference, and other actions. This can be useful for tracking down <strong>when </strong>a particular change was made, or <strong>recovering a lost commit</strong>.</p><p>For example; you have made some changes to your repository and you want to view the history of those changes. You could use the following command to view the reflog:</p><pre>git reflog</pre><p>This might produce output like the following:</p><pre>6d9c37b HEAD@{0}: commit: Added a new feature<br>05f8e5a HEAD@{1}: commit: Made some changes to the code<br>a9f4c34 HEAD@{2}: commit: Fixed a bug</pre><p>This shows that three commits were made recently (I hope you noticed that the commit messages were not ideally worded 😉), in the order shown. The <em>HEAD@{0}</em> entry refers to the most recent change, and each subsequent entry refers to an earlier change.</p><p>For example, if you wanted to revert to the “Fixed a bug” commit shown above, you could use the following command:</p><pre>git reset — hard a9f4c34</pre><p>This would reset the local repository to the state it was in when the “Fixed a bug” commit was made, and all the changes made since then would be discarded. This can be a useful way to undo a series of mistakes, e.g. to recover from a failed experiment.</p><p>Since the changes to the local repository get shown, this is also an amazing tool to recover lost commits, for example those of a deleted branch. In that case you would check which of the shown commits you want to recover and perform a cherry-pick:</p><h3>Git cherry-pick</h3><p>Git’s cherry-pick command is a useful tool for <strong>selectively applying changes from one branch to another.</strong> It allows you to choose specific commits from a branch and apply them to your current branch, without merging the entire branch. This can be useful in a variety of situations, such as when you want to cherry-pick only a bug fix from one branch without applying other changes to your current branch, or when you want to pick only a few important changes from a large branch and apply them to your current branch.</p><p>For example, suppose you have a Git repository with two branches: dev and feature. The feature branch contains several commits, including a commit that fixes a bug. You want to apply the bug fix to your dev branch, without merging the entire feature branch. You could do this using the cherry-pick command, like this:</p><pre># switch to the development branch<br>git checkout dev<br># cherry-pick the commit that fixes the bug<br>git cherry-pick &lt;commit-hash&gt;</pre><p>This would apply the changes from the specified commit to the development branch, without merging the entire feature branch. You could then continue working on the development branch, knowing that the bug has been fixed.</p><p>You can also use the cherry-pick command to pick multiple commits at once. For example, if you want to cherry-pick the last three commits from the feature branch, you could use the following command:</p><pre># switch to the dev branch<br>git checkout dev<br># cherry-pick the last three commits from the feature branch<br>git cherry-pick feature~3..feature</pre><p>This would apply the changes from the last three commits on the feature branch to the development branch. You could then continue working on the development branch, with the changes from the feature branch incorporated.</p><p>It is also possible to cherrypick only the changes to a single file in a specific commit by specifying the filename with the <strong>-x </strong>flag, but this will most likely lead to merge conflicts at a later stage which have to be resolved manually.</p><h3>Git bisect</h3><p>Git bisect is a feature in Git that allows developers to <strong>find the commit that introduced a bug in the codebase by using a binary search algorithm</strong>. It works by allowing the developer to specify a “good” commit that doesn’t have the bug and a “bad” commit that has the bug, and then Git will automatically find the commit that introduced the bug by checking out the middle commit between the good and the bad commit and asking you to test if the bug is present in that commit.</p><p>If you have a rough understanding, that a specific but has been introduced between these 2 commits (which might have a multitude of commits between them):</p><pre><br> 6d9c37b Added a new feature # &lt;- The bug is already here!<br> … (possibly 100+ commits merged overnight)<br> a9f4c34 HEAD@{2}: commit: Fixed a bug # &lt;- You know the bug is NOT here!</pre><p>To find the exact commit, which introduced the bug, you would type</p><pre># git bisect start &lt;bad commit&gt; &lt;good commit&gt;<br>git bisect start 6d9c37b a9f4c34</pre><p>Following this command, git will select commits for you to test if the bug is present. If that is the case, type “<em>git bisect bad</em>”, if the bug is not present type “<em>git bisect good</em>”. This process will be repeated until you find the commit which introduced the bug you are hunting.</p><p>Thanks to the logarithmic scaling of the binary search, very large repositories with possibly over 1000 commits between the last “good” state can be searched quickly to find the commit that contains the bug.</p><h3>Git Worktrees</h3><p>Git worktrees are a feature of Git that allows you to have <strong>multiple working directories for a single Git repository</strong>. This allows you to work on multiple branches or versions of your code simultaneously, without having to switch between different local repositories or clone the repository multiple times.</p><p>To create a Git worktree, you can use the “<em>git worktree</em>” command. For example, if you want to create a new worktree for the “<em>development</em>” branch of your repository, you would run the following command:</p><pre>git worktree add ../development development</pre><p>This creates a new directory called “development” in the parent directory of your current repository and sets up a working tree for the “development” branch of your repository in that directory. You can now quickly check if some certain behavior is present on the “development” branch while continuing to work on e.g. the “<em>feature/XXX</em>” branch in your original repository. For me, this Git feature grew on me more and more, as I got to appreciate the time I saved by not having to either stash my changes and checkout (which can be a nuisance when going back and forth to check a multitude of changes) or clone and build the repository in another directory.</p><h3>Git Aliases</h3><p>Git aliases are s<strong>horthand commands that you can create to simplify and customize your Git workflow.</strong> They allow you to define a custom command that runs a series of Git commands or options under the hood.</p><pre>For example, you like to look at your working directory diff by typing something like <br> git diff --stat --color-words --ignore-all-space --find-renames --find-copies</pre><p>To create a Git alias to prevent you from having to type all these flags every time, you can use the “<em>git config</em>” command. For example, to create the “<em>dif</em>” alias described above, you would run the following command:</p><pre>git config --global alias.dif “diff --stat --color-words --ignore-all-space --find-renames --find-copies”</pre><p>Once you have created an alias, you can use it just like any other Git command. In the example above, you would type “<em>git dif</em>” to run your command.</p><p>Git aliases are a convenient way to streamline and customize your Git workflow. You could also use them to execute multiple git commands in sequence. By using them, you can save time and effort and make your Git experience more efficient and enjoyable.</p><h3>Where to go from here:</h3><p>I am aware that there are <strong>many more features of Git</strong>, where I did not go into further detail, but my main goal is to provide solid groundwork for you as a developer to gain confidence in your abilities to work with advanced Git features. I hope you learned <strong>one or two things</strong> and maybe even picked up a cool Git-Feature you did not know about.</p><p>If I made you interested in discovering more about Git as a tool I can recommend you to have a look at the official documentation, where you can dive deeper into more of the commands mentioned and even check out some features which were left out: <a href="https://git-scm.com/docs">https://git-scm.com/docs</a> .</p><p>For people who want to know more about the history of Git: There is an amazing Tech Talk from Linus Torvalds, who created Git for developers to have an easier time contributing to his Linux codebase, and especially for him to have an easier review process to code changes: <a href="https://www.youtube.com/watch?v=4XpnKHJAok8">https://www.youtube.com/watch?v=4XpnKHJAok8</a> <br>This talk is very interesting, amusing and somewhat edgy in the good old Linus Torvalds fashion, which many of you will enjoy. I highly recommend giving it a listen!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52ca1b05ff70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/getting-the-most-out-of-git-improving-your-developer-experience-52ca1b05ff70">Getting the most out of Git: Improving your developer experience</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to automate data quality checks in machine learning pipeline ?]]></title>
            <link>https://medium.com/machine-learning-reply-dach/how-to-automate-data-quality-checks-in-machine-learning-pipeline-cb8bc698c9bb?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/cb8bc698c9bb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sunitha Radhakrishnan]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 08:19:50 GMT</pubDate>
            <atom:updated>2023-01-24T08:19:50.270Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to automate data quality checks in machine learning pipelines?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*oFTlBqTPAzTmem1eilBBmQ.png" /></figure><h4><strong>Great Expectations do the magic for you!</strong></h4><p><strong>Introduction</strong></p><p>In the world of MLOps, the performance of a machine learning model is often a reflection of underlying data quality. In DevOps, the software developers perform unit testing for the existing features and integrate a new feature<strong>. </strong>Similarly, ML Engineers believe that running tests and adding new tests should be part of the ML model development and deployment process.</p><p>It is a good practice to implement data quality checks and code tests at any stage in the ML Ops pipeline. In the near future, one of the main focuses of MLOps would be to perform data testing and document the output of the model using open source tools/frameworks that can fulfill both goals. One such framework is <strong>Great Expectations. </strong>It is an open source framework that performs data validation, documentation and can also send notifications where the user can specify their expectations from the data in plain, interpretive statements. The main advantage is, it is very useful in projects to automate the data quality tests that leverage continuous integration and continuous deployment is a great fit for ML Ops workflow.</p><p><strong>Different methods of deploying Great Expectations in ML pipelines.</strong></p><ol><li>Leverage the ‘<strong>Great Expectations’ library </strong>to declare assertions to test data in a pythonic code environment or in an interactive environment. Expectations are nothing but data assertions. They are expressed as python methods and can be used directly on pandas or pySpark dataframe.</li><li>It offers a complete deployment of <strong>Great Expectation Data Context</strong> where an expectation suite is created and validated against the data. It is two separate processes. A set of expectations(data quality checks) are written together in a suite and can be stored in any remote location(For e.g.: S3 buckets, project folder, etc.). Then, the expectations are validated during runtime in an automated pipeline against an incoming batch of data. One of the advantages is that more than one batch of data can also be specified along the pipeline for validation. In this workflow setup, the framework allows you to write the validation results in ‘Data Docs’. This document is termed as data quality report that contains the assertions about your data and the results for each validation run which can then be supplied to stakeholders.</li><li>Great Expectations can be integrated even with any orchestration workflow setup like the <strong>Airflow in a production environment. </strong>When a machine learning pipeline is triggered by an Airflow DAG runner, a node loads the expectation suite to validate data either after every transformation step or at the end of a bigger DAG subset.</li><li>Last but not least, Great Expectation integrates well into the <strong>CI/CD pipelines</strong> to test the ingestion step and model code as code changes. Similar to the unit testing that the software engineers do, data scientists and data engineers use Great Expectations for various purposes: (i) to test the data they ingest from other teams or vendors and (ii) to validate the data that they transform as a step in the data pipeline in order to ensure the correctness of the transformations. One of the advantages is that in production pipelines, the same assertions/tests (Expectations) would work for both the fixed input and “real” data input since the Great Expectations refers to the “characteristics” of the expected output.</li></ol><p><strong>Leveraging Great Expectations in an automated retraining pipeline.</strong></p><p>It is time to focus on our implementation of this framework in order to perform data quality checks in an automated model retraining pipeline. When I say automated, this means that a machine learning model must be re-trained on an incoming dataset automatically on a scheduled basis and no more manual triggers should be done. As we all know, the accuracy of the model output is the result of the quality of the data that is being sent as input to the model. Here comes a rise to then <strong>perform data quality checks automatically</strong> before determining the rules for model retraining.</p><p>Steps:</p><ol><li>Deploy Great Expectations in your project folder using the command:</li></ol><blockquote><em>great_expectations init</em></blockquote><p>This will initialize the framework under the project directory and it will have the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*dF1t1QgiHHLo-wHD-tFHWA.png" /></figure><p><strong><em>NOTE</em></strong><em>: While productionizing, If you don’t want some files from the initialization or if some files are useless to your use case you can ignore them using .gitignore.</em> <em>There might be challenges when deploying in a dockerized container.</em></p><p>2. Firstly you need to configure the <em>great_expectations.yml</em> file. In this file, we can specify the data sources, stores, data docs, etc. according to the use case. This is the starting point where the great expectation’s data context is processed. In simple words it means, it takes in the data set mentioned by the user and is ready to process them in GE context.</p><p><em>An example of great_expectations.yml file with ‘filesystem’ as datasource is configured below:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*J1pYR7eLfhtnoC6NuYbkpQ.png" /></figure><p>3. Configure a python method to perform data_quality_checks by importing DataContext from GreatExpectations. Additionally, BatchRequest can be imported to perform quality checks on a single batch of data or multiple batches from GE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*IIEtWzBZwOk0__kTpk1c8A.png" /></figure><p>4. Create an expectation suite where you can declare the set of expectations or in this case the data quality checks that you want to perform for your dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dpgudr4XIDLB6dy0waXFvg.png" /></figure><p>5. Create a batch request and specify the datasource, data connector and data asset name when you have multiple datasources configured. Here is an example of creating a BatchRequest for all the batches associated with DataAsset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*VD_d3ErbciBgiaQklqL6SA.png" /></figure><p>6. Using a Validator, we can validate the batch of data against the expectation suite created. Basically getting access to the batches via a validator and running expectations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Xjj4y18tpRoqnJ41ZDe6KQ.png" /></figure><p>There are other parameters that the user can include according to the requirements. For e.g.: datasource_name, data_connector_name, data_asset_name, etc.</p><p>7. The final step would be running the expectations by calling the python methods(provided by the GE) to validate the data and store the results in data docs format. For e.g.:</p><blockquote>validator.expect_table_row_count_to_be_between()</blockquote><blockquote>validator.expect_column_values_to_not_be_null()</blockquote><blockquote>validator.expect_column_values_to_be_in_set()</blockquote><blockquote>validator.expect_column_to_exist()</blockquote><blockquote>validator.expect_column_values_to_be_unique()</blockquote><p><strong><em>NOTE</em></strong><em>: The above methods are called either without the arguments or with the arguments of the columns or values of your dataset.</em></p><p>8. The results in this implementation are stored in a dictionary so that they can be easily integrated with lambda payloads. The results contain both successful and failed expectations. This means that the data that is successfully validated against the expectation suite are termed as result: ‘success’ and the ones that did not meet the expectations criteria are flagged as result: ’failure’. It also gives a detailed list of why the quality check failed. Below is a sample of a failed expectation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*IXwROb3JOIQwkjrGvPtAOw.png" /></figure><p>9. The above steps and lines of code are wrapped in a function and then integrated with <strong>AWS Lambda</strong>.</p><p>10. Finally, the results of the expectations are also sent to our project SLACK channel as alerts which are also configured as part of the above python method and specified under great_expectations.yml file. For the steps to integrate results with your slack, please take a look at GE official documentation and follow a similar process.</p><p>There are a lot of other additional work in this use case which is beyond the scope to discuss in this blog.</p><p><strong>Challenges faced while deploying Great Expectation in AWS Lambda:</strong></p><p>AWS Lambda is the most used serverless environment in most of the projects that aim to use an automated retraining pipeline. Since I was also using Great Expectations for the first time, I faced some difficulties while deploying the package and testing AWS Lambda function. As mentioned above, creating a data-context is the starting point for Great Expectations to work. Initially, the DataContext was using the local filesystem path and AWS Lambda was not able to recognize the path of the context. We must remember that AWS Lambda is <strong>ephemeral storage </strong>and uses a <strong>temporary file system /tmp </strong>to store the folder or the files that are created in runtime. Though in this use case, the AWS Lambda was wrapped in a docker container, the former applies to both scenarios. The solution was to replace the local filesystem path of the GE DataContext with the temporary file system path as shown below:</p><blockquote>ge_context = DataContext(“/tmp/great_expectations”)</blockquote><p><strong>Summary</strong></p><p>It is interesting to know that there are a lot of different components that this tool offers when it comes to data quality perspective. This would be useful for the MLOps guys to play around with this tool for sure if they want to setup an automated pipeline.</p><p>Some remarkable points to note are, Great Expectations can be integrated with different DAG execution tools like <a href="https://spark.apache.org/">Spark</a>, <a href="https://airflow.apache.org/">Airflow</a>, <a href="https://www.getdbt.com/">dbt</a>, <a href="https://www.prefect.io/">prefect</a>, <a href="https://github.com/dagster-io/dagster">dagster</a>, <a href="https://github.com/quantumblacklabs/kedro">Kedro</a>, <a href="https://flyte.org/">Flyte</a>, etc. Additionally, with Databricks, MySQL, AWS Redshift, AWS S3, Lambda, BigQuery, etc., With these many integrations, productionizing the data quality aspect becomes easier since in most projects it is all about continuous integration and continuous deployment. Though there are many pros, we can also foresee some cons. When I came across the “expectations gallery” there are some expectation classes or methods still in the Beta or early Beta testing phase. They are yet to deploy some expectations/quality checks to production. This could be somewhat of a discomfort for us as they often roll out different versions. We should make sure that we migrate our code to the latest version released by Great Expectations community. For instance, I experienced an issue with using their V2 API at the initial stages and then came to know about their latest release V3 API when I figured some parts of my code did not work as expected. Henceforth, I had to migrate the code snippets to V3 API with reference to the new docs. These are some of the cons that one can take care in the early stages while prototyping and take necessary precautions before running into complications.</p><p><strong>Conclusion</strong></p><p>Great Expectation is a great framework to perform data quality checks in a very flexible and easily extendable way. Expectations can also be customized and new python methods or classes can be defined to perform some specific data quality checks if demanded by the project or the use case. Additionally, this package offers different components that are worth exploring and exploiting! It saves time when testing locally and productionizing the same in the pipeline. The slack community is always there to guide you along the way while playing with the tool. It is going to be a win-win situation for us as they do continuous development to the Great Expectations API while we continue to consume the different features actively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb8bc698c9bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/how-to-automate-data-quality-checks-in-machine-learning-pipeline-cb8bc698c9bb">How to automate data quality checks in machine learning pipeline ?</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Business applications of Deep Neural Networks]]></title>
            <link>https://medium.com/machine-learning-reply-dach/business-applications-of-deep-neural-networks-6827b6abe280?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/6827b6abe280</guid>
            <dc:creator><![CDATA[Arnau Jiménez]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 09:09:47 GMT</pubDate>
            <atom:updated>2022-12-22T09:38:10.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQM4OEUTXDPqvzhMgOyagg.png" /></figure><h3>Some words about Neural Networks</h3><p>Machine learning is all about learning patterns from the data, if your data contains a pattern, choosing the right algorithm will likely figure it out and you will be able to generalize to new cases your algorithm has not seen before. In machine learning we have several algorithms: random forests, support vector machines, logistic regression, etc. Depending on the kind of data you have, people have shown that specific algorithms perform better than others, therefore we do not have a universal algorithm that can be applied to any kind of data you can think of. Today we are going to talk about neural networks and in which kind of business cases (and which kind of data) these have been shown to be particularly useful. As a rule of thumb I would say that when the structure of the data is really complex, neural networks seem to outperform other machine learning methods.</p><p>So first of all, what is a neural network and how does it differ from other algorithms? Well, neural networks as well as other algorithms like decision trees are known to be <strong>universal function approximators</strong>. In Lyman terms this simply means that if your algorithm has enough free parameters you should be able to map any input to any output: i.e. capture any kind of pattern, given that you have enough data to train the algorithm.</p><p>A neural network is a succession of one or more layers where each layer takes the input of the previous one and passes its output to the next one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mTykrbfVsijpjupM.png" /><figcaption>Architecture of a vanilla one layer neural network. Image taken from Wikipedia.</figcaption></figure><p>The image above displays the architecture of a really simple one layer neural network. So let me illustrate it with an example. Let’s assume that the two initial green nodes contain the <em>height</em> and <em>weight</em> of a person. Then we pass this information to the middle layer with blue dots, some mathematical operations take place there and they pass the results to the final yellow node. Finally in the yellow node we get a number, we can then for example say, if the number is bigger than some threshold <em>x </em>our algorithm predicts that the person is overweight. Of course this is a dumb example, because we can calculate this simply with a simple fraction, but I think it illustrates good the mechanics of how a neural network operates.</p><p>The architecture is up to you, i.e. the number of neurons in each layer and how the layers are connected. Each of these connections are called <strong>weights </strong>and these are the free parameters that you are going to optimize to get the approximator you want. Of course depending on how you choose your architecture, this will have a huge impact on the performance of your network. In the following sections we will talk about a couple of the <em>must know</em> deep learning architectures by 2022.</p><h3>Why Deep Neural Networks?</h3><p>The adjective “deep’’ in deep neural networks, comes from the fact that a neural network can have several layers, so each layer takes the input of the previous one and passes its output to the next one. Neural networks which have several layers in contrast to one-layer neural networks are referred as <strong>Deep Neural Networks</strong>.</p><p>In principle one layer neural networks are already universal function approximators, then why do we talk about deep neural networks at all? Well it turns out that deep neural networks seem to have been empirically more generalizable and easier to train compared to shallow/one layer neural networks. This seems to be related to the fact that each layer detects a set of features and the next layer will use those detected features to create even more higher level features. A well known example that illustrates this are Convolutional Neural Networks (or CNN for short). In a CNN the first layers detect simple patterns, like edges, the layers afterwards will detect if the edges cross somewhere and the final layer will detect if that corresponds to the picture of a table.</p><p>Hopefully the following image helps you to understand the explanation of the previous paragraph better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*e1lOdO9xMKlnZAKw.jpg" /><figcaption>Features per layer. Image from NVIDIA.</figcaption></figure><h3>Convolutional networks and computer vision</h3><p>In 2012 the CNN named <a href="https://paperswithcode.com/method/alexnet">AlexNet</a> won the <a href="https://www.image-net.org/index.php">ImageNet</a> challenge dropping the classification error from 26% to 15%. Since then the same competition has been won by other CNNs year after year. Therefore convolutional neural networks have become the state of the art for many computer vision tasks like image classification or image segmentation.</p><p>The key ingredient of these kind of networks is that every layer uses an operation called <strong>convolution</strong>. Convolutions have been there way long before deep learning, in fact the first discovery of convolutions as a mathematical operation come back to the 18th century which, and of course, had to be discovered by one of the greatest mathematicians of all times — if not the greatest — Leonhard Euler.</p><p>Why are convolutions so important to image processing? This is because convolutions display a set of <strong>symmetries</strong> that we expect to be there in our algorithm. In particular convolutions display <strong>translation equivariance</strong> in both dimensions of the image (horizontal and vertical). So instead of expecting our algorithm to learn those, we already impose them in our initial architecture. This is an example of what is known in the machine learning community as <a href="https://arxiv.org/pdf/1806.01261.pdf"><strong>inductive bias</strong></a>. Furthermore convolutions reuse the same parameters for the whole image, making the neural network much more lightweight and easier to train compared to a fully connected vanilla neural network for the same purpose.</p><p>In some sense we are creating a shortcut there, we expect that if we start with a fully connected neural network and we train it for a long enough time it should end up discovering these symmetries and creating those layers itself. Instead we are going to help the neural network and start from an already “advanced” stage of its training.</p><p>Again, if you want to learn more about the specifics of CNNs there are plenty of amazing resources out there which would be a waste of time to redundantly repeat in another medium post. If you are interested on them I recommend you this great article about CNNs: <a href="https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/">An Intuitive Explanation of Convolutional Neural Networks</a>.</p><p>These are some of the applications of convolutions neural networks in computer vision:</p><ul><li><strong>Medical imaging</strong>: Time is short and specialized physicians (e.g., radiologists) often cannot keep up with patient demand. This ends up resulting in long waiting times which prevents patients from getting an early diagnosis. CNNs can’t offer a full solution, but can decrease significantly the time before a diagnosis and the amount of human resources to get there. An important problem faced by CNNs in medical imaging is its lack of explainability. So as you probably have heard already Neural Networks act pretty much like a black box, so they get trained but it’s usually almost impossible to translate to a human understandable process how the network decides to classify an image as a car and not as a truck, and as a doctor you would like to be sure of the result before you prescribe any kind of potentially harming drug to a healthy individual.</li><li><strong>Self-driving cars</strong>: Self-driving cars need to be able to distinguish several objects in their surroundings, we need to make sure that we know where the road is, if we have cars around or if some human being is close to us for safety reasons. Not just this, but we also need to be able to interpret the signs in the street. Are the lights red? Is it allowed to go faster than 120 km/h? To solve all these problems self-drivings cars use an ensemble of algorithms that helps them to take decisions.</li><li><strong>Document identification/validation: </strong>You might be running a company where you want to classify documents or even validate national IDs or passports. In that case CNNs might be a good choice</li><li><strong>Face id: </strong>Apple started using CNNs for face identification as early as the iOS 10. Moreover we can also use these networks for other biometric data like fingerprints. As you can see, if you want a reliable way to identify your users CNNs can do the work for you.</li></ul><h3>GPT-3, Language models and transformers</h3><p>The famous paper <a href="https://arxiv.org/abs/1706.03762"><em>Attention is all you need</em></a><em> </em>revolutionized the world of Natual Language Processing (or NLP for short), presenting a new architecture, so-called <strong>transformer</strong>. Transformers are sequence to sequence models and this applies to languages, as a sentence is nothing more than sequence of words. The best introduction I have seen to transformers is by far the article from Jay Alammar: <a href="https://jalammar.github.io/illustrated-transformer/"><em>The illustrated transformer</em></a>. So if you want to go into more detail I encourage you to take a look at it.</p><p>Transformers have become the state of the art for NLP tasks, with incredible results to translate language, write essays, summarize text, answer questions and many more. Just go into the Playground of OpenAI <a href="https://beta.openai.com/examples">https://beta.openai.com/examples</a> and test the models with some simple Q&amp;A or text generation. If you feel lazy to set up the necessary things for the OpenAI playground you can start directly playing with the new AI chat from openAI: <a href="https://chat.openai.com/">https://chat.openai.com/</a></p><p>But the mechanism of self-attention which characterizes the transformer architecture seems to be quite universal. In recent years a lot of papers for computer vision have been using transformers, challenging the previous state-of-the-art CNN architecture. Here I am going to give you a couple more of examples where transformers are shining for their huge potential to revolutionize the Pharma industry:</p><ul><li><strong>Drug discovery: </strong>Nvidia and AstraZeneca collaborated to create an algorithm based on the transformer architecture for predicting how chemicals will react with each other and generate new molecular structures. Here you have the original article from Nvidia: <a href="https://blogs.nvidia.com/blog/2021/04/12/ai-drug-discovery-astrazeneca-university-florida-health/">Drug Discovery Gets Jolt of AI via NVIDIA Collaborations with AstraZeneca, U of Florida Health</a>.</li><li><strong>AlphaFold</strong>: When the paper of AlphaFold appeared for the first time, it shocked the entire scientific community, even the magazine Forbes published an article with the following header: <a href="https://www.forbes.com/sites/robtoews/2021/10/03/alphafold-is-the-most-important-achievement-in-ai-ever/?sh=469fac6b6e0a">AlphaFold Is The Most Important Achievement In AI — Ever</a>. What AlphaFold does is to determine the 3D structure of a protein from its aminoacid sequence. Apparently the proteins shape determines what it does and how it works, and this has a direct impact on inventing new medications which target those proteins. Alphafold is able to predict the structures for nearly all cataloged proteins known to science and this is huge. As by the year 2019 just a <em>small fraction</em> of them were known and it took a vast amount of human resources just to figure out one more. This is the original article in the magazine nature: .<a href="https://www.nature.com/articles/s41586-021-03819-2">Highly accurate protein structure prediction with AlphaFold</a></li></ul><h3>Cooling servers and deep reinforcement learning</h3><p>In contrast with most algorithms in Machine Learning, in Reinforcement Learning we train an algorithm which its most characteristic trait is that is able to take decisions by its own. The simplest example is playing a chess game, in reinforcement learning you train a so-called agent which depending on the distribution of figures on the board and possibly on the previous moves of your opponent the agent is going to take a decision and move one of the figures on the board. Of course we train the agent to maximize the likelihood of winning the game. In general there is always a goal we want to achieve and the success or failure depends on the strategy or set of actions taken by the trained agent.</p><p>In general reinforcement learning does not necessarily need to be coupled with deep learning, but again as explained in the introduction deep learning comes in handy when the complexity of the problem is quite high. Therefore for many real-life applications, like self-driving cars, reinforcement learning is going to take advantage of deep learning for a better performance.</p><p>DeepMind and Google have been using Deep Reinforcement Learning to optimize the <strong>cooling strategy</strong> of their servers. Until recently the data center team was in charge to continuously monitorize and take decisions on what to do once the servers started to warm up over a certain threshold. With the new AI algorithm, the team was not just able to reduce the energy consumption of the cooling system but also discovered strategies for cooling down the servers that they were not even aware of! If you want to know more about this amazing application of RL take a look at the original paper of DeepMind: <a href="https://arxiv.org/pdf/2211.07357.pdf">Controlling Commercial Cooling Systems Using Reinforcement Learning</a>.</p><p>Needless to say, reinforcement learning fits in perfectly in applications like <strong>autonomous driving</strong>, as the car (the agent) needs to constantly asses what is the next decision that he is going to take. Is he going to stop, accelerate turn to the right, to the left?</p><p>Another amazing application coming again from DeepMind is the <a href="https://ai.googleblog.com/2020/04/chip-design-with-deep-reinforcement.html?m=1">Chip Design with Deep Reinforcement Learning</a>. In this application DeepMind trained a RL agent to design chips which are suit specifically for ML purposes, reducing the chip design cycle time dramatically.</p><h3>Synthetic data, Art and generative models</h3><p>Until now we talked about models that take as input the type of data that we want to analyze and they output a result: be this classification, regression, segmentation, etc. These are known as <strong>Discriminative Models</strong> in contrast to the models we will talk in this section, the so-called <strong>Generative Models</strong>.</p><p>Generative models work a bit the other way around, so we start sampling from some random probability distribution (usually a Gaussian) and as output we get a data point that should be really “similar” to our training data. I think the most well-known example is the case of creating realistic faces using a Generative Adversarial Network (or GAN). Take a look at the following picture from the <a href="https://github.com/NVlabs/stylegan">StyleGAN</a> repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Lfk_kWzpFQea1EB" /><figcaption>All these faces do not belong to any real person. Photo taken from original repo: <a href="https://github.com/NVlabs/stylegan">https://github.com/NVlabs/stylegan</a></figcaption></figure><p>Maybe you can spot that some of the images seem to be a bit odd, but others you can’t really tell that they are produced from an algorithm and that the face does not belong to a real person.</p><p>These are generative models: you train them with a type of data, in this case faces of people, and at the end of the day they are able to produce samples so similar to the training data that it is hard to tell the difference.</p><p>There are several algorithms that belong to the category of generative models, the most well-known are GANs, VAEs, Normalizing Flows and Diffusion models (I recommend this <a href="https://lilianweng.github.io/posts/2021-07-11-diffusion-models/">article</a> for the mathematical avid reader). The important thing is to remember that these algorithms are able to create realistic, still synthetic data.</p><p>But why would synthetic data creation be useful? In Europe GDPR regulations might be quite strict for certain data and in general data related to health tends to be highly protected. Therefore the <strong>healthcare</strong> as well as the <strong>Pharma</strong> industry are two of the sectors that can benefit the most from <strong>synthetic data</strong>. As long as the privacy of the users is guaranteed you should be able to share synthetic artificial data that contains the correlations and characteristics that enable researchers to speed up research or drug discovery for example. There are already companies offering such services, for example <a href="https://gretel.ai/">gretel</a> offers a service to create synthetic data. Of course the more complex the data structure the harder it is to replicate it. If you want to create synthetic data from genomics, that can be quite a challenge as figuring out realistic combinations of DNA bases A, C, G and T as these sequences vary in size from hundreds to millions.</p><p>Another example could be in Art, I invite you to try the following models that create images from text: <a href="https://replicate.com/collections/text-to-image">https://replicate.com/collections/text-to-image</a>. Pretty cool huh?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6827b6abe280" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/business-applications-of-deep-neural-networks-6827b6abe280">Business applications of Deep Neural Networks</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Migrate to an Actively Maintained Web Framework]]></title>
            <link>https://medium.com/machine-learning-reply-dach/how-to-migrate-from-gwt-to-an-actively-maintained-web-framework-2da4e7cdd8d7?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/2da4e7cdd8d7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-web-toolkit]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-migration]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Simon Hellbrück]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 09:01:33 GMT</pubDate>
            <atom:updated>2023-01-10T08:08:32.228Z</atom:updated>
            <content:encoded><![CDATA[<p>An overview of Google Web Toolkit and reasons for a software migration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tv5ZBSmddVDKob--Xk2u7g.png" /><figcaption>From <a href="https://upload.wikimedia.org/wikipedia/commons/2/26/Gwt_logo.png">GWT</a> to <a href="https://positivethinking.tech/wp-content/uploads/2021/01/Logo-Vuejs.png">Vue.js</a>, <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Node.js_logo.svg/1200px-Node.js_logo.svg.png">Node.js</a>, <a href="https://www.datocms-assets.com/45470/1631110818-logo-react-js.png">React</a> or <a href="https://acquven.com/blog/02/images/angular.jpg">AngularJS</a>?</figcaption></figure><h3>Introduction: GWT and Our Customer</h3><p>While Google Web Toolkit (GWT) has long enjoyed great popularity, it can nowadays be considered outdated for a number of reasons. The problem with using this framework is not only that its popularity has been <a href="https://insights.stackoverflow.com/trends?tags=gwt%2Cvue.js%2Cnode.js%2Creactjs%2Cangular">steadily declining for years</a>, but also that there are clear cutbacks compared to modern frameworks in terms of maintainability, design and an active community. Features that were innovative at the time it was released (2006) are no longer a real advantage compared to modern web frameworks such as Vue.js, Node.js, React or AngularJS.</p><p>In our case, we have a client, who operates in the automotive, aerospace, defense and security industries. In our project, further development of a GWT application is desired, whose development started in 2009. Regardless of individual details, the fact that an application can no longer be debugged within a reasonable time is sufficient as a reason for a company to (at least) consider a software migration process. Especially if long-term support is needed.</p><p>Apart from that, further drawbacks are explained in detail below. In addition, related projects are presented and the current software architecture as well as a potential architecture at our customer’s in the future are explained in more detail.</p><h3>Drawbacks of GWT</h3><p>In theory, there are various reasons for migrating from GWT to a modern web framework. The most important, which have mainly emerged in the course of development during the project phase, are the following (in no particular order):</p><ul><li><strong>Debugging: </strong>There is no way to debug the frontend. Add-ons and plugins that were released a few years ago (such as <a href="https://chrome.google.com/webstore/detail/gwt-super-dev-button/piekceemifgeaigkimahdckfcikpmleh">GWT Super Dev Button</a> for Chrome or <a href="https://marketplace.eclipse.org/content/gwt-eclipse-plugin">GWT Eclipse Plugin</a> for Eclipse IDE) no longer work and are no longer updated.</li><li><strong>Building process: </strong>This problem arises directly from the previous one (debugging). Since there is no possibility of being able to see changes to the UI code directly on GUI elements, the entire application must always be rebuilt even for small tests, which can take 5–10 minutes depending on the CPU. Of course, build time can continue to increase as more code and tests are written.</li><li><strong>Look: </strong>The entire user interface is more reminiscent of Windows XP times than a modern web application. (Of course, this represents a subjective view of the author.)</li><li><strong>Unsupported libraries:</strong> Many libraries, such as Google’s Guava (yes, it is supported in theory, but certain parts such as data structures are overwritten by the internal compiler and thus not usable), cannot be used with the GWT compiler, pieces of code have to be completely rewritten or alternative data structures have to be implemented yourself.</li><li><strong>Outdated documentation: </strong>The <a href="https://www.gwtproject.org/usingeclipse.html">documentation</a> can be considered outdated because, among other things, it refers to a plugin that itself is outdated.</li><li><strong>Community: </strong>GWT has been an open source project since 2012 and as a direct result of the decline in popularity and the strong competition, further development and maintenance are very limited.</li></ul><h3>Existing Architecture</h3><p>The following graphic shows our customer’s software architecture. For the sake of simplicity, certain components can be classified in frontend or backend logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoZhgFFHCIn3zWxUlu3q4w.png" /><figcaption>Current Software Architecture</figcaption></figure><p>All the data, which in turn originates from an internal customer of our customer, is fed into a Maria database, which is made accessible to the Java application via a Java Database Connectivity (JDBC) driver. Since the use of free strings can be considered error-prone and an Object-Relational Mapping (ORM) such as Hibernate is not compatible with the remaining part of the software architecture, a query builder is used to create SQL strings. By that, the developer’s input is <em>validated</em> through the support of the IDE (i.e. disallowing SQL statements containing syntax errors).</p><p>Pieces of Java code at runtime are managed within the confines of containers and process requests by accepting them and sending an appropriate response. This part is handled by the Tomcat server. Interfaces form the connection between frontend and backend. Components of the graphical user interface are still programmed in Java, but represent the first code that interacts directly with user input. Of course, input validation is more than necessary (for usability as well as security reasons). UI Code written by the developer in Java is then converted into JavaScript and HTML code by the use of the GWT Cross Compiler.</p><p>Furthermore, to allow multiple developers to work on the code as well as to reduce <a href="https://www.gwtproject.org/articles/mvp-architecture.html">GWT test cases</a>, GWT applications are generally based on the Model-view-presenter (MVP) architecture. Here, the model contains the business logic, while the view does not have any logic and does not <em>know</em> what data it is displaying, but only has layout information. The presenter acts as a link between the model and the view. In the image above, “UI Components” can be considered as the view, “Interfaces” as presenters and “Servlet Containers” maintained by the Tomcat server as models.</p><h3>Related Migration Projects</h3><p>Field reports on software migration projects containing GWT can be found in several scientific papers as well as on blogs and websites. In the following, some of them will be presented briefly along with the technical methodology that was used.</p><h4>Migrating from GWT to Vue.js —<a href="https://www.filecloud.com/blog/2021/06/the-new-filecloud-experience-migrating-from-gwt-to-vue-js/"> FileCloud</a></h4><ul><li>FileCloud has decided to replace an outdated GWT application with Vue.js. FileCloud primarily praises Vue.js for the user experience as well as developer-friendly support from numerous libraries and an active community. The migration process was done manually by analyzing and converting pieces of code from the old application.</li></ul><h4>Making the Move from GWT to AngularJS —<a href="https://appdevelopermagazine.com/making-the-move-from-gwt-to-angularjs/"> Bandwidth</a></h4><ul><li>Brian Dill from Bandwidth highlights customer complaints as the primary reason for a software migration from GWT to AngularJS. But also the time-consuming Java-to-JavaScript compilation is an important point as well as boilerplate code and the difficulties to integrate graphic elements since GWT manages CSS and HTML code in different formats. In this case, the migration process was also carried out manually.</li></ul><h4>Migrating from GWT to Angular.js — <a href="https://www.research-bl.com/2019/03/23/automatic-software-migration-from-gwt-to-angular/">Berger-Levrault</a></h4><ul><li>Berger-Levrault, a French software publisher, made a successful attempt to semi-automatically convert 8 GWT applications, each with more than 1.5 million lines of code and more than 400 web pages, into AngularJS applications. That very project can be considered to be pretty much the largest migration project involving GWT which is discussed in <a href="https://ieeexplore.ieee.org/search/searchresult.jsp?newsearch=true&amp;queryText=gwt%20migration">several scientific papers</a> and blogs.</li></ul><p>Apart from industrial use cases, of course, there are many other blog entries and articles (<a href="https://medium.com/@stressed83/integrating-react-with-google-web-toolkit-gwt-8b6c0fb0e77b">Integrating React with Google Web toolkit (GWT)</a>, <a href="https://medium.com/@aldouille/how-to-integrate-react-into-a-java-legacy-gwt-client-b76d7614b7d5">How to integrate React into a Java legacy GWT client</a>, <a href="https://www.activeviam.com/journey-gwt-react/">Our journey from GWT to React</a>) about integrating a more modern framework into existing GWT applications.</p><h3>Our New Potential Architecture</h3><p>So, what does that mean for us? In the current project phase, GWT not only affects the development due to the already mentioned flaws but also due to a new requirement that involves the use of graphic elements. There is hardly any useful tool out of the box for GWT, yet there are numerous JavaScript libraries. There is one quick fix for this. JavaScript code can be passed to the GWT compiler via comments in order to make them usable. This feature is implemented through the J<a href="https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI">avaScript Native Interface (JSNI)</a> of GWT. See the below piece of code to get an idea. Note that Java methods are called within the JavaScript code again.</p><pre>public class JSNIExample {<br><br>  String myInstanceField;<br>  static int myStaticField;<br><br>  void instanceFoo(String s) {<br>    // use s<br>  }<br><br>  static void staticFoo(String s) {<br>    // use s<br>  }<br><br>  public native void bar(JSNIExample x, String s) /*-{<br>    // Call instance method instanceFoo() on this<br>    this.@com.google.gwt.examples.JSNIExample::instanceFoo(Ljava/lang/String;)(s);<br><br>    // Call instance method instanceFoo() on x<br>    x.@com.google.gwt.examples.JSNIExample::instanceFoo(Ljava/lang/String;)(s);<br><br>    // Call static method staticFoo()<br>    @com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/String;)(s);<br><br>    // Read instance field on this<br>    var val = this.@com.google.gwt.examples.JSNIExample::myInstanceField;<br><br>    // Write instance field on x<br>    x.@com.google.gwt.examples.JSNIExample::myInstanceField = val + &quot; and stuff&quot;;<br><br>    // Read static field (no qualifier)<br>    @com.google.gwt.examples.JSNIExample::myStaticField = val + &quot; and stuff&quot;;<br>  }-*/;<br><br>}</pre><p>However, the conglomerate of two programming languages ​​makes the code quite illegible. Not to say dirty. Although this method is already practiced in isolated cases, a larger integrated library would represent a completely new dimension. It is even likely that JavaScript code would gradually make up the bulk of the (Java) application, given that external libraries containing functionalities that GWT cannot provide will continue to be required in the future. The figure below illustrates the architecture of such an application including external JavaScript code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ScDhT7mFZ9OWdKAIJX8Og.png" /><figcaption>Using Java and JavaScript Altogether</figcaption></figure><p>Arguably the most charming and comfortable approach would be to adopt the automated mechanism used in the project for Berger-Levrault as it seems well documented on <a href="https://github.com/badetitou/Casino">GitHub</a> and, of course, appears to be the most time-saving solution. However, initial tests have shown that the technologies used are not well documented, let alone self-explanatory. Regardless of that, the desirable outcome would still be to replace the existing client code with lightweight JavaScript code via one of the popular frameworks as can be seen in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfkamx9XoIkJj7XVmBae7w.png" /><figcaption>Using a New Framework for the Frontend</figcaption></figure><p>Note that the Tomcat server containing the business logic as well as the existing code may be retained in the backend, while the new framework would be based on top of it. This approach would still mean that two programming languages ​​would be used in one application, but within logically separated blocks (frontend and backend). In addition, this solution saves converting many lines of Java code (roughly a quarter of the entire code of our application) during a potential migration process.</p><h3>Conclusion</h3><p>Web frameworks enjoy great popularity in simplifying the development of web applications. The big advantage of GWT at the beginning was that developers could concentrate completely on one programming language, namely Java, while the cross-compiler converted that code into standalone JavaScript files, which are highly optimized.</p><p>Whether a migration should ultimately be carried out should be agreed upon in close consultation with the customer, since such a project inevitably ties up resources that may be needed more urgently elsewhere. A possible compromise could be to create smaller prototypes alongside the ongoing development in order to be able to better assess the feasibility (in the case of a manual migration). Simplifying approaches such as low code no code could also be considered for this purpose.</p><p>Finally, a software migration is supposed to be about benefits for end users and not about the well-being of developers. But as already explained at the beginning, the potentially shortened build process and the associated faster delivery of new features as well as accelerated fixing of bugs already represent an immense advantage. Speeding up the development pace most probably represents the greatest advantage for end users as well as developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2da4e7cdd8d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/how-to-migrate-from-gwt-to-an-actively-maintained-web-framework-2da4e7cdd8d7">How to Migrate to an Actively Maintained Web Framework</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language Models and their Evolution]]></title>
            <link>https://medium.com/machine-learning-reply-dach/language-model-and-its-evolution-6c01cf26caf8?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/6c01cf26caf8</guid>
            <category><![CDATA[transformer-model]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Jasmine Padhye]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 09:16:24 GMT</pubDate>
            <atom:updated>2022-12-06T09:17:38.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9eyPcITvvx9RcWL2" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Natural Language Processing is one of the hot research topics that deals with extracting and understanding text data. The field has undergone significant growth in recent years, and one of the major contributing factors to this growth is the emergence of language models. This blog post gives an overview of what a language model is and how it has evolved over the years to become more powerful.</p><p>In simple words, a <em>Language Model (LM)</em> assigns a probability to a sentence, i.e a sequence of words. It determines how likely a sequence of words will occur. For example, the sentence <em>It is going to rain today</em> is more likely to occur than the sentence <em>Today is rain</em>. This example can be mathematically represented as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*r4BlyMlLclgqAdsOCCPdEQ@2x.jpeg" /></figure><p>But why do we need such probabilities? Getting these probabilities can be useful in different use cases such as <em>text summarisation</em> in which the input sentence is shortened without losing meaning, <em>question-answering</em> in which answers for a given question are extracted from the web/input text, <em>chatbots</em> in which computer communicates with humans and provides assistance, <em>text recognition</em> which converts text from image to textual data, and many more. The following examples show how these probability distributions can be useful.</p><h4>1. Machine translation: Translate input sentence from one language to another</h4><p>When a sentence from one language is translated into another, the order of words in the output sentence might need rearrangement, or some words might need replacement with more plausible words to make sense of the output. In the given example, <em>heavy rain</em> is more plausible than <em>large rain</em>. This probability helps in choosing the correct synonym during translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*4JisH2HzAdGWki0sitWLlg@2x.jpeg" /></figure><h4>2. Autocorrect: Suggest a correction for misspelled words or incorrect grammar</h4><p>When a word is misspelled, the probability of the given sequence drops. When this happens, the likelihood of a word that fits best with the given sequence can be suggested as the correct replacement. For example, the occurrence of <em>15 minutes</em> is much more probable than <em>15 minuets</em>. Autocorrect also considers which words from the most probable words need the least character replacement with the misspelled word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*-FrX01LrOV47D6Jd5K2mHw@2x.jpeg" /></figure><h4>3. Speech recognition: Convert input voice signal to text</h4><p>In speech recognition, many similar sounding words can be confused with each other. The likelihood of combinations of words is required to recognize which word was spoken correctly. For example, the probability of someone saying <em>I saw a cow</em> is much higher than saying <em>Eyes of a bow</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*auWiPzQXwznR_bBOde2w8g@2x.jpeg" /></figure><h4>4. Sentence completion: Suggest next words in the input sentence</h4><p>For sentence completion, the model needs to suggest the most likely word to occur given the current sequence of words. For example, a cheese pizza is much more likely to be ordered with <em>olives</em> than <em>rice</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*yt_AhnmCok20yno89XJjiw@2x.jpeg" /></figure><p>The methods of finding these probability distributions have improved tremendously in the last few years.</p><p>Our intuition tells us to find this probability distribution by applying the chain rule to the joint probability of a sentence. For example, to find the probability distribution of the sentence <em>I will not be able to attend the meeting</em>, we do the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*gFjYNug5WpxoJPkf-VTl7Q@2x.jpeg" /></figure><p>And we get these individual conditional probabilities as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*xisrdYnL-TJXHvWkfT9EDQ@2x.jpeg" /></figure><p>However, the issue with this approach is that we cannot have enough data for estimating these conditional probabilities for long sentences. These long term dependencies can be handled by simply limiting the number of words on which the next word depends. In other words, instead of computing <em>P(meeting|I will not be able to attend the)</em>, the dependency can be reduced to 2 words to compute <em>P(meeting|attend the)</em>. In NLP, this kind of prediction which is based on short history is called the <em>Markov assumption.</em></p><p>This assumption implies that the probability of the <em>n-th</em> word depends only on <em>n-1</em> words, and the words prior to that do not affect this probability. The <strong><em>N-gram</em></strong> language model is based on this assumption.</p><ul><li>Unigram model: probability of n-th word depends on 1–1=0 prior words</li><li>Bi-gram model: probability of n-th word depends on 2–1 = 1 prior words</li><li>N-gram model: probability of n-th word depends on n-1 prior words</li></ul><p>With the increase in <em>n</em>, looking back becomes more and more expensive. In addition, setting this hard limit on how far back to look results in completely forgetting the beginning of a sentence. To combat this limitation, <em>RNN-based</em> language models were developed allowing information to persist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*O87POQRWB7k9x87e5neQHg@2x.jpeg" /><figcaption>Unrolled Recurrent Neural Network</figcaption></figure><p>In a RNN model, one word is processed after another in a loop by the same neural network, which introduces the recurrent nature of the model as shown in the image above. At every step, the network processes the new input along with the information obtained from the previous step and passes it to the next step. This helps the network connect previous information with current information, which can help with tasks such as sentence completion. For example, if we want to predict the next word in <em>The cat drank ___</em>, the RNN based language model can easily connect <em>cat</em> and <em>drank</em> to <em>milk</em> as the prediction. However, this model also comes with its own limitations. When a sentence gets long, only the most recent information is not enough, and some context from earlier steps of the sentence is required for the prediction. For example, in the sentence, <em>I went to India to visit my parents and I ate ___</em>, the model can use the recent information <em>ate</em> to predict the next word to be a food item. However, the model needs to look even further back to <em>India</em> to predict a food item from Indian cuisine. When this gap between current steps and relevant information increases, the performance of RNN drops.</p><p>Similar to the training process on a simple NN, during the training of RNN, the weights are updated in the backward pass. The gradients during backpropagation flow backward across time steps. And with an increase in sentence length, the risk of facing exploding or vanishing gradients increases. These two issues of RNN-based language models were solved by using <em>LSTM networks</em>.</p><p>LSTMs are a special kind of RNNs that consists of so called long term memory. Unlike RNNs in which each cell consists of a single NN layer, a LSTM cell consists of 4 layers that decide which information to keep, which to forget and how much information to pass through. Using LSTMs can give a better performance than simple RNN as the network can hold relevant information for longer. However, training a LSTM network can be time expensive. Researchers developed another breakthrough approach, much simpler and faster than LSTM, called <em>Attention</em> which was proposed in a paper titled <em>Attention is all you need</em>.</p><p>LSTMs consist of gates for forgetting information. Unlike LSTMs, instead of actively deciding which information is not important, an Attention mechanism concentrates only a few things at every step while ignoring others. For example, if we want to predict a pronoun after <em>Jane is writing ___</em>, we only need to focus on <em>Jane</em> to predict the pronoun to be <em>her</em> and other information <em>is writing</em> can be ignored. Similarly, to predict the next word of <em>Jane is writing her ___</em>, the attention mechanism only focuses on <em>is writing</em> and gives <em>essay</em> as output, and it ignores other non-relevant information <em>Jane</em> and <em>her</em>.</p><p>The working of the attention mechanism idea can be visualized quite nicely during image captioning, as shown below. The different colors show the correspondence between underlined words and the attended region in the attention map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*Jc9dhX_AiY2dOwaGWunjeQ@2x.jpeg" /><figcaption>Source: arXiv:1612.01887</figcaption></figure><p>This attention mechanism was then adopted in a deep learning model with an encoder-decoder structure called <em>Transformers</em>. The encoder encodes the input sentence like in any encoder-decoder architecture. However, the attention mechanism helps the encoder to look also at other parts of the input sentence while it encodes a word. Similarly, it also helps the decoder to look at other relevant information while decoding.</p><p>A Transformer architecture does not contain any recurrence component and takes the entire input sequence simultaneously, which enables parallelizing the computation. This can help in faster training of a model with a huge number of parameters on a large corpus. Because of these advantages, Transformers created a massive impact in NLP and Computer Vision domain. BERT by Google, GPT by OpenAI, and their variants are some examples in NLP of such Transformer models with billions of parameters trained on large corpora using parallel computation power. Nowadays, when we talk about language models, we always refer to these powerful Transformer-based language models.</p><h3>References:</h3><ul><li>https://www.youtube.com/watch?v=rURRYI66E54</li><li>https://www.analyticsvidhya.com/blog/2019/11/comprehensive-guide-attention-mechanism-deep-learning/</li><li>http://jalammar.github.io/illustrated-transformer/</li><li>https://huggingface.co/docs/transformers/main/en/index</li><li>http://colah.github.io/posts/2015-08-Understanding-LSTMs/</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c01cf26caf8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/language-model-and-its-evolution-6c01cf26caf8">Language Models and their Evolution</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Introduction to the Amazon SageMaker Python SDK]]></title>
            <link>https://medium.com/machine-learning-reply-dach/a-practical-introduction-to-the-amazon-sagemaker-python-sdk-e38beea5dbaa?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/e38beea5dbaa</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Temiloluwa Adeoti]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 09:34:56 GMT</pubDate>
            <atom:updated>2022-12-01T09:34:56.562Z</atom:updated>
            <content:encoded><![CDATA[<p>An AWS Sagemaker tutorial</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AW9oDqVew9ogtvYZBU16Ng.png" /></figure><h3>Introduction</h3><p>On the 12th of October, 2022, I presented a Knowledge Share to my colleagues at <a href="https://www.reply.com/machine-learning-reply/de/">Machine Learning Reply GmBH</a> titled, <a href="https://www.slideshare.net/TemiReply/mldevelopmentwithsagemakerpptx">“Developing Solutions with Sagemaker”</a>. Knowledge Sharing is a tradition we observe weekly at <a href="https://www.reply.com/machine-learning-reply/de/">Machine Learning Reply GmBH</a> that helps us as consultants to develop a broad range of skill sets. There was little time to go delve into the Sagemaker Python SDK on the day. With this follow-up blog post, I would like to explore the Estimator API, Model API, Preprocessor API, and Predictor API using the AWS Sagemaker Python SDK.</p><h3>AWS Sagemaker Python SDK</h3><p>The Amazon SageMaker Python SDK is the recommended library for developing solutions in Sagemaker. The other ways of interacting with Sagemaker are the AWS CLI, Boto3, and the AWS web console. In theory, the SDK should offer the best developer experience, but I discovered that there is a learning curve and it is hard to hit the ground running.</p><p>This post walks through a simple regression task that showcases the important APIs in the SDK. I also highlight “gotchas” encountered while developing this solution. The entire codebase is found <a href="https://github.com/Temiloluwa/sagemaker_auto_mpg">here</a>.</p><h3>Regression Task: Fuel Consumption Prediction</h3><p>I selected a regression task I tackled as a budding Data scientist (<a href="https://github.com/Temiloluwa/ML-database-auto-mpg-prediction/blob/master/solution.ipynb">notebook link</a>): to predict the fuel consumption of vehicles in MPG (<a href="https://archive.ics.uci.edu/ml/datasets/auto+mpg">problem definition</a>). I broke down the problem into three stages:</p><ol><li>A preprocessing stage for feature engineering</li><li>A model training and evaluation stage</li><li>A model inferencing stage</li></ol><p>Each of these stages produces reusable model artifacts that are stored in S3.</p><h3>Sagemaker Preprocessing and Training</h3><p>Two things are king in Sagemaker: S3 and Docker containers. S3 is the primary location for storing training data and the destination for exporting training artifacts like models. The SDK provides <a href="https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_processing.html">Preprocessors</a> and <a href="https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html">Estimators</a> as the fundamental interfaces for data preprocessing and model training. These two APIs are simply wrappers for Sagemaker Docker containers. This is what happens under the hood when a preprocessing job is created with a Preprocessor or training job with an Estimator:</p><ol><li>Data is transferred from S3 into the Sagemaker Docker container</li><li>The Job (training or preprocessing) is executed in the container that runs on the compute instance you have specified</li><li>Output artifacts (models, preprocessed features) are exported to S3 when the job is concluded</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*QGVJmRGuXmeH8SRU" /></figure><p>This image depicts data transfer into and out of a preprocessing container from S3.</p><h4>Sagemaker Containers</h4><p>It is crucial to get familiar with the environmental variables and pre-configured path locations in Sagemaker containers. More information is found on the Sagemaker Containers’ <a href="https://github.com/aws/sagemaker-containers">Github page</a>. For example, Preprocessors receive data from S3 into /opt/ml/preprocessing/input while Estimators store training data in /opt/ml/input/data/train. Some environmental variables include SM_MODEL_DIR for exporting models, SM_NUM_CPUS, and SM_HP_{hyperparameter_name}.</p><h3>Project Folder Structure</h3><p>The diagram below shows the project’s folder structure. The main script is the python notebook auto_mpg_prediction.ipynb whose cells are executed in Sagemaker Studio. Training and preprocessing scripts are located in the scripts folder.</p><pre><br>├── Blog.md<br>├── LICENSE<br>├── README.md<br>├── auto_mpg_prediction.ipynb<br>└── scripts<br>    ├── model<br>    │   ├── inference.py<br>    │   └── train.py<br>    └── preprocessor<br>        ├── custom_preprocessor.py<br>        ├── inference.py<br>        └── train.py</pre><h3>Preliminary Steps</h3><p>Let’s start with initializing a Sagemaker session followed by boilerplate steps of getting the region, execution role, and default bucket. I create prefixes to key s3 locations for data storage, and the export of preprocessed features and models.</p><pre>import os<br>import json<br>import time<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd<br>import requests<br>import boto3<br>import sagemaker<br>from sagemaker import get_execution_role<br>from io import StringIO<br><br># initialize sagemaker session <br>sess = sagemaker.Session()<br>region = sess.boto_session.region_name<br>bucket = sess.default_bucket() <br>role = get_execution_role()<br><br># boto3 client<br>sm_client = boto3.client(&#39;sagemaker&#39;)<br><br>prefix = &quot;auto_mpg&quot;<br><br># raw data path<br>raw_train_prefix = f&quot;{prefix}/data/bronze/train&quot;<br>raw_val_prefix = f&quot;{prefix}/data/bronze/val&quot;<br>raw_test_prefix = f&quot;{prefix}/data/bronze/test&quot;<br><br># preprocessed features path<br>pp_train_prefix = f&quot;{prefix}/data/gold/train&quot;<br>pp_val_prefix = f&quot;{prefix}/data/gold/val&quot;<br>pp_test_prefix = f&quot;{prefix}/data/gold/test&quot;<br><br># preprocessor and ml models<br>pp_model_prefix = f&quot;{prefix}/models/preprocessor&quot;<br>ml_model_prefix = f&quot;{prefix}/models/ml&quot;<br><br><br>def get_s3_path(prefix, bucket=bucket):<br>    &quot;&quot;&quot; get full path in s3 &quot;&quot;&quot;<br>    return f&quot;s3://{bucket}/{prefix}&quot;</pre><h3>Raw Data Transfer to S3</h3><p>Next, we have to transfer our raw data to S3. In a production setting, an ETL job sets an S3 bucket as the final data destination. I have implemented a function that downloads the raw data, splits it into the train, validation, and test sets then uploads them all to their respective s3 paths in the default bucket based on pre-defined prefixes.</p><pre><br>def upload_raw_data_to_s3(sess,<br>                          raw_train_prefix=raw_train_prefix,<br>                          raw_val_prefix=raw_val_prefix,<br>                          raw_test_prefix=raw_test_prefix, <br>                          split=0.8):<br>    &quot;&quot;&quot;<br>    Read MPG dataset, peform train test split, then upload to s3<br>    &quot;&quot;&quot;<br>    # filenames<br>    train_fn = &quot;train.csv&quot;<br>    val_fn = &quot;val.csv&quot;<br>    test_fn = &quot;test.csv&quot;<br>    <br>    # download data<br>    data_url = &quot;https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data&quot;<br>    res = requests.get(data_url)<br>    file = StringIO(res.text)<br>    <br>    # read data<br>    data = pd.read_csv(file, header = None, delimiter = &#39;\s+&#39;, low_memory = False, na_values = &quot;?&quot;)<br>    data_frame = data.drop(columns = 8)<br>    data_frame = data_frame.fillna(data_frame.mean())<br>    data_frame = data_frame.rename(index = int, columns = {0: &quot;mpg&quot;, 1:&quot;cylinders&quot;, 2: &quot;displacement&quot;,3: &quot;horsepower&quot;, 4: &quot;weight&quot;, 5:&quot;acceleration&quot;,6:&quot;model year&quot;,7:&quot;origin&quot;})<br>    <br>    # train - test - split<br>    train_df = data_frame.sample(frac=split)<br>    test_df = data_frame.drop(train_df.index)<br>    <br>    # take the last 10 rows of test_df as the test data and the <br>    val_df = test_df[:-10]<br>    test_df = test_df[-10:]<br>    <br>    assert set(list(train_df.index)).intersection(list(test_df.index)) == set([]), &quot;overlap between train and test&quot;<br>    <br>    # save data locally and upload data to s3<br>    train_df.to_csv(train_fn, index=False, sep=&#39;,&#39;, encoding=&#39;utf-8&#39;)<br>    train_path = sess.upload_data(path=train_fn, bucket=bucket, key_prefix=raw_train_prefix)<br>    <br>    val_df.to_csv(val_fn, index=False, sep=&#39;,&#39;, encoding=&#39;utf-8&#39;)<br>    val_path = sess.upload_data(path=val_fn, bucket=bucket, key_prefix=raw_val_prefix)<br>    <br>    test_df.to_csv(test_fn, index=False, sep=&#39;,&#39;, encoding=&#39;utf-8&#39;)<br>    test_path = sess.upload_data(path=test_fn, bucket=bucket, key_prefix=raw_test_prefix)<br>    <br>    # delete local versions of the data<br>    os.remove(train_fn)<br>    os.remove(val_fn)<br>    os.remove(test_fn)<br>    <br>    print(&quot;Path to raw train data:&quot;, train_path)<br>    print(&quot;Path to raw val data:&quot;, val_path)<br>    print(&quot;Path to raw test data:&quot;, test_path)<br>    <br>    return train_path, val_path, test_path<br><br>train_path, val_path, test_path = upload_raw_data_to_s3(sess)</pre><h3>Stage 1: Feature Engineering</h3><p>The preprocessing steps are implemented using the Sklearn python library. These are the goals of this stage:</p><ol><li>Preprocess the raw train and validation .csv data into features and export them to s3 in .npyformat</li><li>Save the preprocessing model using <a href="https://scikit-learn.org/stable/model_persistence.html">Joblib</a>and export it to s3. This saved model will be deployed as the first step of our inference pipeline. During inferencing, its task will be to generate features (.npy) for raw test data.</li></ol><p>The Sagemaker Python SDK offers <a href="https://sagemaker.readthedocs.io/en/stable/frameworks/sklearn/sagemaker.sklearn.html#sagemaker.sklearn.processing.SKLearnProcessor">Sklearn Preprocessors</a> and <a href="https://sagemaker.readthedocs.io/en/stable/api/training/processing.html#sagemaker.spark.processing.PySparkProcessor">PySpark Preprocessors</a>. These are preprocessors that already come with Sklearn and Pyspark pre-installed. Unfortunately, I discovered it is not possible to use custom scripts or dependencies with both. Therefore, I had to use the <a href="https://sagemaker.readthedocs.io/en/stable/api/training/processing.html#sagemaker.processing.FrameworkProcessor">Framework Preprocessor</a>.</p><p>To instantiate the Framework Preprocessor with the Sklearn library, I supplied <a href="https://sagemaker.readthedocs.io/en/stable/frameworks/sklearn/sagemaker.sklearn.html">SKlearn estimator</a> Class to the estimator_cls parameter. The .run method of the preprocessor comes with a code parameter for specifying the entry point script and source_dir a parameter for indicating the directory that contains all custom scripts.</p><p>Pay close attention to how data is transferred into and exported out of the preprocessing container using <a href="https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProcessingInput.html">ProcessingInput</a> and <a href="https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProcessingOutput.html">ProcessingOutput</a> APIs. You will see how container (/opt/ml/*) and S3 paths for data transfer are specified. Note that, unlike Estimators that are executed using a .fit method, Preprocessors use a .run method.</p><pre><br>from datetime import datetime<br>from sagemaker.sklearn.estimator import SKLearn<br>from sagemaker.processing import FrameworkProcessor<br>from sagemaker.processing import ProcessingInput, ProcessingOutput<br><br>current_time = datetime.now().strftime(&quot;%d-%b-%Y-%H:%M:%S&quot;).replace(&quot;:&quot;, &quot;-&quot;)<br>TRAIN_FN = &#39;train.csv&#39;<br>VAL_FN = &#39;val.csv&#39;<br>TRAIN_FEATS_FN = &#39;train_feats.npy&#39;<br>VAL_FEATS_FN = &#39;val_feats.npy&#39;<br><br><br>sklearn_processor = FrameworkProcessor(<br>    base_job_name=f&quot;auto-mpg-feature-eng-{current_time}&quot;,<br>    framework_version=&quot;1.0-1&quot;,<br>    role=role,<br>    instance_type=&quot;ml.m5.xlarge&quot;,<br>    instance_count=1,<br>    estimator_cls=SKLearn<br>)<br><br>sklearn_processor.run(<br>    code=&quot;train.py&quot;,<br>    source_dir=&quot;scripts/preprocessor/&quot;,<br>    inputs=[<br>        ProcessingInput(source=get_s3_path(raw_train_prefix), destination=&quot;/opt/ml/processing/input/train&quot;),<br>        ProcessingInput(source=get_s3_path(raw_val_prefix), destination=&quot;/opt/ml/processing/input/test&quot;)<br>    ],<br>    outputs=[<br>        ProcessingOutput(output_name=&quot;train_features&quot;, source=&quot;/opt/ml/processing/train&quot;, destination=get_s3_path(pp_train_prefix)),<br>        ProcessingOutput(output_name=&quot;val_features&quot;, source=&quot;/opt/ml/processing/test&quot;, destination=get_s3_path(pp_val_prefix)),<br>        ProcessingOutput(output_name=&quot;preprocessor_model&quot;, source=&quot;/opt/ml/processing/output&quot;, destination=get_s3_path(pp_model_prefix)),<br>    ],<br>    arguments=[&quot;--train-filename&quot;, TRAIN_FN,<br>               &quot;--test-filename&quot;, VAL_FN,<br>               &quot;--train-feats-filename&quot;, TRAIN_FEATS_FN,p<br>               &quot;--test-feats-filename&quot;, VAL_FEATS_FN],<br>)</pre><h4>Custom Preprocessor</h4><p>I wanted to implement some custom preprocessing logic so I created a custom preprocessor class and configured it to follow the popular Sklearn .fit and .transform interfaces by extending BaseEstimator and TransformerMixin. The preprocessor transforms the feature named Model Year into Age and converts Origin and Cylinders into categorical features. This custom transformer must be stored in a separate file and imported by the main preprocessing script. The reason for this will be explained during the inferencing step.</p><pre>%%writefile scripts/preprocessor/custom_preprocessor.py<br><br>from sklearn.base import BaseEstimator, TransformerMixin<br><br>original_features = [&#39;cylinders&#39;,<br>                     &#39;displacement&#39;,<br>                     &#39;horsepower&#39;,<br>                     &#39;weight&#39;,<br>                     &#39;acceleration&#39;,<br>                     &#39;model year&#39;,<br>                     &#39;origin&#39;]<br><br><br>class CustomFeaturePreprocessor(BaseEstimator, TransformerMixin):<br>    &quot;&quot;&quot;<br>    This is a custom transformer class that does the following<br>    <br>        1. converts model year to age<br>        2. converts data type of categorical columns<br>    &quot;&quot;&quot;<br>    <br>    feat = original_features<br>    new_datatypes = {&#39;cylinders&#39;: &#39;category&#39;, &#39;origin&#39;: &#39;category&#39;}<br>    <br>    def fit(self, X, y=None):<br>        &quot;&quot;&quot; Fit function&quot;&quot;&quot;<br>        return self<br><br>    def transform(self, X, y=None):<br>        &quot;&quot;&quot; Transform Dataset &quot;&quot;&quot;<br>        assert set(list(X.columns)) - set(list(self.feat))\<br>                    ==  set([]), &quot;input does have the right features&quot;<br>        <br>        # convert model year to age<br>        X[&quot;model year&quot;] = 82 - X[&quot;model year&quot;]<br>        <br>        # change data types of cylinders and origin <br>        X = X.astype(self.new_datatypes)<br>        <br>        return X<br>    <br>    def fit_transform(self, X, y=None):<br>        &quot;&quot;&quot; Fit transform function &quot;&quot;&quot;<br>        x = self.fit(X)<br>        x = self.transform(X)<br>        return x</pre><h4>Preprocessing Job</h4><p>The preprocessing script located at scripts/preprocessor/train.py is executed in the preprocessing container to perform the feature engineering. I create a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline">Sklearn Pipeline</a> model using my CustomFeaturePreprocessor class as its first step, followed by a OneHotEncoder for transforming categorical columns and finally StandardScaler for numerical columns. A Sklearn pipeline is an easy way to chain multiple Sklearn transformers together.</p><p>You should avoid data leakage during feature engineering as a good ML Engineer. Since the same transformer is applied to the train and validation, I excluded the first columns of the Pandas Dataframes which is the target. I also fitted the model on only the train set.</p><p>After the model is saved using Joblib, it must be compressed into a file. Sagemaker models are archived as tarfiles else an error will be thrown when importing the model during inferencing.</p><pre>%%writefile scripts/preprocessor/train.py<br><br>import os<br>import joblib<br>import argparse<br>import numpy as np<br>import pandas as pd<br>import tarfile<br>from sklearn.base import BaseEstimator, TransformerMixin<br>from sklearn.pipeline import Pipeline<br>from sklearn.compose import make_column_selector, ColumnTransformer<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br>from custom_preprocessor import original_features, CustomFeaturePreprocessor<br><br>def save_numpy(np_array, path):<br>    &quot;&quot;&quot; save np array &quot;&quot;&quot;<br>    with open(path, &#39;wb&#39;) as f:<br>        np.save(f, np_array)<br><br>if __name__ == &#39;__main__&#39;:<br>    CONTAINER_TRAIN_INPUT_PATH = &quot;/opt/ml/processing/input/train&quot;<br>    CONTAINER_VAL_INPUT_PATH = &quot;/opt/ml/processing/input/test&quot;<br>    CONTAINER_TRAIN_OUTPUT_PATH = &quot;/opt/ml/processing/train&quot;<br>    CONTAINER_VAL_OUTPUT_PATH = &quot;/opt/ml/processing/test&quot;<br>    CONTAINER_OUTPUT_PATH = &quot;/opt/ml/processing/output&quot;<br>    <br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&#39;--train-filename&#39;, type=str, default=&#39;train.csv&#39;)<br>    parser.add_argument(&#39;--val-filename&#39;, type=str, default=&#39;val.csv&#39;)<br>    parser.add_argument(&#39;--model-filename&#39;, type=str, default=&#39;model.tar.gz&#39;)<br>    parser.add_argument(&#39;--train-feats-filename&#39;, type=str, default=&#39;train_feats.npy&#39;)<br>    parser.add_argument(&#39;--val-feats-filename&#39;, type=str, default=&#39;val_feats.npy&#39;)<br>    <br>    args = parser.parse_args()<br><br>    # one hot categorical features<br>    # apply standard scaler to numerical features<br>    ct = ColumnTransformer([(&quot;categorical-feats&quot;, OneHotEncoder(), make_column_selector(dtype_include=&quot;category&quot;)),<br>                            (&quot;numerical-feats&quot;, StandardScaler(), make_column_selector(dtype_exclude=&quot;category&quot;))])<br><br>    # apply custom preprocessing<br>    pl = Pipeline([(&quot;custom-preprocessing&quot;, CustomFeaturePreprocessor()), (&quot;column-preprocessing&quot;, ct)])<br>    <br>    train_data_path = os.path.join(CONTAINER_TRAIN_INPUT_PATH, args.train_filename)<br>    val_data_path = os.path.join(CONTAINER_VAL_INPUT_PATH, args.val_filename)<br>    <br>    # preprocess features, first column is target and the rest are features<br>    train_df = pd.read_csv(train_data_path)<br>    train_data = train_df.iloc[:, 1:]<br>    train_target = train_df[&quot;mpg&quot;].values.reshape(-1, 1)<br>    train_features = pl.fit_transform(train_data)<br>    <br>    val_df = pd.read_csv(val_data_path)<br>    val_data = val_df.iloc[:, 1:]<br>    val_target = val_df[&quot;mpg&quot;].values.reshape(-1, 1)<br>    val_features = pl.transform(val_data)<br>    <br>    # save features in output path with the container<br>    train_features = np.concatenate([train_target, train_features], axis=1)<br>    val_features = np.concatenate([val_target, val_features], axis=1)<br>    train_features_save_path = os.path.join(CONTAINER_TRAIN_OUTPUT_PATH, args.train_feats_filename)<br>    val_features_save_path = os.path.join(CONTAINER_VAL_OUTPUT_PATH, args.val_feats_filename)<br>    save_numpy(train_features, train_features_save_path)<br>    save_numpy(val_features, val_features_save_path)<br>    <br>    # save preprocessor model<br>    model_save_path = os.path.join(CONTAINER_OUTPUT_PATH, args.model_filename)<br>    <br>    # save model should be a tarfile so it can be loaded in the future<br>    joblib.dump(pl, &quot;model.joblib&quot;)<br>    with tarfile.open(model_save_path, &quot;w:gz&quot;) as tar_handle:<br>        tar_handle.add(&quot;model.joblib&quot;)</pre><h3>Stage 2: Model Training and Evaluation</h3><p>A different python library smexperiments is used for Experiment tracking in Sagemaker. A Trial in Sagemaker is synonymous with an MLFlow run. A trial could consist of multiple ML workflow stages, depending on the complexity of the solution. For example, model training and evaluation or just a single hyperparameter optimization step could be considered a trial. What&#39;s important is that metrics are logged for each trial run to enable the comparison of different trials.</p><p>I created a trial for just the training step and attributed it to the created experiment using the experiment_name parameter in the Trial.create call.</p><pre><br>from smexperiments.experiment import Experiment<br>from smexperiments.trial import Trial<br>from smexperiments.trial_component import TrialComponent<br>from smexperiments.tracker import Tracker<br><br>current_time = datetime.now().strftime(&quot;%d-%b-%Y-%H-%M-%S&quot;)<br>experiment_name = &quot;auto-mg-experiment&quot;<br># create a new experiment a load one if it exists<br>try:<br>    auto_experiment = Experiment.load(experiment_name=experiment_name)<br>    print(f&#39;experiment {experiment_name} was loaded&#39;)<br>except Exception as ex:<br>    if &quot;ResourceNotFound&quot; in str(ex):<br>        auto_experiment = Experiment.create(experiment_name = experiment_name,<br>                                            description = &quot;Regression on Auto MPG dataset&quot;,<br>                                            tags = [{&#39;Key&#39;: &#39;Name&#39;, &#39;Value&#39;: f&quot;auto-mg-experiment-{current_time}&quot;},<br>                                                    {&#39;Key&#39;: &#39;MLEngineer&#39;, &#39;Value&#39;: f&quot;Temiloluwa Adeoti&quot;},<br>                                                   ])<br>        print(f&#39;experiment {experiment_name} was created&#39;)<br><br>from sagemaker.sklearn.estimator import SKLearn<br><br>current_time = datetime.now().strftime(&quot;%d-%b-%Y-%H-%M-%S&quot;)<br>n_estimators = 10<br>trail_name = f&quot;auto-mg-{n_estimators}-estimators&quot;<br># create a trial for the training job<br>training_job_trial = Trial.create(trial_name = f&quot;{trail_name}-{current_time}&quot;,<br>                              experiment_name = auto_experiment.experiment_name,<br>                              sagemaker_boto_client=sm_client,<br>                              tags = [{&#39;Key&#39;: &#39;Name&#39;, &#39;Value&#39;: f&quot;auto-mg-{current_time}&quot;},<br>                                       {&#39;Key&#39;: &#39;MLEngineer&#39;, &#39;Value&#39;: f&quot;Temiloluwa Adeoti&quot;}])<br><br># configure the estimator<br>model = SKLearn(<br>    entry_point=&quot;train.py&quot;,<br>    source_dir=&quot;./scripts/model&quot;,<br>    framework_version=&quot;1.0-1&quot;, <br>    instance_type=&quot;ml.m5.xlarge&quot;, <br>    role=role,<br>    output_path = get_s3_path(ml_model_prefix), # model output path<br>    hyperparameters = {<br>        &quot;n_estimators&quot;: n_estimators<br>    },<br>    metric_definitions=[<br>            {&quot;Name&quot;: &quot;train:mae&quot;, &quot;Regex&quot;: &quot;train_mae=(.*?);&quot;},<br>            {&quot;Name&quot;: &quot;test:mae&quot;, &quot;Regex&quot;: &quot;test_mae=(.*?);&quot;},<br>            {&quot;Name&quot;: &quot;train:mse&quot;, &quot;Regex&quot;: &quot;train_mse=(.*?);&quot;},<br>            {&quot;Name&quot;: &quot;test:mse&quot;, &quot;Regex&quot;: &quot;test_mse=(.*?);&quot;},<br>            {&quot;Name&quot;: &quot;train:rmse&quot;, &quot;Regex&quot;: &quot;train_rmse=(.*?);&quot;},<br>            {&quot;Name&quot;: &quot;test:rmse&quot;, &quot;Regex&quot;: &quot;test_rmse=(.*?);&quot;},<br>        ],<br>    enable_sagemaker_metrics=True<br>)<br><br># fit the estimator<br>model.fit(job_name=f&quot;auto-mpg-{current_time}&quot;,<br>          inputs = {&quot;train&quot;: get_s3_path(pp_train_prefix), <br>                    &quot;test&quot;: get_s3_path(pp_val_prefix)<br>                   }, <br>          experiment_config={<br>            &quot;TrialName&quot;: training_job_trial.trial_name,<br>            &quot;TrialComponentDisplayName&quot;: f&quot;Training-auto-mg-run-{current_time}&quot;,<br>          },<br>          logs=&quot;All&quot;)</pre><p>I reckon logging of metrics to be a bit involved in Sagemaker in comparison to other frameworks. This is how custom training metrics are captured:</p><ol><li>Create a logger that streams to standard output (logging.StreamHandler(sys.stdout)). The streamed logs are automatically captured by AWS Cloudwatch</li><li>Log metrics based on your predetermined format e.g metric-name=metric-value</li><li>Give a regex pattern that matches your metric logging format to the metric_definition parameter when creating the estimator that runs the training script</li></ol><p>The training job is executed by running the scripts/model/train.py file within a Sklearn Estimator container on a compute instance (ml.m5.xlarge in this case). Pay attention to how inputs are supplied to estimators using the inputs parameter and how the training job is assigned to the created trial using the experiment_config parameter.</p><p>The script trains RandomForestRegressor on the .npy preprocessed train features and the model is evaluated on validation features. I will explain why I did not save the model as a tarfile in the following paragraph.</p><pre>%%writefile scripts/model/train.py<br>import logging<br>import sys<br>import argparse<br>import os<br>import pandas as pd<br>import numpy as np<br>import joblib<br>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.metrics import mean_absolute_error, mean_squared_error <br><br># configure logger to standard output<br>logger = logging.getLogger(__name__)<br>logger.setLevel(logging.DEBUG)<br>stream_handler = logging.StreamHandler(sys.stdout)<br>stream_handler.setFormatter(logging.Formatter(&quot;%(asctime)s %(name)-12s %(levelname)-8s %(message)s&quot;))<br>logger.addHandler(stream_handler)<br><br><br>def get_metrics(train_y_true, train_y_pred, val_y_true, val_y_pred):<br>    &quot;&quot;&quot;<br>    Return train and val metrics<br>    &quot;&quot;&quot;<br>    <br>    # mae<br>    t_mae = mean_absolute_error(train_y_true, train_y_pred)<br>    ts_mae = mean_absolute_error(val_y_true, val_y_pred)<br>    <br>    # mse<br>    t_mse = mean_squared_error(train_y_true, train_y_pred, squared=False)<br>    ts_mse = mean_squared_error(val_y_true, val_y_pred, squared=False)<br>    <br>    # rmse<br>    t_rmse = mean_squared_error(train_y_true, train_y_pred, squared=True)<br>    ts_rmse = mean_squared_error(val_y_true, val_y_pred, squared=True)<br>    <br>    return t_mae, ts_mae, t_mse, ts_mse, t_rmse, ts_rmse<br><br><br>if __name__==&#39;__main__&#39;:<br>    parser = argparse.ArgumentParser()<br>    # Sagemaker specific arguments. Defaults are set in the environment variables.<br>    parser.add_argument(&#39;--output-data-dir&#39;, type=str, default=os.environ[&#39;SM_OUTPUT_DATA_DIR&#39;])<br>    # location in container: &#39;/opt/ml/model&#39;<br>    parser.add_argument(&#39;--model-dir&#39;, type=str, default=os.environ[&#39;SM_MODEL_DIR&#39;])<br>    # location in container: &#39;/opt/ml/input/data/train&#39;<br>    parser.add_argument(&#39;--train&#39;, type=str, default=os.environ[&#39;SM_CHANNEL_TRAIN&#39;])<br>    # location in container: &#39;/opt/ml/input/data/test&#39;<br>    parser.add_argument(&#39;--test&#39;, type=str, default=os.environ[&#39;SM_CHANNEL_TEST&#39;])<br>    # model filename<br>    parser.add_argument(&#39;--model-filename&#39;, type=str, default=&quot;model.joblib&quot;)<br>    <br>    # Hyperparameters are described here.<br>    parser.add_argument(&#39;--n_estimators&#39;, type=int)<br>    args = parser.parse_args()<br>    <br>    logger.debug(f&quot;Number of Estimators: {args.n_estimators}&quot;)<br>    <br>    # Load numpy features saved in S3 <br>    # Targets are the first column, features are other columns<br>    train_data = np.load(os.path.join(args.train, &quot;train_feats.npy&quot;))<br>    train_feats = train_data[:, 1:]<br>    train_target = train_data[:, 0]<br>    <br>    val_data = np.load(os.path.join(args.test, &quot;val_feats.npy&quot;))<br>    val_feats = val_data[:, 1:]<br>    val_target = val_data[:, 0]<br>    <br>    # Train random forest model<br>    model = RandomForestRegressor(max_depth=args.n_estimators, random_state=0)<br>    model.fit(train_feats, train_target)<br>    logger.info(&quot;Model Trained &quot;)<br>    <br>    train_pred = model.predict(train_feats)<br>    val_pred = model.predict(val_feats)<br>    <br>    # Evaluate Model<br>    train_mae, val_mae, train_mse, val_mse, train_rmse, val_rmse = \<br>        get_metrics(train_target, train_pred, val_target, val_pred)<br>    <br>    logger.info(f&quot;train_mae={train_mae};  val_mae={val_mae};&quot;)<br>    logger.info(f&quot;train_mse={train_mse};  val_mse={val_mse};&quot;)<br>    logger.info(f&quot;train_rmse={train_rmse}; val_rmse={val_rmse};&quot;)<br>    <br>    # Save the Model<br>    joblib.dump(model, os.path.join(args.model_dir, args.model_filename))</pre><h3>Stage 3: Model Inferencing</h3><p>Sagemaker provides the <a href="https://sagemaker.readthedocs.io/en/stable/api/inference/model.html">Model</a> API for model deployment to an endpoint and the <a href="https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html">Predictor</a> API for making predictions with the endpoint. Since we have two models, the preprocessor and regressor models, we require a Sagemaker pipeline model to chain both and make a deployment.</p><p>I selected the SKLearnModel (Model with Sklearn dependencies pre-installed) for the preprocessor. To prepare the Model, I supplied as arguments paths to the saved tar model in S3, the inference script which is its entry point, and the custom_preprocessor.py.</p><p>Repeating the CustomFeaturePreprocessor in both the preprocessor model training ( scripts/preprocessor/train.py) and inference ( scripts/preprocessor/inference.py) scripts did not work. I needed to import the class from a separate file ( scripts/preprocessor/custom_preprocessor.py) for inferencing. This was the error I encountered: Can&#39;t get attribute &#39;CustomFeaturePreprocessor&#39; on &lt;module &#39;<strong>main</strong>&#39; from &#39;/miniconda3/bin/gunicorn&#39;&gt; . It is a common problem faced during model deployment. You can read more on this type of problem in this <a href="https://stackoverflow.com/questions/49621169/joblib-load-main-attributeerror">Stackoverflow post</a></p><p>I did not save the regressor as a tarfile because I chose not to import the regressor model from S3. Instead, I created a Sagemaker Model directly from the trained Estimator with the .create_model method (another way to create Models).</p><p>When the two models are provided in a list in the pipeline model definition as shown below, Sagemaker automatically serves the output of the preprocessor model as input to the regressor model. I deployed the model to a ml.c4.xlarge instance and used a <a href="https://sagemaker.readthedocs.io/en/stable/api/inference/serializers.html">CSVSerializer</a> for input requests.</p><pre>from sagemaker.sklearn.model import SKLearnModel<br>from sagemaker.pipeline import PipelineModel<br>from sagemaker.serializers import CSVSerializer<br>from datetime import datetime<br><br>current_time = datetime.now().strftime(&quot;%d-%b-%Y-%H:%M:%S&quot;).replace(&quot;:&quot;, &quot;-&quot;)<br>model_name = f&quot;inference-pipeline-{current_time}&quot;<br>endpoint_name = f&quot;inference-pipeline-{current_time}&quot;<br>pp_model_path = get_s3_path(pp_model_prefix) + &quot;/model.tar.gz&quot;<br><br>print(&quot;preprocessor model path &quot;, pp_model_path)<br><br># preprocessor<br>sklearn_processor_model = SKLearnModel(<br>                             model_data=pp_model_path,<br>                             role=role,<br>                             entry_point=&quot;scripts/preprocessor/inference.py&quot;,<br>                             dependencies=[&quot;scripts/preprocessor/custom_preprocessor.py&quot;],<br>                             framework_version=&quot;1.0-1&quot;,<br>                             sagemaker_session=sess)<br><br># regression model<br>reg_model = model.create_model(entry_point=&quot;inference.py&quot;,<br>                               source_dir=&quot;./scripts/model&quot;)<br><br># create a pipeline model with the two models    <br>inference_pipeline = PipelineModel(<br>    name=model_name, role=role, models=[sklearn_processor_model, reg_model],<br>    sagemaker_session=sess<br>)<br><br># deploy model<br>predictor = inference_pipeline.deploy(initial_instance_count=1, <br>                                      instance_type=&quot;ml.c4.xlarge&quot;, <br>                                      endpoint_name=endpoint_name,<br>                                      serializer=CSVSerializer() # to ensure input is csv<br>                                     )</pre><h4>Sagemaker Inference Script Structure</h4><p>In Sagemaker, the model server requires four functions to successfully deploy a model.</p><ol><li>The model_fn loads the model file e.g .joblibmodel</li><li>The input_fn parses the input request to the model. Data deserialization and transformation can occur to prepare the request for the model.</li><li>The predict_fn makes the actual prediction with the model e.g calls model.predict.</li><li>The output_fn processes the response and delivers it in the desired format to the caller.</li></ol><p>Our Sklearn model server already has default implementations of these functions which can be overridden in our inference script.</p><h4>Preprocessor Inference Script</h4><p>In my inference script for the preprocessor, I imported the custom dependencies to avoid the error earlier mentioned. The model_fn loads the .joblib model, while the input_fn ensures the request is in text or csv format and transforms the data into a Pandas Dataframe. By default, the predict_fn should make a .predict call on the model, but since the preprocessor is a transform, I used the .transform method.</p><pre>%%writefile scripts/preprocessor/inference.py<br>import os<br>import joblib<br>import argparse<br>import pandas as pd<br>from io import StringIO<br># import the custom dependencies<br>from custom_preprocessor import original_features, CustomFeaturePreprocessor<br><br>def input_fn(input_data, content_type):<br>    &quot;&quot;&quot; Preprocess input data &quot;&quot;&quot;<br>    if content_type == &#39;text/csv&#39;:<br>        df = pd.read_csv(StringIO(input_data), header=None)<br><br>        if len(df.columns) == len(original_features) + 1:<br>            df = df.iloc[:, 1:]<br>            <br>        if list(df.columns) != original_features:<br>            df.columns = original_features<br>            <br>        return df<br>    else:<br>        raise ValueError(f&quot;Unsupported content type: {type(content_type)}&quot;)<br><br>def predict_fn(input_data, model):<br>    &quot;&quot;&quot; Call the transform method instead of the default predict method&quot;&quot;&quot;<br>    predictions = model.transform(input_data)<br>    return predictions<br><br><br>def model_fn(model_dir):<br>    &quot;&quot;&quot;Load the model&quot;&quot;&quot;<br>    model_path = os.path.join(model_dir, &quot;model.joblib&quot;)<br>    loaded_model = joblib.load(model_path)<br>    return loaded_model</pre><h4>Regressor Inference Script</h4><p>The regressor uses a much simpler inference script. Here the output_fn is implemented to provide a JSON response to the input request.</p><pre>%%writefile scripts/model/inference.py<br>import sys<br>import os<br>import logging<br>import json<br>import joblib<br>from sagemaker_containers.beta.framework import worker<br><br># configure logger to standard output<br>logger = logging.getLogger(__name__)<br>logger.setLevel(logging.DEBUG)<br>stream_handler = logging.StreamHandler(sys.stdout)<br>stream_handler.setFormatter(logging.Formatter(&quot;%(asctime)s %(name)-12s %(levelname)-8s %(message)s&quot;))<br>logger.addHandler(stream_handler)<br><br>def model_fn(model_dir):<br>    &quot;&quot;&quot;Deserialize fitted model<br>    &quot;&quot;&quot;<br>    model = joblib.load(os.path.join(model_dir, &quot;model.joblib&quot;))<br>    return model<br><br><br>def output_fn(prediction, accept):<br>    &quot;&quot;&quot;<br>    Preprocess numpy array to return JSON output<br>    &quot;&quot;&quot;<br>    pred = []<br>    for i, row in enumerate(prediction.tolist()):<br>        pred.append({&quot;id&quot;: i, &quot;prediction&quot;: row})<br><br>    return worker.Response(json.dumps(pred))</pre><h3>Making Predictions</h3><p>All the major work is done and making predictions is a very simple process with the <a href="https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html">Predictor API</a>.</p><p>In the code snippet below, I download the raw test set from S3 and store each line of the CSV, except the header, as a string in the list called test_data. After instantiating the Predictor with the endpoint name and sagemaker session, I make predictions by calling the .predict method on the predictor instance.</p><pre>from pprint import pprint<br><br># download raw test data and read text files<br>sess.download_data(path=&quot;.&quot;, bucket=bucket, key_prefix=raw_test_prefix)<br>with open(&quot;test.csv&quot;, &quot;r&quot;) as f:<br>    test_data = f.readlines()[1:]<br><br># make predictions with the deployed endpoint<br>from sagemaker.predictor import Predictor<br>from sagemaker.deserializers import JSONLinesDeserializer<br><br>predictor = Predictor(<br>    endpoint_name=endpoint_name, sagemaker_session=sess, serializer=CSVSerializer(), deserializer=JSONLinesDeserializer()<br>)<br><br>num_of_samples = 1<br>response = predictor.predict(test_data[:num_of_samples])</pre><h3>Conclusion</h3><p>In this post, we have explored the Estimator API, Model API, Preprocessor API, and Predictor API using the AWS Sagemaker Python SDK by training and deploying a regression model. These are the fundamental APIs that are required for developing solutions in Sagemaker.</p><p>Sagemaker comes with over 20 features that cover most of the ML life cycle from data annotation and preprocessing to model deployment. A full feature list is found <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html">here</a>. Some of these features like we saw with Sagemaker Experiments have separate python libraries. This could make Sagemaker challenging to learn. From my experience, I have found it helpful to study <a href="http://: https://sagemaker-examples.readthedocs.io/en/latest/intro.html">Sagemaker examples</a> when working with unfamiliar Sagemaker features.</p><p>Since most Sagemaker jobs run within a docker container, it’s vital to have logging activated to debug errors. Logs streamed to standard output and default Sagemaker metrics are captured by Cloudwatch. I guarantee that this would save you a lot of pain when working with Sagemaker.</p><p>For further assistance with developing ML Solutions in the cloud, do not hesitate to reach out to <a href="https://www.reply.com/machine-learning-reply/de/">Machine Learning Reply</a>. We guide and support all our customers in the development of their IT capabilities toward Data Machine Learning and Cloud use cases, regardless of their current phase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e38beea5dbaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/a-practical-introduction-to-the-amazon-sagemaker-python-sdk-e38beea5dbaa">A Practical Introduction to the Amazon SageMaker Python SDK</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Recommendation Systems Applied to Streaming Video]]></title>
            <link>https://medium.com/machine-learning-reply-dach/the-power-of-recommendation-systems-applied-to-streaming-video-d32d4570d188?source=rss----4e1d53a63327---4</link>
            <guid isPermaLink="false">https://medium.com/p/d32d4570d188</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[recommendation-engine]]></category>
            <category><![CDATA[streaming-video]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Pedro Flores]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 09:59:13 GMT</pubDate>
            <atom:updated>2022-11-21T09:59:13.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KL0lqeDIA2wuoHyKbjlP6A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kelly Sikkema</a> on <a href="https://unsplash.com/es?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Nowadays, every online service or app in the market tracks and stores all the interactions done in the form of data. This data is used for targeted ads, improved recommendations, or statistical analysis among many other purposes. All this collected information is generally available for any individual who requests a copy of this data.</p><p>This article will analyze the gathered data of a streaming video platform, reveal some insights about it and later use a database of movies to make some recommendations of new titles, while applying different methodologies.</p><p>The approach followed comprehends these 3 points:</p><p><strong>I. Understanding the Data Available</strong></p><p>Here the available files are enumerated and explained for better understanding of the data that will be used. Finding and treating missing values is also discussed.</p><p><strong>II. Analysis and Visualization</strong></p><p>In this section is done the analysis with help of some visualizations</p><p><strong>III. Recommendation Systems</strong></p><p>Finally, the different recommendation systems are described and applied to find out similar titles to what user likes to watch</p><h4>1. Understanding the Data Available</h4><p>Streaming Video Platforms allow active users to get their data from the account page. By clicking on the option to download personal information, anyone can send the Video Platform a request to email the data to the user. Once the request is processed, a folder with multiple content inside is received, such as <em>IP_ADDRESSES</em>, <em>PAYMENT_AND_BILLING</em> and <em>CONTENT_INTERACTION</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-395HqkVkmKDQ-rXY1JLJw.png" /><figcaption>Data available from streaming video paltform</figcaption></figure><p>Inside this last folder is the file of our interest, ViewingActivity.csv, where the data that the Streaming Video Platform has about us can be found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TVUo0bsgHxUNYk9T7zCy6Q.png" /><figcaption>Overview of information inside ViewingActivity file</figcaption></figure><p>As can be seen, <em>Profile Name, Duration, Title, Device Type</em> and <em>Country</em> among other categories are available. Analyzing this information, it is possible to get insights like Average Watching Time, Distribution of Viewing Time by Day or Hour and so on.</p><p>As a way to enrich the information available, Cinemagoer will be used. Cinemagoer is a Python package for retrieving and managing the data of the popular site IMDb, a movie database. This way it is feasible to also have access to data such as genre, original title, or country where the movie was produced. To access the data, the following code can be used:</p><pre>ia = Cinemagoer() <br>search_result = ia.search_movie(movie_title) <br>movie_id = search_result[0].getID() <br>movie = ia.get_movie(movie_id) </pre><p>First, it is necessary to create an instance of the Cinemagoer class. Then, the <em>search_movie</em> method is used for searching the desired <em>movie_title</em>. Once this data is collected, it is possible to get the id of the title, and with this id, information like plot, country and year is retrieved. For instance, for the movie <em>The Adam Project</em>, this is the information available after using Cinemagoer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*KguWjQ21-67BofRuQhRUHQ.png" /><figcaption>Additional information retrieved with Cinemagoer</figcaption></figure><p>Finally, the MovieLens Dataset will be used for making recommendations. It describes ratings and free-text tagging activities from more than 100000 users between 1995 and 2015. Each user is represented by an id, and inside the file movies_metadata.csv is the information needed.</p><p><strong>Data manipulation and cleaning</strong></p><p>Now that the data available has been introduced, it is time to start transforming it as necessary. The focus is going to be on one hand in looking for missing values that may affect the analysis and recommendations, and on the other hand in anonymizing the users on the dataset.</p><p>First, an exploration will be carried out for finding missing values in ViewingActivity and MovieLens Dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb74818d624cea789d5688b64a66817b/href">https://medium.com/media/eb74818d624cea789d5688b64a66817b/href</a></iframe><p>For columns named <em>Attributes</em>, <em>Supplemental Video Type</em>, <em>belongs_to_collection</em>, <em>homepage</em> and <em>overview</em>, there are some cells with no values. From them, the only information that will be used is present in <em>overview</em>, where the plot for every film in the MovieLens Dataset is contained. This data will be especially useful later for recommending similar titles based on their plots and thus no missing value can be found here. Therefore, rows with no data in <em>overview</em> will be deleted.</p><p>Regarding user anonymization, the only necessary transformation is to replace the different available users with some generic name. <em>User</em> will be used for this purpose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*nrkSo7zdJ895UytXbo8ujA.png" /><figcaption>User anonymization</figcaption></figure><h4>2. Analysis and Visualization</h4><p>Once all the information needed has been collected, it is possible to use it for the analysis. The focus will be on analyzing the Viewing Activity to understand how users use their time to consume content.</p><p>A good starting point is the distribution of viewing time, since the consumption time can be devised depending on the day of the week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*PLhyqaws7s9a3VQjsi8pZQ.png" /></figure><p>From the picture above, users tend to spend an average of less than 24 minutes (0.4 hours) per day watching content with a slight increase during the weekend, due to the availability of more free time.</p><p>Another interesting feature to investigate is the country where the platform was accessed from. This can give an idea about the residence of the users and from where they typically use the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*W7OQW4dM5tv6CP5vemdlKQ.png" /></figure><p>As can be seen on the picture above, most accesses to the platform are done from Spain and Germany with marginal appearance of other countries that could suggest short trips or the utilization<strong> </strong>of a VPN to use the service.</p><p>Finally, looking at the heatmap of the viewing activity gives an idea of the day, and time on each day, that <em>User 1</em> is more likely to use the service. As the distribution of viewing time already depicted, weekends are when there is more use of the service but here it can also be determined that the period between 17 and 21 is the preferred to consume content on the video platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXzy05oZYkLEsA0R64F94g.png" /><figcaption>Sum of content viewed by user 1 in each time slot</figcaption></figure><h4>3. Recommendation Systems</h4><p>Recommendation systems are one of the most popular applications of data science. They are used to predict the “rating” that a user would give to an item, and it is employed by retail companies for product suggestions to customers, by social networks to make recommendations on pages and people to follow, and by streaming platforms to make content recommendations, among other applications.</p><p>Recommendation systems can be grouped into 4 categories: Simple Recommendations and Suggestions, Content-Based Recommendations, Collaborative Filtering and Matrix Factorization.</p><p>In the following lines the mentioned recommenders will be explained and applied to the MovieLens Dataset to get a list of recommendations with each of them for <em>User 1</em></p><p><strong>3.1 Simple Recommendations and Suggestions</strong></p><p>It is based on the popularity of movies and the underlying concept is that titles that are most popular will have a higher chance of being liked by the average audience. Using this idea, and counting the number of reviews per title in the Dataset, the following table is obtained:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f9646c0db7585ee5fa8b7688a6898d6/href">https://medium.com/media/8f9646c0db7585ee5fa8b7688a6898d6/href</a></iframe><p>However, just because a movie has been watched by a lot of people does not necessarily mean that viewers enjoyed it. To understand how a viewer actually felt about a movie, more explicit data is useful. To do so, the average rating of each movie in the MovieLens Dataset is calculated followed by sorting the result to find the movies with the highest average rating:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2c549048ddc00afdab4c61dd29aba29/href">https://medium.com/media/c2c549048ddc00afdab4c61dd29aba29/href</a></iframe><p>The last two methods have their weaknesses. Finding the most frequently watched movies will show what has been watched, but not how people explicitly feel about it. However, finding the average of reviews has the opposite problem where there is customers’ explicit feedback, but individual preferences are skewing the data. Now is time to combine the two previous methods to find the average rating only for movies that have been reviewed more than a threshold, that will be defined as forty thousand times in this case. The titles obtained are more accurate because they are based in both popularity and feedback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f2ea66ed5345cd594a5287b0b96ec39/href">https://medium.com/media/3f2ea66ed5345cd594a5287b0b96ec39/href</a></iframe><p>One last method inside Simple Recommendations to consider, is to calculate pairs of films that have been watched and rated together and compute all the possible combinations of them (calculate the permutations). Once this is done, the way to proceed is to determine how often these pairs of titles appear and sort this list from highest to lowest.</p><p>Since there is data available of titles watched by <em>User 1</em>, it is possible to make recommendations for specific titles based on the list calculated with the permutations. Applying this method to <em>Batman Begins</em>, the following titles are the recommended for <em>User 1</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*NrYkK02p59vaC0CVBE6vaQ.png" /></figure><p>As can be seen, some well-known films are between the suggestions</p><p><strong>3.2 Content-Based Recommendations</strong></p><p>Content-based filtering uses item features to recommend other items similar to what the user likes, based on their previous actions or explicit feedback. The underlying concept is that when a user likes a particular item, he or she will also like an item that has similar attributes.</p><p><strong><em>Recommender based on title plot</em></strong></p><p>In this first content-based recommender, a Natural Language Processing problem will be solved. The aim here is, being picked a random title that <em>User 1</em> has watched before, recommend from the MovieLens Dataset other films that have a similar plot and therefore user will probably like.</p><p>First, <em>LanguageDetector</em>() (from library <em>spaCy</em>) is going to be applied to keep only the films that have an overview in English. Then, because all films with the same title have the same plot, the rows with repeated titles can be deleted to keep a table with unique titles and plot descriptions. This way the processing time when using NLP will be lower. Once this is done, a total of unique 2769 titles are ready to be analyzed.</p><p>The cosine similarity will be applied on films plot to find alike titles to <em>Batman Begins</em> (<em>User 1</em> watched it already). After applying it to all plots and ordering the results from higher to lower similarity score, the following list of recommendations is obtained:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/327a6bf6ecef5c14ce65b67b555c83da/href">https://medium.com/media/327a6bf6ecef5c14ce65b67b555c83da/href</a></iframe><p>As expected, all films recommended are remarkably similar to the one selected to make recommendations from.</p><p><strong><em>Recommender based on Jaccard Index</em></strong></p><p>In this other content-based recommender, the metric that is used to measure similarity between items is called the Jaccard similarity index. It is the ratio of attributes that two items have in common, divided by the total number of their combined attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*yjDwygs6OsXp46leSoOsIw.png" /><figcaption>Jaccard Similarity for two sets</figcaption></figure><p>This score will always be between 0 and 1 and the more attributes the two items have in common, the higher the score.</p><p>To get all these similarities at once, a helpful function from the <em>SciPy</em> package will be called upon. <em>Pdist</em> (short for pairwise distance) helps find all the distances at once, using Jaccard as the metric argument. Note that pdist calculates the Jaccard distance which is a measure of how different rows are from each other. As the aim is to calculate the complement of this, the similarity, these values will be subtracted from 1.</p><p>This methodology is applied to the genre attributes of all films and after wrapping the results in a DataFrame, it is easy to find similar titles by looking up any pairings. For example, for the film <em>The Terminator,</em> the following results are obtained:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ecca452560c8bd70bff57c9b5d65088/href">https://medium.com/media/6ecca452560c8bd70bff57c9b5d65088/href</a></iframe><p><strong>3.3 Collaborative Filtering</strong></p><p>Collaborative filtering uses similarities between users and items simultaneously to provide recommendations. This allows for serendipitous recommendations; that is, collaborative filtering models can recommend an item to user A based on the interests of a similar user B.</p><p>The approach to apply this method starts by creating a table where the data about userId, titles and ratings is collected. Then center each user ratings around 0 by subtracting the average rating of each film. Once this is done, the cosine similarity is applied to the transposed matrix to find out the similarity between elements. Afterwards it is possible to build a square matrix in which each row and column represents the title of the film, and each cell contains the similarity score for each pair of titles. Therefore, the diagonal will have the value 1.</p><p>With this information it is possible to select a title, for example <em>Jurassic Park III</em>, sort the values in descending order and obtain a list of similar titles:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3add23122ac9b7190db74aa310f73637/href">https://medium.com/media/3add23122ac9b7190db74aa310f73637/href</a></iframe><p><strong>3.4 Matrix Factorization</strong></p><p>In this last method the basic idea is to decompose the user-rating matrix into the product of two lower dimensionality matrices.</p><p>A common challenge with real-world ratings data is that most users will not have rated most items, and most items will only have been rated by a small number of users. This results in a very empty or sparse DataFrame. To solve this situation is necessary to apply a matrix factorization. Factors can be found as long as there is at least one value in every row and column. Or in other words, every user has given at least one rating, and every item has been rated at least once.</p><p>There are many ways to find the factors of a matrix, but here a technique called singular value decomposition (SVD) will be used. Before applying this, it is necessary to normalize the data by subtracting each row’s mean from each value in that row and filling in the remaining empty values with 0.</p><p>Like any matrix factorization approach, singular value decomposition finds factors for some matrix and in this case the following components are obtained:</p><ul><li><em>U</em> is the user matrix</li><li><em>V</em> transpose represent the features</li><li><em>Sigma</em>, simply a diagonal matrix which can be thought of as the weights of the latent features, or how large an impact they are calculated to have</li></ul><p>Finally, once the three matrices are determined, it is possible to multiply them back together and add the average ratings for each row to obtain a complete matrix of ratings without missing values. And by sorting out the resulting matrix it is possible to obtain the list of titles that the user would have given to all films like depicted in the following table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a052e2aeb286282fbc6860601ba0d80/href">https://medium.com/media/7a052e2aeb286282fbc6860601ba0d80/href</a></iframe><h4><strong>Conclusion</strong></h4><p>This blog post tried to give an overview of some common recommendation techniques used in the video streaming industry to make suggestions to users to discover new films. A basic explanation and a practical approach were also provided to understand how the results were obtained while presenting real recommendations based on what <em>User 1</em> enjoyed watching.</p><p>Although recommendations were made using films, it also has applications in many fields like product recommendations, social media, home listings, music streaming and restaurants, among others.</p><p>At Machine Learning Reply, we guide and support all our customers in the development of their IT capabilities towards Machine Learning, data, or cloud Use Cases, regardless of their current phase.</p><p>References:</p><ul><li><a href="https://developers.google.com/machine-learning/recommendation/collaborative/basics?hl=en">https://developers.google.com/machine-learning/recommendation/collaborative/basics?hl=en</a></li><li><a href="https://www.learndatasci.com/glossary/jaccard-similarity/">https://www.learndatasci.com/glossary/jaccard-similarity/</a></li><li><a href="https://www.datacamp.com/tutorial/recommender-systems-python">https://www.datacamp.com/tutorial/recommender-systems-python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d32d4570d188" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-reply-dach/the-power-of-recommendation-systems-applied-to-streaming-video-d32d4570d188">The Power of Recommendation Systems Applied to Streaming Video</a> was originally published in <a href="https://medium.com/machine-learning-reply-dach">Machine Learning Reply DACH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>