<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Talha Nebi Kumru on Medium]]></title>
        <description><![CDATA[Stories by Talha Nebi Kumru on Medium]]></description>
        <link>https://medium.com/@TalhaNebiKumru?source=rss-2f9aee9f265b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xIBokYp08YQac_63HSw0bA.png</url>
            <title>Stories by Talha Nebi Kumru on Medium</title>
            <link>https://medium.com/@TalhaNebiKumru?source=rss-2f9aee9f265b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:07:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@TalhaNebiKumru/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Data Warehouse]]></title>
            <link>https://medium.com/@TalhaNebiKumru/data-warehouse-34c76111161f?source=rss-2f9aee9f265b------2</link>
            <guid isPermaLink="false">https://medium.com/p/34c76111161f</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Talha Nebi Kumru]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 07:27:46 GMT</pubDate>
            <atom:updated>2024-01-01T07:27:46.008Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Warehouse is a centralized database where data from various sources is collected, transformed and stored for analysis and reporting purposes. It is designed to support business intelligence and decision-making processes. By providing a unified view of historical and current data, it enables organizations to perform complex queries, generate reports and gain insights for strategic planning and decision making based on their data. There are three main types of data warehouse:</p><ol><li>Enterprise Data Warehouse</li><li>Operational Data Warehouse</li><li>Data Mart</li></ol><h3>Database &amp; Data Warehouse Differences</h3><p>Database is a structured collection of data that is organized and stored in a way that allows for efficient retrieval, management, and updating of that data. Databases are used to store and manage information in various fields, including business, science, education, and more. Their differences are;</p><h4>Usage Reasons</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*JQ96hK66gkO2acjHd6iB3g.png" /></figure><h4>Characteristic Features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*REOESVh5tu2ht7ynOpb1hg.png" /></figure><h4>Main Differences</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*TlyRx209R7YfJGRcfq4cGA.png" /></figure><h3>Data Warehouse Architect</h3><p>Data Warehouse’s database; the master database is the foundation of the data storage environment. This database is implemented in relational database technology. However, this type of implementation is constrained by the fact that the traditional relational database system is optimized for data storage and not for operational data transaction.</p><ul><li>In a data warehouse, relational databases are deployed in parallel to allow scalability.</li><li>New index structures are used to bypass relational table scanning and increase speed.</li><li>Multidimensional database (MDDB) is used to overcome the limitations imposed by the relational data model. (Oracle Essbase)</li></ul><h4>ETL Tools</h4><p>ETL tools are used to perform all transformations, summarizations and any changes needed to convert the data into a unified format in the data store.</p><ul><li>Anonymizes data according to regulatory provisions.</li><li>Prevents unwanted data in operational databases from being uploaded to the data warehouse.</li><li>Search and exchange common names and definitions of data from different sources.</li><li>Calculates summaries and derived data.</li><li>In case of missing data, fills them with default values</li><li>Detect duplicated or repeated data from multiple sources.</li></ul><h4>Metadata</h4><p>Metadata is a fairly simple concept, although it introduces some high-level technological concepts. Metadata is data about the data that defines the data warehouse. It is used to create, maintain and manage the data warehouse. Metadata provides answers to the following questions:</p><ul><li>Which tables, attributes and keys does the data warehouse contain?</li><li>Where did the data come from?</li><li>How many times is the data reloaded?</li><li>What transformations were done with the cleansing?</li></ul><p><strong>Technical Metadata: </strong>It contains information about the data warehouse used by Data Warehouse designers and administrators.</p><p><strong>Business Metadata: </strong>It provides end users with a granularity that makes it easier for them to understand the information stored in the data warehouse.</p><h4>Query Tools</h4><p>One of the main purposes of data storage is to provide businesses with information to make strategic decisions.</p><h3>ETL</h3><p>ETL stands for Extract, Transform, Load, and it refers to a process used in data integration and data warehousing. The ETL process involves the movement and transformation of data from source systems to a target system, typically a data warehouse, where the data can be analyzed and queried.</p><ul><li>It helps companies analyze business data to make critical business decisions.</li><li>Transactional databases cannot answer complex business questions that can be answered by ETL.</li><li>Data Warehouse provides a common data store.</li><li>ETL provides a method of moving data from various sources into the data warehouse.</li><li>As data sources change, the data warehouse will be updated automatically.</li></ul><h4>Extract</h4><p>Data is extracted from the source system to the <em>staging area</em> (not necessarily always). If it is in the transformation area, it is transformed. This way the performance of the source system is not degraded. There are three types of extraction:</p><ol><li>Full Extraction</li><li>Partial Extraction with Update</li><li>Partial Extraction without Update</li></ol><p>Some validation is done during extraction:</p><ul><li>Matching records with source data</li><li>Ensure no spam data is uploaded</li><li>Data type checking</li><li>Removal of all duplicate / fragmented data types</li><li>Checking that all keys are in place</li></ul><h4>Transform</h4><p>The data obtained from the source server cannot be used in its raw and original form. Therefore, it needs to be cleaned, mapped and transformed. This is the key step where the ETL process adds value and changes the data to create insightful BI reports.</p><h4>Load</h4><p>Loading the data into the target data warehouse is the last step of the ETL process. In a typical data warehouse, a huge amount of data needs to be loaded in a relatively short period of time (nights). Therefore, the loading process must be optimized for performance. Load types:</p><ol><li>Initial Load</li><li>Incremental Load</li><li>Full Load</li></ol><p>Some validation is done during the load:</p><ul><li>Make sure that Primary Key (PK) data is not missing or empty.</li><li>Test model views based on target tables.</li><li>Check the merged values and calculated measurements.</li><li>Data should be checked in the dimension table and in the history table.</li><li>Check BI reports in the loaded fact and dimension table.</li></ul><h4>ETL &amp; ELT Differences</h4><p>ELT provides a different perspective on data movement. Instead of the transformation phase, which is the phase before the data is uploaded to the target system, it performs this phase after the upload to the target system. ELT usually uses <em>nosql databases such as Hadoop, data app and cloud upload.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*UBr6Wrvh1PYQSjAs_e6vqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*aofulD1uYMUZr_9ogwLAhA.png" /></figure><h3>Data Modelling</h3><p>It is the process of creating a data model for the data to be stored in the database. Data Modeling is divided into two techniques:</p><ol><li>ER Model</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*FHQ_fmd2RL-7Fqu10CLOvw.png" /></figure><p>2. UML Model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*H0eRGziTzZBPf0aMQVNs9g.png" /></figure><h4>Purposes</h4><ul><li>It provides an accurate representation of all the data objects required by the database.</li><li>Data model helps to design the database at conceptual, physical and logical levels.</li><li>Data Model structure helps to define relational tables, foreign key, primary key and procedures.</li><li>It provides a clear view of the underlying data. It can be used by database developers to create a physical database.</li><li>It also helps to identify missing and redundant data.</li><li>While the initial creation of a Data Model can be labor and time consuming, in the long run it aims to upgrade your IT infrastructure and make it cheaper and faster to maintain.</li></ul><h4>Advantages &amp; Disadvantages</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*2of7WmeJloBG5o7UdrbfGA.png" /></figure><h3>Online Analytical Processing (OLAP)</h3><p>It is a category of software that enables users to analyze information from multiple database systems at the same time. It is a technology that enables analysts to extract and view business data from different angles. OLAP stands for Online Analytical Processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*uzlcZ0-FpkmtM_BI2cHzSQ.png" /></figure><p><strong>OLAP Cube:</strong> At the heart of OLAP is the concept of an OLAP cube. An OLAP cube is a data structure optimized for very fast data analysis. The OLAP cube contains numeric facts that are categorized by dimension. These are called measures. An OLAP cube is also known as a hyper cube.</p><p>Data Warehouse retrieves information from multiple data sources and formats such as txt, excel, multimedia, etc. Extracted data is cleaned and transformed. The data is uploaded to a pre-calculated OLAP server (or OLAP cube) for further analysis. OLAP has four types of analytical processes:</p><ol><li>Roll-up</li><li>Drill-down</li><li>Slice</li><li>Pivot</li></ol><h3>OLAP Hierarchy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*ih3DWESpeE2nLt2r4xuD9A.png" /></figure><h4>ROLAP</h4><p>It works with data in a relational database. Fact and dimension tables are stored as relational tables. It also allows the analysis of multi-dimensional data and is the fastest growing type of OLAP.</p><p><strong>Advantage</strong></p><ul><li>High Data Efficiency: Offers high data efficiency as query performance and access language are optimized specifically for multi-dimensional data analysis.</li><li>Scalability: Offers scalability for managing large amounts of data, even when data is growing.</li></ul><p><strong>Disadvantage</strong></p><ul><li>Demand for Higher Resources: ROLAP requires a high utilization of manpower, software and hardware resources.</li><li>Aggregate Data Limitations: ROLAP tools use SQL for all aggregate data calculations. However, there is no set limit for calculations.</li><li>Slow Query Performance: Compared to MOLAP, it is quite slow.</li></ul><h4>MOLAP</h4><p>MOLAP is a classic OLAP that facilitates data analysis using a multi-dimensional data cube. The data is pre-calculated, pre-summarized and stored in a MOLAP (a big difference from ROLAP).</p><p>Using MOLAP, the user can use different aspects of multidimensional view data. If a relational database is used, multidimensional data analysis is also possible. For this it is necessary to query data from multiple tables. On the contrary, MOLAP already has all possible combinations of data stored in a multidimensional array. MOLAP can access this data directly. Therefore, MOLAP is faster compared to ROLAP.</p><ul><li>Operations are called transactions.</li><li>Processes information with the same amount of response time, regardless of the level of summarization.</li><li>It eliminates the complexity of the design phase of a relational database, where data is stored for analysis.</li><li>The server implements two levels of storage representation to manage dense and sparse data sets.</li><li>If the dataset is sparse, storage utilization can be low.</li><li>Facts are stored in a multidimensional array and the dimension used to query them.</li></ul><p><strong>MOLAP Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHYG8t3T1nK1y5tpqnGutQ.png" /></figure><p><strong>MOLAP Implementation</strong></p><ul><li>It is important to consider both maintenance and storage implications when strategizing cube creation in MOLAP.</li><li>There are a number of specialized languages that we use to query MOLAP, however, such as MDX by Microsoft, which includes extensive click and drag support.</li><li>It is difficult to scale because as the number of dimension increases, the number and size of cubes required will also increase.</li><li>The API is also used in the cube logic.</li><li>You may need different skill sets and tools for the database administrator to create and maintain databases.</li></ul><p><strong>Advantage</strong></p><ul><li>It can manage, analyze and store significant amounts of multi-dimensional data.</li><li>Fast query performance due to optimized storage, indexing and caching.</li><li>Offers smaller data sizes than a relational database.</li><li>Provides automatic calculation of higher aggregation data.</li><li>Helps users analyze larger and less defined data.</li><li>It is easier for users. Therefore, it is a suitable model for inexperienced users.</li><li><em>MOLAP cubes are built for fast data acquisition.</em> Ideal for slicing and dicing operations.</li><li>All calculations are done in advance when the cube is created.</li></ul><p><strong>Disadvantage</strong></p><ul><li>One of its weakest aspects is that it is less scalable than ROLAP as only a limited amount of data is processed.</li><li>It is resource intensive and therefore offers data redundancy.</li><li>It can be lengthy, especially with large data volumes.</li><li>It may encounter problems when updating and querying models when the number of dimensions is more than 10.</li><li>It cannot contain detailed data.</li><li>Storage utilization can be low if the dataset is highly distributed.</li><li>It can only manage a limited amount of data. Therefore, it is not possible to add large amounts of data inside the cube.</li></ul><h4><strong>Hybrid OLAP</strong></h4><p>HOLAP is a mixture of both ROLAP and MOLAP. It offers the fast computation of MOLAP and the higher scalability of ROLAP. HOLAP uses two databases.</p><ol><li>The collected or calculated data is stored in a multidimensional OLAP cube.</li><li>Detailed information is stored in a relational database.</li></ol><p><strong>Advantage</strong></p><ul><li>It helps to economize disk space and also helps to avoid problems with access speed and convenience.</li><li>HOLAP uses cube technology which provides faster performance for all data types.</li><li>ROLAP is updated instantly and HOLAP users can access this real-time instantly updated data. MOLAP provides data cleaning and transformation. This increases the connectivity of the data.</li></ul><p><strong>Disadvantage</strong></p><ul><li>Most Complex Level: The biggest disadvantage of HOLAP systems is that they support both ROLAP and MOLAP tools and applications. It is therefore very complex.</li><li>Potential conflicts: There are many potential conflicts, especially in terms of functionality.</li></ul><h3>Dimensional Model</h3><p>It is a data structure technique optimized for data storage. It consists of <strong>fact</strong> and <strong>dimension</strong> tables. It is designed to read, summarize, and analyze numeric information in the data warehouse, such as values, balances, counts, or weights. In contrast, in a relational modeling, the insertion, update and deletion of data is optimized as a real-time system. They are used in data warehouse systems and are not suitable for relational systems.</p><p><strong>Fact: </strong>These are the tables where calculations are made in business intelligence projects. They are tables that can be more than one according to the need and contain our measure values. In other words, they are tables with variables that can be calculated.</p><p><strong>Dimension: </strong>Provides the content surrounding the business process event. In simple terms, it answers the who, what, where questions of the fact.</p><p><strong>Attribute: </strong>They represent Dimensions. They are used to search, filter or classify facts. There are attributes within Dimension tables.</p><p><strong>Fact Table: </strong>It is positioned as a primary table in the Dimensional Model.</p><h3>Star Schema</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*Z4Q2mTbcc-B2k76LLCtzzw.png" /></figure><ul><li>Each dimension represents a dimension table.</li><li>Dimension tables have attributes.</li><li>Dimension table is connected to fact table with FK key.</li><li>Dimension tables are not linked to each other.</li><li>Fact table can contain key and measue.</li><li>The Star schema is easy to understand and requires minimal disk storage.</li><li>Dimension tables are not normalized.</li><li>Schemas are widely supported by BI tools.</li></ul><h3>Snowflake Schema</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*wHKpWLmbaJyYBWk2S8x6HQ.png" /></figure><ul><li>The main benefit is that it uses less disk space.</li><li>It is easy to add dimension to the schema.</li><li>Query performance suffers due to multiple tables.</li><li>The biggest challenge is that you need to do more maintenance work due to more lookup tables.</li></ul><h4>Star &amp; Snowflake Differences</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*5fiADU4JvM-q3-XudI985w.png" /></figure><h3>Data Mart</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*J0ZH_gFaRa41-jP4TFfdhg.png" /></figure><p>Data Mart is a condensed version of a data warehouse and is designed to be used by a specific department, unit or group of users in an organization. Data Mart typically receives data from only a few sources compared to a data warehouse. Data marts are smaller and more flexible than a data warehouse.</p><h3>Data Lake</h3><p>Data Lake is a repository that can hold large amounts of structured, semi-structured and unstructured data. It is a place to store any type of data in its own format, without a fixed limitation on account size or file. It offers high data volumes to improve analytical performance and native integration.</p><p>Data Lake is like a big container, very similar to real lakes and rivers. Like a lake, it has multiple tributaries. The main purpose of building a Data Lake is to provide data scientists with a defined data view.</p><p>Reasons for using Data Lake:</p><ul><li>With the introduction of storage engines like Hadoop, it has become easier to store different information. There is no need to model data in an enterprise-wide schema with data lake.</li><li>With the increase in data volume, data quality and metadata, the quality of analysis also increases.</li><li>Data lake offers business agility.</li><li>It offers competitive advantage to the implementing organization.</li><li>There is no data warehouse structure. It provides a 360-degree view and makes the analysis more robust.</li></ul><h3>Summary</h3><p>Data Warehouse is a structure where data is taken from its source, cleaned, transformed and loaded into a pre-computed OLAP server for analysis. OLAP supports four types of analytical operations such as roll-up, drill-down, slice and pivot. ROLAP works with data contained in a relational database, while MOLAP uses a multidimensional data cube. HOLAP is a mixture of ROLAP and MOLAP. The dimensional model consists of fact and dimension tables and uses star or snowflake schemas. Data Mart is a subset of a data warehouse and is used by a specific department or user group, while a data lake is a repository for structured, semi-structured and unstructured data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34c76111161f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RFM Analysis]]></title>
            <link>https://medium.com/@TalhaNebiKumru/rfm-analysis-34e0b53bfc70?source=rss-2f9aee9f265b------2</link>
            <guid isPermaLink="false">https://medium.com/p/34e0b53bfc70</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[crm]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-engineer]]></category>
            <dc:creator><![CDATA[Talha Nebi Kumru]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 16:02:02 GMT</pubDate>
            <atom:updated>2023-01-30T16:02:02.158Z</atom:updated>
            <content:encoded><![CDATA[<p>RFM Analysis is a statistical analysis method used to identify key customer segments by measuring customers purchasing habits. It is the process of labeling customers by determining the Recency, Frequency and Monetary values of their purchases and ranking them on a scoring model. It provides the opportunity to take data-based actions on many topics for CRM studies. After the definition article will follow with project. Project steps are;</p><p>1. Business Problem</p><p>2. Data Understanding</p><p>3. Data Preparation</p><p>4. Calculating RFM Metrics</p><p>5. Calculating RFM Scores</p><p>6. Creating &amp; Analysing RFM Segments</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*_md1LegoGvecVJLRnqO_gA.png" /></figure><h3><strong>Recency, Frequency, Monetary Metrics</strong></h3><ul><li><strong>Recency</strong>: Data on how recently a customer made a purchase</li></ul><p>Recency Value = (Today Day)-(Customer’s Last Transaction Day)</p><p>The lower the Recency Value in the RFM analysis, the higher the customer’s score (Rs) should be.</p><p>· <strong>Frequency</strong>: Data on how often a customer makes a purchase</p><p>The total number of purchase transactions for each customer in the customer database is calculated as the Frequency Value. Although there are many products made at the same time, this should be considered as a single purchase.</p><p>The higher the Frequency Value in the RFM analysis, the higher the client’s score (Fs) should be.</p><p>· <strong>Monetary</strong>: Data on how much money a customer spends on their purchase.</p><p>Total sales turnover of each of the customers is determined separately and calculated as Amount Value. The higher the Amount Value in the RFM analysis, the higher the customer’s score (Ms) should be.</p><p>As a result of the RFM analysis, each customer ranks each of these three categorical values numerically on a simple scale scale. According to the ranking, the “Best” customer will be the customer with the highest score in each category. Generally, this ranking is done between 1 and 5, as well as with letters (A, B, C, …), special name tags (Platinum, Gold, Classic etc.) or adjective definitions (Champions, Coming Soon, Loyal Customers etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*-ffLoDSHKpXEYLSGMP2urA.png" /></figure><h3>RFM Analysis Project</h3><h4><strong>Business Problem</strong></h4><p>An e-trade company wants make segmentations to customers for strategy formulation about marketing.</p><h4>Company Dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*LbxjC9P0nL0NEYTonvNYpw.jpeg" /></figure><p><strong>master_id</strong>: Unique customer number.<br><strong>order_channel</strong>: Shopping platform (Android, ios, Desktop, Mobile)<br><strong>last_order_channel</strong>: Last shopped platform<br><strong>first_order_date</strong>: First shopped date<br><strong>last_order_date</strong>: Last shopped date<br><strong>last_order_date_online</strong>: Last shopped on online date<br><strong>last_order_date_offline</strong>: Last shopped on offline date<br><strong>order_num_total_ever_online</strong>: Shopping count on online<br><strong>order_num_total_ever_offline</strong>: Shopping count on offline<br><strong>customer_value_total_ever_offline</strong>: Total spending price on offline<br><strong>customer_value_total_ever_online</strong>: Total spending price on online<br><strong>interested_in_categories_12</strong>: Shopped which categories last 12 months</p><h4><strong>Data Understanding</strong></h4><pre>import pandas as pd<br>import datetime as dt<br><br>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;3%f&#39; % x)</pre><p>Import the necessary libraries what will use. Set option to display whole columns and display 3 digit after comma.</p><pre>df_ = pd.read_csv(&quot;datasets/flo_data_20k.csv&quot;)<br>df = df_.copy()<br><br>df.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6Ygz46EcFofkMuOJ2_Efg.png" /></figure><pre>df.dtypes<br><br># Output<br><br>master_id                             object<br>order_channel                         object<br>last_order_channel                    object<br>first_order_date                      object<br>last_order_date                       object<br>last_order_date_online                object<br>last_order_date_offline               object<br>order_num_total_ever_online          float64<br>order_num_total_ever_offline         float64<br>customer_value_total_ever_offline    float64<br>customer_value_total_ever_online     float64<br>interested_in_categories_12           object<br>dtype: object</pre><pre>df.groupby(&quot;order_channel&quot;).agg({&quot;master_id&quot;: &quot;count&quot;})<br><br># Output<br><br>               master_id<br>order_channel           <br>Android App         9495<br>Desktop             2735<br>Ios App             2833<br>Mobile              4882</pre><p>When see the outputs, customers select android app more than the others. When see the data types, date columns types are object. Firstly should to change types to datetime.</p><pre>def change_date(dataframe, variable):<br>    dataframe[variable] = dataframe[variable].astype(&quot;datetime64[ns]&quot;)<br>    <br>change_date(df, &quot;first_order_date&quot;)<br>change_date(df, &quot;last_order_date&quot;)<br>change_date(df, &quot;last_order_date_online&quot;)<br>change_date(df, &quot;last_order_date_offline&quot;)<br><br>spend_statistics = df.groupby(&quot;master_id&quot;).agg({<br>    &quot;order_num_total_ever_online&quot;: lambda on: on.sum(),<br>    &quot;order_num_total_ever_offline&quot;: lambda off: off.sum(),<br>    &quot;customer_value_total_ever_online&quot;: lambda price: price.sum(),<br>    &quot;customer_value_total_ever_offline&quot;: lambda price: price.sum()<br>    }).rename(columns={&quot;order_num_total_ever_online&quot;: &quot;online_count&quot;, <br>                       &quot;order_num_total_ever_offline&quot;:&quot;offline_count&quot;, <br>                       &quot;customer_value_total_ever_online&quot;:&quot;total_online&quot;, <br>                       &quot;customer_value_total_ever_offline&quot;:&quot;total_offline&quot;})<br>spend_statistics.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*OygDita3j6qLSE4PTt16VQ.jpeg" /></figure><h4>Data Preparation &amp; Calculating RFM Metrics</h4><pre>spend_statistics[&quot;total_count&quot;] = spend_statistics[&quot;online_count&quot;] + spend_statistics[&quot;offline_count&quot;]<br>spend_statistics[&quot;total_price&quot;] = spend_statistics[&quot;total_online&quot;] + spend_statistics[&quot;total_offline&quot;]<br><br>last_date = df[&quot;last_order_date&quot;].max() # 2021-05-30<br>today_date = dt.datetime(2021, 6, 1)<br><br>spend_statistics[&quot;recency_days&quot;] = df.groupby(&quot;master_id&quot;).agg({<br>    &quot;last_order_date&quot;: lambda date: (today_date - date.max()).days})<br><br>spend_statistics[&quot;total_count&quot;] = spend_statistics[&quot;total_count&quot;].astype(&quot;int&quot;)<br><br>rfm = spend_statistics[[&quot;recency_days&quot;, &quot;total_count&quot;, &quot;total_price&quot;]]<br>rfm.columns = [&quot;recency&quot;, &quot;frequency&quot;, &quot;monetary&quot;]</pre><h4>Calculating RFM Scores</h4><pre>rfm[&quot;recency_score&quot;] = pd.qcut(rfm[&quot;recency&quot;], 5, labels=[5, 4, 3, 2, 1])<br>rfm[&quot;frequency_score&quot;] = pd.qcut(rfm[&quot;frequency&quot;].rank(method=&#39;first&#39;), 5, labels=[1, 2, 3, 4, 5])<br>rfm[&quot;monetary_score&quot;] = pd.qcut(rfm[&quot;monetary&quot;], 5, labels=[1, 2, 3, 4, 5])<br><br>rfm[&quot;RF_SCORE&quot;] = rfm[&quot;recency_score&quot;].astype(&quot;string&quot;) + rfm[&quot;frequency_score&quot;].astype(&quot;string&quot;)</pre><h4>Creating &amp; Analysis RFM Segments</h4><pre>seg_map = {<br>    r&#39;[1-2][1-2]&#39;: &#39;hibernating&#39;,<br>    r&#39;[1-2][3-4]&#39;: &#39;at_risk&#39;,<br>    r&#39;[1-2]5&#39;: &#39;cant_loose&#39;,<br>    r&#39;3[1-2]&#39;: &#39;about_to_sleep&#39;,<br>    r&#39;33&#39;: &#39;need_attention&#39;,<br>    r&#39;[3-4][4-5]&#39;: &#39;loyal_customers&#39;,<br>    r&#39;41&#39;: &#39;promising&#39;,<br>    r&#39;51&#39;: &#39;new_customers&#39;,<br>    r&#39;[4-5][2-3]&#39;: &#39;potential_loyalists&#39;,<br>    r&#39;5[4-5]&#39;: &#39;champions&#39;<br>}<br><br>rfm[&#39;segment&#39;] = rfm[&#39;RF_SCORE&#39;].replace(seg_map, regex=True)<br>rfm.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*CmBtU-4tqPMoDGCr84eaPw.png" /></figure><p>After all this segmentation, You can analyze what you want.</p><h3>Conclusion</h3><p>RFM shows to customers behaviour so that company make campaigns their behaviour. Project gives us how to code RFM Analysis. Happy coders.</p><h3>Author</h3><p><strong>Talha Nebi Kumru</strong>: <a href="https://www.linkedin.com/in/talha-nebi-kumru-929859183/">https://www.linkedin.com/in/talha-nebi-kumru-929859183/</a></p><p><strong>Hazal Hanay</strong>: <a href="https://www.linkedin.com/in/hazal-hanay-361351172/">https://www.linkedin.com/in/hazal-hanay-361351172/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34e0b53bfc70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CLTV Prediction with BG-NBD and Gamma Gamma]]></title>
            <link>https://medium.com/@TalhaNebiKumru/cltv-prediction-with-bg-nbd-and-gamma-gamma-2179ded9fa6c?source=rss-2f9aee9f265b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2179ded9fa6c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[crm]]></category>
            <dc:creator><![CDATA[Talha Nebi Kumru]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 12:36:29 GMT</pubDate>
            <atom:updated>2023-01-29T13:39:16.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*oaohmb-pmDuGUWcYD9MvHg.jpeg" /></figure><p>CLTV means money unit that is income to company from customer. CLTV is reliable for long-term period more than short-term period.</p><p><strong>Life Time Value = </strong>Average Value of Sale * Number of Transactions * Retention Time Period</p><p><strong>Customer Lifetime Value = </strong>Lifetime Value * Profit Margin</p><p>After definition, make to project with these steps:</p><ol><li>Data Preparation</li><li>Expected Number of Transaction with BG-NBD</li><li>Expected Average Profit with Gamma Gamma</li><li>Calculate CLTV with BG-NBD and Gamma Gamma</li><li>Segmentation with CLTV</li></ol><h3>BG-NBD</h3><p>Beta Geometric / Negative Binomial Distribution known as BG-NBD Model. It gives us the conditional expected number of transactions in the next period. This model can answer the following questions:</p><ul><li>How many transactions will be next week?</li><li>How many transactions will be in the next 3 months?</li><li>Which customers will do the most purchases in the next 2 weeks?</li></ul><p>BG-NBD is known as “Till You Die” model. After these make to project with BG-NBD model using by Lifetimes library.</p><h3><strong>Gamma Gamma</strong></h3><p>For more efficient analyze, need to average profit. Gamma Gamma gives average profit to each customers.</p><h3>CLTV with BG-NBD and Gamma Gamma</h3><p>Project purpose is showing to how to use BG-NBD and Gamma Gamma model and how to calculate CLTV.</p><h4>Data Preparation</h4><pre>import pandas as pd<br><br>import datetime as dt                          <br><br>from lifetimes import BetaGeoFitter<br>from lifetimes import GammaGammaFitter<br>from lifetimes.plotting import plot_period_transactions<br><br>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;%3f&#39; % x)<br><br>df_ = pd.read_csv(&quot;datasets/flo_data_20k.csv&quot;)<br>df = df_.copy()<br>                      <br>def outlier_thresholds(dataframe, variable):<br>    quartile1 = dataframe[variable].quantile(0.01)<br>    quartile3 = dataframe[variable].quantile(0.99)<br>    interquantile_range = quartile3 - quartile1<br>    up_limit = quartile3 + 1.5 * interquantile_range<br>    low_limit = quartile1 - 1.5 * interquantile_range<br>    <br>    return round(low_limit), round(up_limit)<br><br>def replace_with_threshold(dataframe, variable):<br>    low_limit, up_limit = outlier_thresholds(dataframe, variable)<br>    dataframe.loc[(dataframe[variable] &gt; up_limit), variable] = up_limit<br><br>replace_with_threshold(df, &quot;order_num_total_ever_online&quot;)<br>replace_with_threshold(df, &quot;order_num_total_ever_offline&quot;)<br>replace_with_threshold(df, &quot;customer_value_total_ever_offline&quot;)<br>replace_with_threshold(df, &quot;customer_value_total_ever_online&quot;)</pre><p>Import libraries what will use. Set options about pandas dataframes. Read / copy csv file. Make functions for get up limit and low limit. Set / replace up limit. Lets see dataframe variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*JY9ZaJx3PHG7dxGtVHQYrA.png" /></figure><p><strong>master_id</strong>: Unique customer number.<br><strong>order_channel</strong>: Shopping platform (Android, ios, Desktop, Mobile)<br><strong>last_order_channel</strong>: Last shopped platform<br><strong>first_order_date</strong>: First shopped date<br><strong>last_order_date</strong>: Last shopped date<br><strong>last_order_date_online</strong>: Last shopped on online date<br><strong>last_order_date_offline</strong>: Last shopped on offline date<br><strong>order_num_total_ever_online</strong>: Shopping count on online<br><strong>order_num_total_ever_offline</strong>: Shopping count on offline<br><strong>customer_value_total_ever_offline</strong>: Total spending price on offline<br><strong>customer_value_total_ever_online</strong>: Total spending price on online<br><strong>interested_in_categories_12</strong>: Shopped which categories last 12 months</p><pre>def change_date(dataframe, variable):<br>    dataframe[variable] = dataframe[variable].astype(&quot;datetime64[ns]&quot;)<br>    <br>change_date(df, &quot;first_order_date&quot;)<br>change_date(df, &quot;last_order_date&quot;)<br>change_date(df, &quot;last_order_date_online&quot;)<br>change_date(df, &quot;last_order_date_offline&quot;)</pre><p>Make function for changing data types. Converting string date types to datetime.</p><pre>last_date = df[&quot;last_order_date&quot;].max() # 2021-05-30<br>analyze_date = dt.datetime(2021, 6, 1)<br><br>df[&quot;total_order_count&quot;] = df[&quot;order_num_total_ever_online&quot;] + df[&quot;order_num_total_ever_offline&quot;]<br>df[&quot;total_price&quot;] = df[&quot;customer_value_total_ever_offline&quot;] + df[&quot;customer_value_total_ever_online&quot;]<br><br>cltv = df[[&quot;master_id&quot;, &quot;total_order_count&quot;]]<br><br>cltv[&quot;recency&quot;] = (df[&quot;last_order_date&quot;] - df[&quot;first_order_date&quot;]) \<br>    .apply(lambda date: date.days)<br>    <br>cltv[&quot;T&quot;] = (analyze_date - df[&quot;first_order_date&quot;]) \<br>    .apply(lambda date: date.days)<br>    <br>cltv[&quot;monetary&quot;] = df[&quot;total_price&quot;] / df[&quot;total_order_count&quot;]<br><br>cltv.columns = [&quot;master_id&quot;, &quot;frequency&quot;, &quot;recency_cltv_weekly&quot;, &quot;T_weekly&quot;, &quot;monetary_cltv_avg&quot;]<br><br>cltv = cltv[cltv[&quot;frequency&quot;] &gt; 1]<br><br>cltv[&quot;frequency&quot;] = cltv[&quot;frequency&quot;].astype(&quot;int&quot;)<br><br>cltv[&quot;recency_cltv_weekly&quot;] = cltv[&quot;recency_cltv_weekly&quot;] / 7<br>cltv[&quot;T_weekly&quot;] = cltv[&quot;T_weekly&quot;] / 7</pre><p>Making CLTV parameters. Firstly get latest date. After that set to analyze_date for T value. Creating cltv dataframe. Calculating recency, T, monetary and frequency. Finally initialize to CLTV parameters for format.</p><h4>Expected Number of Transaction with BG-NBD</h4><pre>bgf = BetaGeoFitter(penalizer_coef=0.001)<br><br>bgf.fit(cltv[&quot;frequency&quot;],<br>        cltv[&quot;recency_cltv_weekly&quot;],<br>        cltv[&quot;T_weekly&quot;])<br><br>cltv[&quot;exp_sales_3_month&quot;] = bgf \<br>    .conditional_expected_number_of_purchases_up_to_time(12, cltv[&quot;frequency&quot;], <br>                                                         cltv[&quot;recency_cltv_weekly&quot;], <br>                                                         cltv[&quot;T_weekly&quot;])<br>    <br>cltv[&quot;exp_sales_6_month&quot;] = bgf \<br>    .conditional_expected_number_of_purchases_up_to_time(24, cltv[&quot;frequency&quot;], <br>                                                         cltv[&quot;recency_cltv_weekly&quot;], <br>                                                         cltv[&quot;T_weekly&quot;])</pre><p>Making BG-NBD model. After that fitting model for 3 / 6 months prediction. Lets compare to reel value with BG-NBD results.</p><pre>plot_period_transactions(bgf)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*6TTLoXjaLbq4vJa1RYAR5g.png" /></figure><h4>Expected Average Profit with Gamma Gamma</h4><pre>ggf = GammaGammaFitter(penalizer_coef=0.01)<br><br>ggf.fit(cltv[&quot;frequency&quot;], cltv[&quot;monetary_cltv_avg&quot;])<br><br>cltv[&quot;exp_average_value&quot;] = ggf \<br>    .conditional_expected_average_profit(cltv[&quot;frequency&quot;], cltv[&quot;monetary_cltv_avg&quot;])</pre><p>Creating Gamma Gamma model. After that set variable for expected average profit for each customer.</p><h4>Calculate CLTV with BG-NBD and Gamma Gamma</h4><pre>exp_6_month_end = ggf.customer_lifetime_value(bgf, <br>                                          cltv[&#39;frequency&#39;],<br>                                          cltv[&#39;recency_cltv_weekly&#39;], <br>                                          cltv[&#39;T_weekly&#39;], <br>                                          cltv[&#39;monetary_cltv_avg&#39;],<br>                                          time=6, # Month<br>                                          freq=&quot;W&quot;,<br>                                          discount_rate=0.01)<br>cltv[&quot;cltv&quot;] = exp_6_month_end</pre><p>Calculating CLTV for 6 months with BG-NBD and Gamma Gamma models.</p><h4>Segmentation with CLTV</h4><pre>cltv[&quot;segment&quot;] = pd.qcut(cltv[&quot;cltv&quot;], 4, labels=[&quot;D&quot;, &quot;C&quot;, &quot;B&quot;, &quot;A&quot;])</pre><p><strong>output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*RBw0BY4HQN-FcGHejGErUQ.png" /></figure><h3>Conclusion</h3><p>CRM Analytics is wanted more with nowadays. CLTV and CLTV Prediction are one of them for CRM Analytics. Happy codes.</p><h4>Authors</h4><p><strong>Talha Nebi Kumru</strong>: <a href="https://www.linkedin.com/in/talha-nebi-kumru-929859183/">https://www.linkedin.com/in/talha-nebi-kumru-929859183/</a></p><p><strong>Hazal Hanay</strong>: <a href="https://www.linkedin.com/in/hazal-hanay-361351172/">https://www.linkedin.com/in/hazal-hanay-361351172/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2179ded9fa6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Processing, Optimization, Transformation to Apache Hive, PostgreSQL and Delta Lake on Apache…]]></title>
            <link>https://medium.com/@TalhaNebiKumru/data-processing-optimization-transformation-to-apache-hive-postgresql-and-delta-lake-on-apache-941b564ddc35?source=rss-2f9aee9f265b------2</link>
            <guid isPermaLink="false">https://medium.com/p/941b564ddc35</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Talha Nebi Kumru]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 04:34:52 GMT</pubDate>
            <atom:updated>2023-01-27T04:36:38.072Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Processing, Optimization, Transformation to Apache Hive, PostgreSQL and Delta Lake on Apache Spark</h3><p>On the way of being Data Engineer / Data Scientist. I like manage data, that is why I want.</p><p>The problems increases with more data in big data world. The main problem is data processing has more cost with data memory has more disk usage. However there are many solutions but one of them is The Apache Spark. In this article;</p><ul><li>What is Apache Spark?</li><li>How to optimize Apache Spark?</li><li>What is Delta Lake?</li><li>Apache Spark Project.</li></ul><p>This project is versatile. Project follows these steps:</p><ol><li>Run Apache Hadoop, Apache Hive</li><li>Execute Apache Spark by PySpark with Delta Lake configuration</li><li>Read / Process Data</li><li>Optimize Apache Spark. Save data on Apache Hive, PostgreSQL and Delta Lake</li><li>Import saved data from Apache Hive, PostgreSQL and Delta Lake.</li><li>Stop Apache Spark</li></ol><h3>What is Apache Spark?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*kNBQi-vVM_J3vaqHS_HBWw.png" /></figure><p>Apache Spark is a multi-language engine for executing data engineering, data science, and machine learning on single-node machines or clusters.</p><h4>Purpose</h4><p>Spark is comfortable area for multi-clusters. That means spark has got many applications such as Scala, Python, Java, R, SQL ext. Spark contains special SQL module order that Spark streams real-time data. In fact Spark has got graph engine which contains machine learning library therefore Spark is the most famous multi-language engine in area.</p><h4>Distributed Data and Distributed IT</h4><p>The distributed computer system(dcs) which has got many computers run as a system that contains many software components. Dcs can connect localhost to each others. Dcs can be any numbers of computers such as mini computers, main computers, personal computers ext. Dcs purpose is “dcs should run like one computer”. Anyway in dcs, whole computers are node, all computers are cluster.</p><h4>Processing Engine</h4><p>The processing engine uses structure of distributed parallel programming that can processes big data that is distributed many nodes. It should process to source. Typical processing engines are;</p><ul><li>Batch Processing</li><li>Streaming</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*7mOaYgpDW72QE8N8R-k5pQ.png" /><figcaption>Apache Spark Ecosystem</figcaption></figure><h4>Spark Core API</h4><p>Spark Core is built-in platform from other function. Spark Core contains API for function in memory, model that is support different applications, useful programming languages. There are basic components in Spark Core:</p><ul><li>Memory Usage</li><li>Error Recovery</li><li>Storage / Distribute Job</li></ul><h4>Streaming</h4><p>Streaming supports processing real-time data. For example, message queues.</p><h4>MLlib Machine Learning</h4><p>Spark comes with Machine Learning(ML) library. MLlib supports classification, regression, clustering, filtering ext. algorithms. In order that it can import / export data.</p><h4>Spark SQL + DataFrames</h4><p>Spark SQL is Spark module that can processes structured data. It supports abstract programming as DataFrames. Also it can be like SQL query engine.</p><h4>GraphX Graph Computation</h4><p>This is library which can manipulate graphs and calculate parallel graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*TONz8NH2VI6DUkEbQE7sDA.png" /><figcaption>Apache Spark Architecture</figcaption></figure><h4>Driver Program</h4><p>Driver program runs the main function and makes SparkContext class. Purpose of SparkContext is coordination of spark applications as independent clusters on a cluster.</p><h4>Cluster Manager</h4><p>The Role of Cluster Manager separates sources in applications. Spark can run on many clusters:</p><ul><li>YARN</li><li>Mesos</li><li>Kubernetes</li><li>Standalone Scheduler</li><li>Local</li></ul><h4>Worker Node</h4><p>Worker Node is the dependent node. It’s role is running application code in cluster.</p><h4>Executer</h4><p>Executer is operation for an application in work node. It executes tasks. After that it storages data between disk memory or nodes. It reads / writes data to external sources. Whole applications has own executer.</p><h4>Task</h4><p>Task is job unit that will send to application.</p><h3>How to Optimize Apache Spark?</h3><p>There are many options for optimizing Apache Spark. These can be faster execution and efficient execution.</p><h4>Caching and Persistence of Data</h4><p>In Spark they are synonymous. Two API calls cache() and persist(), offer these capabilities. The latter provides more control over how and where your data is stored. It can be in memory and on disk so serialized and unserialized. Both contribute to better performance for frequently accessed DataFrames or tables. How to use;</p><pre>df = ...<br>df.cache() # Cache created</pre><h4>Bucketing</h4><p>For more performance, it should avoid shuffle. Shuffle means disk I/O and network cost. If there are few trade off data in out of executor, it will gives more performance. Bucketing is used for more performance. It is relation with data organization. CPU needs and Latency are decreased with bucketing but writing cost is increased. It can used with partitioning. Hashing algorithm specify bucketing using on where. Bucketing number can be set in creating table. How to use;</p><pre>spark = ...<br>spark.conf.set(&quot;spark.sql.sources.bucketing.enabled&quot;, True)<br><br>df = ...<br>df.write /<br>  .bucketBy(&lt;bucket number&gt;, &quot;&lt;column_name&quot;)</pre><h4>Partitioning</h4><p>It is also for avoiding shuffle. It is relation with data organization. It is folder which contains / storages categoric columns. Performance is increased that is why same categories are in same folder. How to use;</p><pre>df = ...<br>df.write \<br>  .partitionBy(&quot;&lt;column_name&quot;)</pre><h4>Shuffle Partitions</h4><p>Shuffle Partitions means distributed part number when data is shuffling. Default number is 200. It can be bad performance, if there are too many / few shuffle partition number. How to use;</p><pre>spark = ...<br>spark.conf.set(&quot;spark.sql.shuffle.partitions&quot;, &lt;shuffle_partition_number&gt;)</pre><h4>Adaptive Query Execution</h4><p>Adaptive Query Execution sets optimized shuffle partition number. It can more performance. Default is false. How to use;</p><pre>spark = ...<br>spark.conf.set(&quot;spark.sql.adaptive.enabled&quot;, True)</pre><h3>What is Delta Lake?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*6oNE5oCiddsL01fkMHISVg.png" /></figure><p>Delta Lake is an open source storage layer that brings reliability to data lakes. Delta Lakes provides ACID transactions, scalable metadata handling, and unifies streaming and batch data processing. Delta Lake runs on top of your existing data lake and is fully compatible with Apache Spark APIs.</p><h3>Project</h3><p>Project purposes showing how to data processing with Apache Spark, how to optimize Apache Spark and how to integrate Apache Spark with Apache Hive, PostgreSQL and Delta Lake.</p><h4>Run Apache Hadoop, Apache Hive</h4><pre>%HADOOP_HOME%\sbin\start-all.cmd<br>%DERBY_HOME\bin\StartNetworkServer -h 0.0.0.0<br>hive --service schematool -dbType derby -initSchema<br>hive --service hiveserver2 start</pre><h4>Execute Apache Spark by Pyspark with Delta Lake configuration</h4><pre>import findspark<br><br>from pyspark.sql import SparkSession, functions as F<br><br>findspark.init(&quot;C:\Program Files\Spark\spark-3.3.1-bin-hadoop3&quot;) # SPARK_HOME direction path<br><br>spark = SparkSession.builder \<br>    .master(&quot;yarn&quot;) \<br>    .appName(&quot;Data Processing with Spark&quot;) \<br>    .config(&quot;spark.jars.packages&quot;, &quot;io.delta:delta-core_2.12:2.2.0&quot;) \ # For delta lake<br>    .config(&quot;spark.sql.extensions&quot;, &quot;io.delta.sql.DeltaSparkSessionExtension&quot;) \ # For delta lake<br>    .config(&quot;spark.sql.catalog.spark_catalog&quot;, &quot;org.apache.spark.sql.delta.catalog.DeltaCatalog&quot;) # For delta lake \<br>    .enableHiveSupport() \<br>    .getOrCreate()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mASNEr0ASIlKU5hPZ4_y5A.png" /></figure><p>Control to “Apache Spark is running on Apache Hadoop”</p><h4>Read / Process Data</h4><pre># Read data<br><br>thy = spark.read \<br>    .option(&quot;header&quot;, True) \ # Data contains headers<br>    .option(&quot;inferSchema&quot;, True) \ # Spark can initialize column&#39;s data types<br>    .option(&quot;sep&quot;, &quot;,&quot;) \ # Set to column seperation character <br>    .csv(&quot;datasets/thy_data.txt&quot;) # Set to dataset path<br><br>thy.cache() # It is for optimization<br><br>thy.columns<br><br># Output<br>[&#39;SEASON&#39;, &#39;ORIGIN&#39;, &#39;DESTINATION&#39;, &#39;PSGR_COUNT&#39;]</pre><p>Let understand to data. Data contains four columns. Dataset gives to their information.</p><ul><li><strong>SEASON:</strong> Season information.</li><li><strong>ORIGIN:</strong> Starting airport.</li><li><strong>DESTINATION: </strong>Ending airport.</li><li><strong>PSGR_COUNT: </strong>Passenger count in plane.</li></ul><pre>thy.printSchema()<br><br># Output<br><br>root<br> |-- SEASON: string (nullable = true)<br> |-- ORIGIN: string (nullable = true)<br> |-- DESTINATION: string (nullable = true)<br> |-- PSGR_COUNT: integer (nullable = true)</pre><p>Understand to data contains three strings value and one integer value.</p><pre>thy.count()<br><br># Output<br><br>1719202<br><br>thy.show(5)<br><br># Output<br><br>+------+------+-----------+----------+<br>|SEASON|ORIGIN|DESTINATION|PSGR_COUNT|<br>+------+------+-----------+----------+<br>|SUMMER|   227|        YYZ|         6|<br>|SUMMER|   224|        222|         3|<br>|SUMMER|   226|        JF8|         1|<br>|SUMMER|   227|        3RG|        11|<br>|SUMMER|   227|        6RV|       245|<br>+------+------+-----------+----------+<br><br>thy.select(&quot;SEASON&quot;).distinct().show()<br><br># Output <br><br>+------+<br>|SEASON|<br>+------+<br>|WINTER|<br>|SUMMER|<br>+------+</pre><p>When see the data, season has only two different value. It can be more efficient if season data change to bool but project is about data engineering more than data analyze.</p><pre>thy.select(F.countDistinct(&quot;Origin&quot;).alias(&quot;Origin nunique&quot;)).show()<br><br># Output<br><br>+--------------+<br>|Origin nunique|<br>+--------------+<br>|          4210|<br>+--------------+</pre><p>It is the other option to find nunique output. Company has too many different origin as seen.</p><pre>seasonal_statistics = thy.groupBy(F.col(&quot;SEASON&quot;)) \<br>    .agg(F.sum(&quot;PSGR_COUNT&quot;).alias(&quot;TOTAL_PSGR_COUNT&quot;),<br>         F.avg(&quot;PSGR_COUNT&quot;).alias(&quot;AVG_PSGR_COUNT&quot;),<br>         F.count(&quot;PSGR_COUNT&quot;).alias(&quot;COUNT&quot;)) <br>seasonal_statistics.show() <br><br># Output<br><br>+------+----------------+-----------------+------+<br>|SEASON|TOTAL_PSGR_COUNT|   AVG_PSGR_COUNT| COUNT|<br>+------+----------------+-----------------+------+<br>|WINTER|       336882094|420.1829420855103|801751|<br>|SUMMER|       521002675|567.8806552066541|917451|<br>+------+----------------+-----------------+------+</pre><p>When see the output, people prefer summer to winter for travelling.</p><h4>Optimize Apache Spark. Save data on Apache Hive, PostgreSQL and Delta Lake</h4><pre># Optimization Part<br><br>spark.conf.set(&quot;spark.sql.sources.bucketing.enabled&quot;, True)<br>spark.conf.set(&quot;spark.sql.adaptive.enabled&quot;, True)<br><br># Write on Apache Hive<br><br>seasonal_statistics.write \<br>    .format(&quot;orc&quot;) \ # source format type<br>    .mode(&quot;overwrite&quot;) \ # save mode type<br>    .partitionBy(&quot;SEASON&quot;) # Optimization part<br>    .bucketBy(15, &quot;ORIGIN&quot;) # Optimization part<br>    .saveAsTable(&quot;thy.season_origin_orc&quot;)<br><br># Write on PostgreSQL<br><br>jdbcUrl = &quot;jdbc:postgresql://localhost:5432/thy?user=postgres&amp;password=password&quot;<br><br>seasonal_statistics.write \<br>    .mode(&quot;overwrite&quot;) \<br>    .jdbc(url=jdbcUrl, # PostgreSQL server url<br>          table=&quot;seasonal_statistics&quot;,<br>          mode=&quot;overwrite&quot;,<br>          properties={&quot;driver&quot;: &quot;org.postgresql.Driver&quot;})<br><br># Write on Delta Lake<br><br>from delta.tables import * <br><br>deltaPath = &quot;/user/talha/delta_db/thy_season&quot;<br><br>seasonal_statistics.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(deltaPath)</pre><h4>Import saved data from Apache Hive, PostgreSQL and Delta Lake</h4><pre># Read Table from Apache Hive<br><br>spark.sql(&quot;Select * from thy.season_origin_orc&quot;).limit(5).toPandas()<br><br># Read Table from PostgreSQL<br><br>spark.read.jdbc(url=jdbcUrl,<br>                table=&quot;seasonal_statistics&quot;,<br>                properties={&quot;driver&quot;: &quot;org.postgresql.Driver&quot;}).limit(5).toPandas()<br><br># Read Table from Delta Lake<br><br>season_origin_delta = DeltaTable.forPath(spark, deltaPath)</pre><h4>Stop Apache Spark</h4><pre>spark.stop()</pre><h3>Conclusion</h3><p>Apache Spark is a powerful tool that can handle large-scale data processing and analysis. Hope to these basic commands for data transformations will be helpful and useful. Happy days.</p><p><strong>linkedin_profile:</strong> <a href="https://www.linkedin.com/in/talha-nebi-kumru-929859183/">https://www.linkedin.com/in/talha-nebi-kumru-929859183/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=941b564ddc35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis with Apache HDFS, Hive, Sqoop]]></title>
            <link>https://medium.com/@TalhaNebiKumru/data-analysis-with-apache-hdfs-hive-sqoop-c60bf090d746?source=rss-2f9aee9f265b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c60bf090d746</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[Talha Nebi Kumru]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 12:50:11 GMT</pubDate>
            <atom:updated>2022-11-27T12:50:11.592Z</atom:updated>
            <content:encoded><![CDATA[<p>On the way of being Data Engineer. I like manage data, that is why I want.</p><h3><strong>Introduction</strong></h3><p>Apache Hadoop is the efficient role to big data. In this role, Apache Hadoop can storage data and process data. This article will basically touch on what Apache concepts are. After the definition, Project will made on how to use Apache HDFS, Hive, Sqoop and PostgreSQL concepts together. This project is not more about Data Analyzes. It is for Data Engineering.</p><h3>Hadoop Distributed File Storage (HDFS)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2gv1vu7jyHdJfJ7ranRtw.png" /></figure><p>HDFS was wrote / distributed by Java. HDFS is scalable and transportable file system. Sample Hadoop is that distributed to HDFS and MapReduce. Hadoop uses HDFS for storage data. Hadoop uses MapReduce for processing data. HDFS has got five services. Those are;</p><ul><li>Name Node</li><li>Job Tracker</li><li>Secondary Name Node</li><li>Data Node</li><li>Task Tracker</li></ul><h3>MapReduce</h3><p>MapReduce is programming model about Hadoop that used for getting data storage from HDFS.</p><h4>How it works?</h4><p>There are two function in MapReduce. These are Map and Reduce. They are ordered to each other.</p><ul><li>Map are took input as &lt;key, value&gt; from disk. It processes input. It makes output as &lt;key, value&gt;.</li><li>Reduce are took input as &lt;key, value&gt; without map. It produces output as &lt;key, value&gt;.</li></ul><p>Keys and values are different for usage. All inputs / outputs are storage in HDFS. Map is necessary for filtering / ordering data. Reduce is not necessary. It is optional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Z-V92brp_tnuJQUbfEQbvg.png" /><figcaption>MapReduce Architecture</figcaption></figure><h3>Yarn</h3><p>Yarn is resource management technology and work schedule technology. Yarn is the basic component of Apache Hadoop. Yarn is responsible for allocation system resource to applications and timing targets in nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*zERut-e3ryXjV2vt5svXbg.png" /><figcaption>Yarn Architect</figcaption></figure><h3><strong>Analyze Data</strong></h3><pre>import pandas as pd<br>dataframe = pd.read_csv(&quot;flo100k.csv&quot;, sep=&quot;|&quot;)<br>dataframe.head()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsheetsu.com%2Ftables%2F063e5ca1b4&amp;dntp=1&amp;display_name=Sheetsu&amp;url=https%3A%2F%2Fsheetsu.com%2Ftables%2F063e5ca1b4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=sheetsu" width="700" height="729" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdaf27d3aa2ad164eec2b2e2d3c1bfd4/href">https://medium.com/media/cdaf27d3aa2ad164eec2b2e2d3c1bfd4/href</a></iframe><p>There is too feature when see data. When analyze to features, company;</p><ul><li>What do customers prefer platform type?</li><li>Which channel do customers use on the platform?</li><li>What is the customer’s budget for shopping?</li><li>Which categories do customers shop? finding answers to questions.</li></ul><h4>Features</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsheetsu.com%2Ftables%2Fd21f9ff911&amp;dntp=1&amp;display_name=Sheetsu&amp;url=https%3A%2F%2Fsheetsu.com%2Ftables%2Fd21f9ff911&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=sheetsu" width="700" height="361" frameborder="0" scrolling="no"><a href="https://medium.com/media/11db3da6f2f6d7b9c0e850f08b3b5412/href">https://medium.com/media/11db3da6f2f6d7b9c0e850f08b3b5412/href</a></iframe><h4>Dataframe Schemas for PostgreSQL &amp; Apache Hive</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*Iu4W7A8mmYsivedGZbgqlA.jpeg" /><figcaption>schemas for postgresql and apache hive</figcaption></figure><p>For these schemas, see to features names and their data types. Data types can be change what sql uses. They are for postgresql and apache hive. Seemed the dataframe structure. From now on, continue with postgresql schema.</p><p>For application what we can do;</p><ol><li>Create table for PostgreSQL schema.</li><li>Importing csv file data to table.</li><li>Transfer table PostgreSQL to Apache HDFS with Apache Sqoop.</li><li>Transfer table PostgreSQL to Apache Hive with Apache Sqoop.</li><li>Create another Apache Hive table as .orc formatted.</li><li>Analyze data on Apache Hive.</li></ol><h3>Apache: HDFS, Hive, Sqoop and PostgreSQL Application</h3><p>In this chapter, see how to communicate apache tools and postgresql each other. Firstly, create table for dataframe. After, importing csv file to postgresql. Then transfer all table with datas to apache hdfs and hive with apache sqoop. This transferred table is not good efficiency therefore convert table to .orc formatted table. Finally, few data analyses on apache hive.</p><h4>Creating Part</h4><pre>create table if not exists customers (<br>     master_id varchar(100),<br>     order_channel varchar(100),<br>     platform_type varchar(25),<br>     last_order_channel varchar(25),<br>     first_order_date varchar(75),<br>     last_order_date varchar(75),<br>     last_order_date_online varchar(75),<br>     last_order_date_offline varchar(75),<br>     order_num_total_ever_online float,<br>     order_num_total_ever_offline float,<br>     customer_value_total_ever_offline float,<br>     customer_value_total_ever_online float,<br>     interested_in_categories_12 varchar(75),<br>     online_product_group_amount_top_name_12 varchar(75),<br>     offline_product_group_name_12 varchar(75),<br>     last_order_date_new varchar(75),<br>     store_type varchar(50)<br>);</pre><p>On the above, create table without data. That’s means setting the column name and its types and it is ready for upcoming datas.</p><h4>Importing Part</h4><pre>psql -d traindb -c &quot;\copy customers from &#39;flo100k.csv&#39; DELIMITERS &#39;|&#39; CSV HEADER;&quot;</pre><p>It is console command. PostgreSQL uses copy command for importing csv files to table. In the command firstly call to PostgreSQL and then selecting which database and SQL command.</p><h4>Transportation Part</h4><pre>sqoop import --connect jdbc:postgresql://localhost:5432/traindb --driver org.postgresql.Driver --username train --password-file file:///home/train/.sqoop.password --table customers --split-by master_id --hive-import --create-hive-table --hive-table test1.customer --target-dir /tmp/c</pre><p>On the above command, sqoop connected to postgresql server. After that give driver, username, password, which table in postgresql, which separator column and hive commands. For hive commands, it is new table so that used to create hive table. Finally create temp file for transportation.</p><pre>SELECT * FROM customer limit 5;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsheetsu.com%2Ftables%2F063e5ca1b4&amp;dntp=1&amp;display_name=Sheetsu&amp;url=https%3A%2F%2Fsheetsu.com%2Ftables%2F063e5ca1b4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=sheetsu" width="700" height="729" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdaf27d3aa2ad164eec2b2e2d3c1bfd4/href">https://medium.com/media/cdaf27d3aa2ad164eec2b2e2d3c1bfd4/href</a></iframe><p>As seen, transportation was success.</p><h4>Optimization Part</h4><p>In here, optimize to Apache Hive. That’s mean Apache Hive gives the high performance for data format. The best performance is .orc formatted table. Given command below create table from created table with file format.</p><pre>CREATE TABLE customer_orc stored as orc as SELECT * FROM test1.customer;</pre><p>After the conversion, table storage decreases fast.</p><pre>hdfs dfs -du -h /user/hive/warehouse/test1.db | grep customer</pre><p>Storage = 20.1 M → 4.3 M</p><h4>Data Analyses Part</h4><p>It is basic queries but important. First is given us to total count for the store type, second is given us to total count for the order channel.</p><pre>SELECT store_type , COUNT(*) as total_count FROM customer_orc <br>GROUP BY store_type<br>ORDER BY total_count DESC;</pre><pre>store_type|total_count|<br>----------|-----------|<br>A         |      89225|<br>A,B       |       8498|<br>B         |       1491|<br>A,C       |        702|<br>A,B,C     |         75|<br>B,C       |         10|</pre><pre>SELECT order_channel, COUNT(*) as total_count FROM customer_orc<br>GROUP BY order_channel <br>ORDER BY total_count DESC;</pre><pre>order_channel|total_count|<br>-------------|-----------|<br>Offline      |      70785|<br>Android App  |      11989|<br>Mobile       |       8512|<br>Desktop      |       4751|<br>Ios App      |       3964|</pre><h3>Conclusion</h3><p>Interested in Apache HDFS, Hive, Sqoop. It is all how to use them each other. Project is for being ready for real project. Project is made for who want to be data engineer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c60bf090d746" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>