<?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 Gizem Özdemir on Medium]]></title>
        <description><![CDATA[Stories by Gizem Özdemir on Medium]]></description>
        <link>https://medium.com/@gizemozdemirg9?source=rss-9f38fe6f0c4a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mBm4owucs_Yksuundt8eYQ.jpeg</url>
            <title>Stories by Gizem Özdemir on Medium</title>
            <link>https://medium.com/@gizemozdemirg9?source=rss-9f38fe6f0c4a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:55:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gizemozdemirg9/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[Unsupervised Learning]]></title>
            <link>https://medium.com/@gizemozdemirg9/unsupervised-learning-a168ab896415?source=rss-9f38fe6f0c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a168ab896415</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[principal-component]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Gizem Özdemir]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 12:04:02 GMT</pubDate>
            <atom:updated>2022-08-24T12:04:02.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*J82yf-YU7Ryhh5BdhyOdcw.png" /></figure><p>If there is no dependent variable in the data we are working on, it is called unsupervised learning problems.</p><p>We will examine this subject under three main headings.</p><p>· K-Means</p><p>· Hierarchical Cluster Analysis</p><p>· Principal Component Analysis</p><h3>K-Means</h3><p>Several distance measures were used to divide some data into clusters based on how close they were to one another. Clustering the observation units is the primary goal of K-means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92uDTR_rDceLdzOkMT6MJg.png" /></figure><p><strong>How K-Means Method Works</strong><br>1. The number of clusters is determined.<br>2. Random k centers are selected. (As many centers as the determined number of clusters are selected.)<br>3. Distances to k centers are calculated for each observation.<br>4. Each observation is assigned to the closest center, namely the cluster.<br>5. For the clusters formed after the assignment operations, center calculations are made again.<br>6. This process is repeated for a determined number of iterations and the cluster structure of the observations in which the total within-cluster variation is minimum is selected as the final cluster.</p><p><strong>It is very important to standardize the variables in the processes of using distance and gradient descent-based methods.</strong></p><p><strong>Hierarchical Cluster Analysis</strong></p><p>The objective is to subset the observations based on how similar they are to one another. The method of hierarchical clustering has the advantage that observation units can be examined broadly. It can therefore be relevant to many decision points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_sYHwc0OEPgXQYR_M8CCg.png" /></figure><p>The hierarchical clustering approach is based on grouping the observation units either vertically or horizontally, or more specifically, in a unifying or splitting manner.</p><p><strong>What is the Difference Between K-Means and Hierarchical Clustering Methods?</strong></p><p>In the K-Means Method, we cannot interfere with clustering from the outside. Therefore, we do not have a chance to observe. However, the hierarchical clustering method allows us to make different clustering at different levels, since we can observe.</p><p><strong>Principal Component Analysis</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*yOAIYOPc27cRxJEeRQVTkg.png" /></figure><p>The basic idea is to use fewer variables, components, and dimensions to represent the key aspects of multivariate data. In other words, by taking a tiny information loss risk, we hope to lower the variable size. Data with multiple dimensions are visualized using it. Convenience is offered together with size reduction.</p><p>The data set is divided into elements expressed by linear combinations of independent variables using principal component analysis. As a result, there is no correlation between these components.</p><p>Technically, how does it extract these components in the details?</p><p>The variances of the variable groups and the variables in the data set are expressed by eigenvalues. The most significant groups and primary components are the ones with the biggest variance among the groups. So, eigenvalues are used to categorize variance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a168ab896415" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RANDOM FOREST/Machine Learning/ RANDOM FOREST]]></title>
            <link>https://medium.com/@gizemozdemirg9/random-forest-machine-learning-random-forest-e33894a013b4?source=rss-9f38fe6f0c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e33894a013b4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bagging]]></category>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Gizem Özdemir]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 10:07:56 GMT</pubDate>
            <atom:updated>2022-08-17T10:07:56.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>RANDOM FOREST/<strong>Machine Learning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*B7uGnTh7s7Czkb3EH8UJ4w.jpeg" /></figure><p>The foundation of random forest is the assessment of forecasts generated by several decision trees.</p><p>· Combining the Bagging (Breiman, 1996) and Random Subspace (Ho, 1998) approaches results in it.</p><p>· The bootstrap random sample selection method is used to choose the observations for trees, while the random subspace method is used to choose the variables.</p><p>· The best branching (information gain) variable is selected from among the lesser number of variables randomly chosen from among all the variables at each node of the decision tree.</p><p>· 2/3 of the data set is used in tree building. Excluded data is used to evaluate the performance of trees and to determine variable significance.</p><p>· At each node, a random variable is chosen.</p><p>Random expression is used because the random selection process is made from the observation units and less number of variables are selected from the variables before starting the division process in the trees created.</p><p><strong>Bagging:</strong> This is a homogenous weak learner’s model that combines the individual parallel learnings for the purpose of calculating the model average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QV8rHB0RuBlAAr2mghQDvg.jpeg" /></figure><p><strong>Boosting:</strong> It functions differently from Bagging despite being a homogeneous weak learners’ model. In this strategy, learners acquire knowledge progressively and adaptively to enhance learning algorithm predictions.</p><p><strong>What is the difference between bagging and boosting methods?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*CJcvMcz0bTS3ZiBl9l2f1A.png" /></figure><p>In the bagging method, trees do not have dependencies on each other. In the boosting method, trees are built on the leftovers. Therefore, trees have interdependencies.</p><ul><li>Bagging helps to decrease the model’s variance.</li><li>Boosting helps to decrease the model’s bias.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e33894a013b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommendation Systems : Association Rule Learning]]></title>
            <link>https://medium.com/@gizemozdemirg9/recommendation-systems-association-rule-learning-14ab16ddbae5?source=rss-9f38fe6f0c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ab16ddbae5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Gizem Özdemir]]></dc:creator>
            <pubDate>Tue, 26 Jul 2022 10:17:13 GMT</pubDate>
            <atom:updated>2022-07-26T10:17:13.878Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recommendation Systems : Association Rule Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*FBu_OLUqMjO2FwkW6dFffQ.png" /></figure><p>The main goal is to be able to reduce things that have a lot of content to a certain extent.</p><ul><li><strong>Simple Recommender Systems</strong></li></ul><p>General recommendations made with business knowledge or simple techniques. For example; category top rated, trending, legends etc.<br>Includes simple advice such as the top ten movies in the country this week, showing everyone’s top five movies, the most watched in the past week.</p><ul><li><strong>Association Rule Learning</strong></li></ul><p>Also known as basket analysis. It is an analysis method that can be used by many companies working online or offline. It makes product recommendations according to the rules learned through association analysis. It very often obtains the probabilities of the products bought together and provides some suggestions based on these probabilities.</p><ul><li><strong>Content Based Recommendation</strong></li></ul><p>It is a recommendation system based on the meta information, descriptions and features of the products.</p><ul><li><strong>Collaborative Filtering</strong></li></ul><p>They are the methods that reflect the common opinions of the community on the basis of user or product.It can be realized based on;</p><p>— Item Based Collaborative Filtering</p><p>— User Based Collaborative Filtering</p><p>— Model Based Matrix Factorization</p><h3><strong>Association Rule Learning</strong></h3><p>It is a rule-based machine learning technique used to find patterns (pattern, relationship, structure) in data. One of the best examples of this is the work of American retail giant Walmart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2OqnLYhjnc_Adlhq_qF8Q.jpeg" /></figure><p>As a result of these studies, it was noticed that there is a relationship between diapers and beer. It has been observed that a very large proportion of those who buy diapers in a certain period of time also buy beer. After this observation, the rows were arranged accordingly and the sales rates increased.</p><h4><strong>Apriori Algorithm</strong></h4><p>It is a method of basket analysis and used to identify product relationships. There are three key metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*flNl1aVXzP-rZ2I7qg3JLw.jpeg" /></figure><p>Support(X,Y):The probability of X and Y occurring together.</p><p>Confidence(X,Y):Probability of selling Y when X is bought.</p><p>Lift: How many times increase the probability of buying Y when X is bought?</p><p><strong>How does apriori work?</strong></p><ol><li>Calculate each product’s support.</li><li>We eliminate those below the threshold value we set. We meet the requirements based on the support.</li><li>Make a new list and support. We create potential product pairings.</li><li>A support account is made for new couples.We are examining the frequency of simultaneous occurrences.</li><li>There are three new lists and supports made.</li><li>With each cycle, the final table is built using the remaining data. The values in this table for support, confidence, and lift are also included.</li></ol><h3><strong>Proje: Association Rule Based Recommender System</strong></h3><p><strong>Business problem:</strong> Suggesting products to users at the basket stage.</p><p><strong>Libraries</strong></p><p>In addition to the Core libraries, we need to install and import the mlxtend library.</p><pre>!pip install mlxtend<br>import pandas as pd</pre><p><strong>Data Preprocessing</strong></p><p>The following codes are written in order to show all columns in the data set, to show all columns without going to the bottom line.</p><pre>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.width&#39;, 500)</pre><p>For the output to be on a single line;</p><pre>pd.set_option(&#39;display.expand_frame_repr&#39;, False)</pre><p>To import apriori and association_rules from library mlxtend library;</p><pre>from mlxtend.frequent_patterns import apriori, association_rules</pre><p><strong>Data Reading</strong></p><p><a href="https://archive.ics.uci.edu/ml/datasets/Online+Retail+II"><em>https://archive.ics.uci.edu/ml/datasets/Online+Retail+II</em></a></p><p>Variables in Data; InvoiceNo, Stockcode, Description, Quantity, InvoiceDate, Unitprice, CustomerID, Country</p><pre>df_ = pd.read_excel(&quot;datasets/online_retail_II.xlsx&quot;,<br>                    sheet_name=&quot;Year 2010-2011&quot;)<br>df = df_.copy()</pre><p>Since reading this dataset takes some time, we copy this dataframe instead of waiting.</p><pre>df.head()<br>df.describe().T<br>df.isnull().sum()<br>df.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*m7bhB0Gs-xufUnfPbyGHAg.png" /><figcaption>Output of df.head() code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*A8dAt7q9jeIoM4_r-r7EpA.png" /><figcaption>Output of df.describe().T code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*LwwhatHuNm9a4ySgQdlVhw.png" /><figcaption>Output of df.isnull().sum() code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*i3nlM__3WmtaOYrkF5Qx-A.png" /><figcaption>Output of df.shape code</figcaption></figure><pre>def retail_data_prep(dataframe):<br>    dataframe.dropna(inplace=True)<br>    dataframe = dataframe[~dataframe[&quot;Invoice&quot;].str.contains(&quot;C&quot;, na=False)]<br>    dataframe = dataframe[dataframe[&quot;Quantity&quot;] &gt; 0]<br>    dataframe = dataframe[dataframe[&quot;Price&quot;] &gt; 0]</pre><pre>    return dataframe</pre><p>Null values are removed from the dataset with the dropna function. In order to choose the invoice variables that contain the letter “C,” we first view the invoice variable as a string. We choose the ones that do not contain the letter “C” by placing a ~ sign. As can be seen in the descriptive statistical part, there are negative values, and in order to get rid of these negative values, we apply the process of selecting values greater than zero in the quantity and price variables in our function.</p><p><strong>Data Preprocessing</strong></p><p>Values outside of a variable are referred to as outliers. We’ll set threshold values for the variables, check to see if any of the numbers are outliers, and give the outliers a threshold value. Let’s start by creating our function to determine the threshold values. The first quarter number is often entered as 25%, and the second quarter value is typically entered as 75%. However, we write it this way because we want to notice the outliers in the simplest possible manner, without significantly altering the data structure.</p><pre>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>    return low_limit, up_limit</pre><p>We will do the suppression by converting the lower and upper limits that we want to access in the dataframe to the threshold value we have determined.</p><pre>def replace_with_thresholds(dataframe, variable):<br>    low_limit, up_limit = outlier_thresholds(dataframe, variable)<br>    dataframe.loc[(dataframe[variable] &lt; low_limit), variable] = low_limit<br>    dataframe.loc[(dataframe[variable] &gt; up_limit), variable] = up_limit</pre><pre>def retail_data_prep(dataframe):<br>    dataframe.dropna(inplace=True)<br>    dataframe = dataframe[~dataframe[&quot;Invoice&quot;].str.contains(&quot;C&quot;, na=False)]<br>    dataframe = dataframe[dataframe[&quot;Quantity&quot;] &gt; 0]<br>    dataframe = dataframe[dataframe[&quot;Price&quot;] &gt; 0]<br>    replace_with_thresholds(dataframe, &quot;Quantity&quot;)<br>    replace_with_thresholds(dataframe, &quot;Price&quot;)<br>    return dataframe</pre><pre>df = retail_data_prep(df)</pre><p>The price and quantity variables’ arbitrary values are being removed using the replace with threshold function.</p><p><strong>Preparing ARL Data Structures (Invoice-Product Matrix)</strong></p><p>There are invoices in the rows and products in the columns. After our work, our goal is to obtain an output as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*EHH6-3y52KhFKcoaC23wGA.png" /></figure><p>Now let’s continue our work by simplifying it to one country.</p><pre>df_fr = df[df[&#39;Country&#39;] == &quot;France&quot;]</pre><p>In order to observe how many of which products are purchased according to the invoices;</p><pre>df_fr.groupby([&#39;Invoice&#39;, &#39;Description&#39;]).agg({&quot;Quantity&quot;: &quot;sum&quot;}).head(20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*ErDjYfyGm9cyZdXeBVEO_A.png" /><figcaption>Output of df_fr.groupby([‘Invoice’, ‘Description’]).agg({“Quantity”: “sum”}).head(20) code</figcaption></figure><p>unstack() allows to create a pivot. We make sure that the names in the image above are converted to variable names. With the iloc structure, we select from indexes.</p><pre>df_fr.groupby([&#39;Invoice&#39;, &#39;Description&#39;]).agg({&quot;Quantity&quot;: &quot;sum&quot;}).unstack().iloc[0:5, 0:5]</pre><p>We must do this procedure in a way that writes zeros in place of missing values and ones in full ones.First of all, after the unstack() operation, we fill the empty spaces with zero by saying fillna(0).</p><pre>df_fr.groupby([&#39;Invoice&#39;, &#39;StockCode&#39;]). \<br>    agg({&quot;Quantity&quot;: &quot;sum&quot;}). \<br>    unstack(). \<br>    fillna(0). \<br>    applymap(lambda x: 1 if x &gt; 0 else 0).iloc[0:5, 0:5]</pre><p>The applymap function loops through the entire function. Using this function, we print 1 to values greater than zero with the lambda function.</p><pre>def create_invoice_product_df(dataframe, id=False):<br>    if id:<br>        return dataframe.groupby([&#39;Invoice&#39;, &quot;StockCode&quot;])[&#39;Quantity&#39;].sum().unstack().fillna(0). \<br>            applymap(lambda x: 1 if x &gt; 0 else 0)<br>    else:<br>        return dataframe.groupby([&#39;Invoice&#39;, &#39;Description&#39;])[&#39;Quantity&#39;].sum().unstack().fillna(0). \<br>            applymap(lambda x: 1 if x &gt; 0 else 0)<br><br>fr_inv_pro_df = create_invoice_product_df(df_fr)<br><br>fr_inv_pro_df = create_invoice_product_df(df_fr, id=True)</pre><p>If we want the information to come according to both StockCode and Description, we can use the above function.</p><p>If we want to get the description of the stockcode we want;</p><pre>def check_id(dataframe, stock_code):<br>    product_name = dataframe[dataframe[&quot;StockCode&quot;] == stock_code][[&quot;Description&quot;]].values[0].tolist()<br>    print(product_name)<br><br><br>check_id(df_fr, 10120)</pre><p><strong>Association Rules Analysis</strong></p><p>We imported the apriori() function above. The apriori() function says: give me your dataframe. If you want to use the names of the variables in the used dataset it says do colnames=True and I’ll give you the probability of possible product associations. We don’t want values below 0.01, so we specify it that way. (min_support=0.01)</p><pre>frequent_itemsets = apriori(fr_inv_pro_df,<br>                            min_support=0.01,<br>                            use_colnames=True)</pre><p>To observe the incoming values in decreasing order;</p><pre>frequent_itemsets.sort_values(&quot;support&quot;, ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*wTSsib_iYBSug2vR4We5Wg.png" /><figcaption>Output of frequent_itemsets.sort_values(“support”, ascending=False) code</figcaption></figure><p>Using this data, we will derive an association rule. For this, the association_rules method is used.</p><pre>rules = association_rules(frequent_itemsets,<br>                          metric=&quot;support&quot;,<br>                          min_threshold=0.01)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yA-FZNRPishHDGvOfwEekA.png" /><figcaption>Output of code above</figcaption></figure><p>I would like to give brief information about the leverage and conviction statements seen above. Leverage tends to prioritize values with high support. Therefore, it has a slight bias. The conviction value is the expected frequency of the X value without Y. Or conversely, it is the expected frequency of the Y value without X.</p><p>Some situations can be handled based on support, confidence and lift values. Accordingly, various comments are made.</p><pre>rules[(rules[&quot;support&quot;]&gt;0.05) &amp; (rules[&quot;confidence&quot;]&gt;0.1) &amp; (rules[&quot;lift&quot;]&gt;5)].sort_values(&quot;confidence&quot;, ascending=False)</pre><p><strong>Product Recommendation</strong></p><p>Firstly, we make a recommendation list so that we can recommend multiple products.</p><pre>recommendation_list = []</pre><p>According to the items that appear first in the sorted rules, we employ the enumerate method. The product will visit the products, and the “i” value will visit their indexes. The product values are transformed into a list so that you can browse them. Choose a consequents value based on the iloc[i] index to browse the products and add them to the recommendation list.</p><pre>for i, product in enumerate(sorted_rules[&quot;antecedents&quot;]):<br>    for j in list(product):<br>        if j == product_id:<br>            recommendation_list.append(list(sorted_rules.iloc[i][&quot;consequents&quot;])[0])</pre><pre>recommendation_list[]</pre><p>If we write a function fot these operations;</p><pre>def arl_recommender(rules_df, product_id, rec_count=1):<br>    sorted_rules = rules_df.sort_values(&quot;lift&quot;, ascending=False)<br>    recommendation_list = []<br>    for i, product in enumerate(sorted_rules[&quot;antecedents&quot;]):<br>        for j in list(product):<br>            if j == product_id:<br>                recommendation_list.append(list(sorted_rules.iloc[i][&quot;consequents&quot;])[0])<br><br>    return recommendation_list[0:rec_count]</pre><p>The quantity of product suggestions that we desire to be generated when the product is entered into the rec count.</p><p>References</p><p><a href="https://www.veribilimiokulu.com/oneri-sistemleri-101/">Öneri Sistemleri 101 - Veri Bilimi Okulu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ab16ddbae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Lifetime Value Prediction]]></title>
            <link>https://medium.com/@gizemozdemirg9/customer-lifetime-value-prediction-e0d430b47c1b?source=rss-9f38fe6f0c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0d430b47c1b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cltv]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gizem Özdemir]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 12:26:04 GMT</pubDate>
            <atom:updated>2022-07-20T12:26:32.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-2EeDMt7Qc3Cz5t0VLuug.jpeg" /></figure><p>The amount of money that a company or a customer can bring in over time is shown by a statistic called probabilistic lifetime value prediction with time projection.</p><p><strong>CLTV = (Customer Value / Churn Rate) * Profit Margin</strong></p><p>We will produce an estimation based on the predicted audience behavior by entering an individual’s characteristics into this probabilistic model in order to probabilistically model the overall audience’s purchasing behavior as well as the average earnings per transaction.</p><p><strong>Customer Value = Purchase Frequency * Average Order Value</strong></p><p>We convert this written formula into a probabilistic form as follows.</p><p><strong>CLTV = Conditional Expected Number of Transaction * Conditional Expected Average Profit</strong></p><p>With this newly written formula, we will be able to make predictions using probabilistic distributions.</p><p>Two different models are used for this process: BG/NBD ( Beta Geometric / Negative Binomial Distribution) Model and Gamma Gamma Submodel</p><p><strong>CLTV =BG/NBD Model * Gamma Gamma Submodel</strong></p><p><strong>BG/NBD ( Beta Geometric / Negative Binomial Distribution)</strong></p><p>The BG/NDB Model probabilistically models two processes for the Expected Number of Transactions:</p><p>Transaction Process (Buy) + Dropout Process (Till you die)</p><p>As long as the Transaction Process is active, a poisson distribution is used to determine how many transactions a client will complete in a given amount of time. As long as a client is alive, it will continue to randomly scatter around its transaction rate.</p><p>Transaction rates vary for each customer, each customer has a different buying habit, and the gamma is distributed for the entire audience(r,a). This means that we can make inferences from a population of which we know the distribution of a variable whose distribution we know. If we know the distribution of this audience, conditionally reducing it to the characteristics of an individual, we can estimate how many purchases that individual may make.</p><p>Dropout Process, each customer has a drop out rate with probability p. Drop out rates vary for each client and beta is distributed for the entire audience (a,b).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkxWhRyxcfAvb4wAwMdhIA.png" /></figure><p>Y : Values we will estimate.<br>x : is the number of repeat sales for a customer.<br>tx : recency value : time between each customer’s first purchase and last purchase (in weeks)<br>T : is the time elapsed since the first purchase of customers. That is the age of the customer. (in weekly terms)<br>r and a : They are the parameters of the gamma distribution that models the transaction difference between customers.<br>a and b : are the parameters of the beta modeling the dropout probability.</p><p><strong>Gamma Gamma SubModel</strong></p><p>It is used to estimate how much profit a customer can generate on average per trade. The monetary value of a customer is randomly distributed around the average of the transaction values. The average transaction value may change between users over time, but not for a single user. The average transaction value is gamma distributed among all customers.</p><p><strong>CLTV Forecast with BG-NBD and Gamma Gamma</strong></p><p>Using this theoretical understanding, we will now look at a sample project where we handle these processes using Python.</p><p>An e-commerce company wants to segment its customers and determine marketing strategies according to these segments.You can access this dataset from the link below.</p><p><strong>Libraries</strong></p><p>In addition to the Core libraries, we need to install and import the Lifetime library.</p><pre>!pip install lifetimes<br>import datetime as dt<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from lifetimes import BetaGeoFitter<br>from lifetimes import GammaGammaFitter<br>from lifetimes.plotting import plot_period_transactions<br>from sklearn.preprocessing import MinMaxScaler</pre><p><strong>Output Display Settings</strong></p><p>The following codes are written in order to show all columns in the data set, to show all columns without going to the bottom line, and to show 4 digits after the comma for float numbers.</p><pre>pd.set_option(&quot;display.max_columns&quot;,None)<br>pd.set_option(&quot;display.width&quot;,500)<br>pd.set_option(&quot;display.float_format&quot;,lambda x: &quot;%.4f&quot; % x)</pre><p><strong>Outlier Thresholds and Replace with Thresholds</strong></p><pre>def outlier_tresholds(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>    return low_limit,up_limit</pre><p>A threshold value must be established by the Outlier thresholds function.Outliers are values that are well outside the general distribution of a variable. We want to suppress these outliers, so we first need to set a threshold.</p><pre>def replace_with_tresholds(dataframe,variable):<br>    low_limit,up_limit = outlier_tresholds(dataframe,variable)<br>    dataframe.loc[(dataframe[variable]&lt;low_limit),variable] = low_limit<br>    dataframe.loc[(dataframe[variable]&gt;up_limit),variable] = up_limit</pre><p>If there is a value smaller than the specified lower limit threshold, this value is assigned to the lower limit, while if there is a higher value than the determined upper limit threshold, the upper limit is assigned to this value. This process is called suppression.</p><p><strong>Data Reading</strong></p><p><a href="https://archive.ics.uci.edu/ml/datasets/Online+Retail+II"><em>https://archive.ics.uci.edu/ml/datasets/Online+Retail+II</em></a></p><p>Variables in Data; InvoiceNo, Stockcode, Description, Quantity, InvoiceDate, Unitprice, CustomerID, Country</p><pre>df_=pd.read_excel(&quot;online_retail_II.xlsx&quot;, sheet_name=&quot;Year 2010-2011&quot;)<br>df=df_.copy()</pre><p>In case of a change in the data set, a copy is created because it will take a long time to read the data set again.</p><pre>df.describe().T </pre><figure><img alt="Output of df.describe().T code" src="https://cdn-images-1.medium.com/max/826/1*iL1TfWADrP_ROX2Lx_fSpg.png" /><figcaption>Output of df.describe().T code</figcaption></figure><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*rd0V7OKBgN0ClOCiEROxog.png" /><figcaption>Output of df.head() code</figcaption></figure><p>df.isnull().sum() function is used to observe missing values. Null values are removed from the dataset with the dropna function.</p><pre>df.isnull().sum()<br>df.dropna(inplace=True)<br>df=df[~df[&quot;Invoice&quot;].str.contains(&quot;C&quot;,na=False)]<br>df=df[df[&quot;Quantity&quot;]&gt;0]<br>df=df[df[&quot;Price&quot;]&gt;0]</pre><p>Suppressing outliers</p><pre>replace_with_tresholds(df,&quot;Quantity&quot;)<br>replace_with_tresholds(df,&quot;Price&quot;)</pre><p>Creating a total price</p><pre>df[&quot;totalprice&quot;]=df[&quot;Quantity&quot;]*df[&quot;Price&quot;]</pre><p>Set date for analysis</p><pre>today_date=dt.datetime(2011,12,11)</pre><p><strong>Preparation of Lifetime Data Structure</strong></p><p><strong>recency </strong>= Difference between min and max purchase date for each user (weekly)<br><strong>frequency </strong>= Total repeat purchases<br><strong>T</strong>= Customer’s age(how long before the analysis date the first purchase was made)(weekly)<br><strong>monetary value</strong>: Average earnings per purchase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*_hYpLjK4ntTkjh03-XfApQ.png" /></figure><p>In the aggregation dictionary structure, the first shopping date was subtracted from the customer’s last shopping date for the purpose of calculating Recency for each customer at the first stage and assigned to InvoiceDate. To calculate the age of the customer, today’s date is subtracted from the date the customer made the first purchase. Reached the number of unique invoices with num.nunique(), this gives us the frequency. Totalprice gives the monetary value left by the customer.</p><p>With df.columns.droplevel(0) the first dataframe headers are deleted. Column names are called ‘recency’, ‘T’, ‘Frequency’, ‘Monetary’.</p><pre>cltv_df.columns = cltv_df.columns.droplevel(0)<br>cltv_df.columns = [&quot;recency&quot;,&quot;T&quot;,&quot;frequency&quot;,&quot;monetary&quot;]</pre><p>We need to choose greater than 1 in frequency.</p><pre>cltv_df=cltv_df[(cltv_df[&quot;frequency&quot;]&gt;1)]</pre><p>To calculate the average earnings per transaction;</p><pre>cltv_df[&quot;monetary&quot;] = cltv_df[&quot;monetary&quot;]/cltv_df[&quot;frequency&quot;]</pre><p><em>Recency değerinin haftalık cinsten ifade edilmesi için;</em></p><pre>cltv_df[&quot;recency&quot;]=cltv_df[&quot;recency&quot;]/7</pre><p>To express how many weeks the customer has been our customer;</p><pre>cltv_df[&quot;T&quot;]=cltv_df[&quot;T&quot;]/7</pre><p><strong>Establishment of BG/NBD Model</strong></p><pre>bgf = BetaGeoFitter(penalizer_coef=0.001)<br>bgf.fit(cltv_df[&quot;frequency&quot;],<br>        cltv_df[&quot;recency&quot;],<br>        cltv_df[&quot;T&quot;])</pre><p>There is a model object created. When the frequency and customer age data are provided using the fit method, the model is constructed through the use of this model object. Beta and gamma distributions are applied in this model. The parameters are used here using the highest likelihood approach. When determining the parameters for this model, a penalty coefficient called the penalizer coef will be added to the coefficients.</p><p><strong>Who are the top 10 customers we anticipate spending the most money in a week?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*M3KWEBZOFPBseW6XtfiN0A.png" /></figure><p>The first parameter of the predict function and the conditional_expected_number_of_purchases_up_to_time function, “1” means 1 week. As a result of these two functions, we reach the answer to the question “<strong>Who are the top 10 customers we anticipate spending the most money in a week?</strong>”.</p><p><strong>Who are the 10 customers we expect to buy the most in 1 week?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*X-WQiOSOrZ27fTTOOE7Urw.png" /></figure><p><strong>Who are the 10 customers we expect to buy the most in 1 month?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*_954uszu8HPoHbjbhWDEow.png" /></figure><p><strong>Who are the 10 customers we expect to buy the most in 3 months?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*1LSsCV_XlYIZ5hMDQc9bWw.png" /></figure><p><strong>Evaluation of the Predicted Outcomes</strong></p><pre>plot_period_transactions(bgf)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*i3O5xG50eowj3OmEJMDfGw.png" /></figure><p><strong>Establishment of Gamma-Gamma Model</strong></p><pre>ggf=GammaGammaFitter(penalizer_coef=0.01)<br>ggf.fit(cltv_df[&quot;frequency&quot;],cltv_df[&quot;monetary&quot;])<br><br>ggf.conditional_expected_average_profit(cltv_df[&quot;frequency&quot;],cltv_df[&quot;monetary&quot;]).head()<br><br>ggf.conditional_expected_average_profit(cltv_df[&quot;frequency&quot;],cltv_df[&quot;monetary&quot;]).sort_values(ascending=False).head()<br><br>cltv_df[&quot;expected_average_profit&quot;]=ggf.conditional_expected_average_profit(cltv_df[&quot;frequency&quot;],cltv_df[&quot;monetary&quot;])<br><br>cltv_df.sort_values(&quot;expected_average_profit&quot;,ascending=False)</pre><p><strong>Calculation of CLTV with BG/NBD and Gamma Gamma Model</strong></p><pre>cltv=ggf.customer_lifetime_value(bgf,<br>                                 cltv_df[&quot;frequency&quot;],<br>                                 cltv_df[&quot;recency&quot;],<br>                                 cltv_df[&quot;T&quot;],<br>                                 cltv_df[&quot;monetary&quot;],<br>                                 time=3 ,   <br>                                 freq=&quot;W&quot;, <br>                                 discount_rate=0.01)</pre><pre>cltv.head()</pre><pre>cltv=cltv.reset_index()<br><br>cltv_final=cltv_df.merge(cltv,on=&quot;Customer ID&quot;,how=&quot;left&quot;)<br><br>cltv_final.sort_values(by=&quot;clv&quot;,ascending=False).head(10)</pre><p>how=”left” specifies the merge operation according to cltv_df.</p><p>The BG-NBD theory says that as the recency value of a regular customer increases, the probability of purchasing the customer gets closer.</p><p><strong>Creating the Customer Segment</strong></p><pre>cltv_final[&quot;segment&quot;]=pd.qcut(cltv_final[&quot;clv&quot;],4,labels=[&quot;D&quot;,&quot;C&quot;,&quot;B&quot;,&quot;A&quot;])<br><br>cltv_final.groupby(&quot;segment&quot;).agg({&quot;count&quot;,&quot;mean&quot;,&quot;sum&quot;})</pre><p>With the qcut function, it is divided into 4 equal parts according to the clv value. At the same time, the qcut function sorts from smallest to largest. It is divided into D between 0–25, C between 25–50, B between 50–75, A between 75–100.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0d430b47c1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B Testing: Comparison of Bidding Methods using A/B Test]]></title>
            <link>https://medium.com/@gizemozdemirg9/a-b-testing-comparison-of-bidding-methods-using-a-b-test-2db3c554596c?source=rss-9f38fe6f0c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db3c554596c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gizem Özdemir]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 14:13:26 GMT</pubDate>
            <atom:updated>2022-07-17T14:13:26.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*ZpC49CtflQcUyHHLva4BTg.png" /></figure><p>A/B testing is a technique for user experience research. It involves using statistical hypothesis testing, also referred to as “two-sample hypothesis testing” in statistics. A/B testing compares two variations of a single variant, usually by comparing a subject’s reaction to variant A and variant B and figuring out which is more effective.To conduct A/B testing, hypotheses are established. Along with equality assumptions, these can also include greatness and smallness hypotheses.</p><p>I will cover an application of how A/B testing is handled with python software.</p><p>The application that needs to be solved is really a business issue. The definition of a business problem is as follows. Currently, maximum bidding is a form of bidding that Facebook employs. It instead introduced average bidding, a new type bid. A/B testing will be conducted by Facebook to determine which of these offer types leads to the most conversions. The control and test groups each have a different data collection. The test group received average bidding whereas the control group received maximum bidding.</p><p>The variables used and the meanings they represent are given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*HgRtrcK1eh-0iJdEgkiRZQ.png" /></figure><p>First, let’s import the libraries we will use.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><p>Next, let’s write the comma settings and the maximum variable settings that can be seen in one line.</p><pre>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.max_rows&#39;, 10)<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;%.5f&#39; % x)</pre><p>Loading our dataset and examining the numerical variables will be done using the describe() method.</p><pre>df_control = pd.read_excel(&quot;datasets/ab_testing.xlsx&quot;, sheet_name=&quot;Control Group&quot;)<br>df_test = pd.read_excel(&quot;datasets/ab_testing.xlsx&quot;, sheet_name=&quot;Test Group&quot;)<br>df_control.describe().T<br>df_test.describe().T</pre><p>Now it’s time to define the hypotheses.</p><pre># H0 : M1 = M2 (There is no significant difference between the gains of the control and test groups.)<br># H1 : M1!= M2 (There is a significant difference between the gains of the control and test groups.)</pre><p>Analysis of the purchase averages for the test and control groups will follow.</p><pre>df_control[&quot;Purchase&quot;].mean()<br>df_test[&quot;Purchase&quot;].mean()</pre><p>After that, we perform the test for normal distribution and homogeneity of variance. We apply the Shapiro test for the assumption of normal distribution and the Levene test for the Homogeneity of Variance. When testing the hypotheses, if the assumptions are met, the independent two-sample T test, a parametric test, is used; otherwise, the Mann-Whitney U test, a non-parametric test, is used.</p><p>Results are interpreted according to p-value.</p><p>If p-value ≤ 0.05, H0 is rejected.</p><p>If p-value &gt; 0.05, H0 cannot be rejected.</p><pre>test_stat, pvalue = shapiro(df_control[&quot;Purchase&quot;])<br>print(&#39;Test Stat = %.4f, p-value = %.4f&#39; % (test_stat, pvalue))<br>test_stat, pvalue = shapiro(df_test[&quot;Purchase&quot;])<br>print(&#39;Test Stat = %.4f, p-value = %.4f&#39; % (test_stat, pvalue))The following information shows the code&#39;s output.</pre><p>The following information shows the code’s output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*jCDjtsbb8eeqUCsRfMjfxw.png" /></figure><p>p-value&gt;0.05 for test and control groups so H0 cannot be rejected.</p><pre>test_stat, pvalue = levene(df_control[&quot;Purchase&quot;],<br>                           df_test[&quot;Purchase&quot;])<br>print(&#39;Test Stat = %.4f, p-value = %.4f&#39; % (test_stat, pvalue))</pre><p>The following information shows the code’s output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*WtNSIPVc4I9T9MKhHukIYQ.png" /></figure><p>p-value&gt;0.05 for test and control groups, variances are homogeneous.</p><p>As a result, the independent two-sample t-test (parametric test) is used because the assumptions are provided.</p><pre>test_stat, pvalue = ttest_ind(df_test[&quot;Purchase&quot;],<br>                              df_control[&quot;Purchase&quot;],<br>                              equal_var=True)</pre><pre>print(&#39;Test Stat = %.4f, p-value = %.4f&#39; % (test_stat, pvalue))</pre><p>The following information shows the code’s output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*d6Pi0mHV5l72kEI8YRsupA.png" /></figure><p>Considering the p_value obtained as a result of the test (p-value = 0.3493 H0 cannot be rejected), it can be said that there is no statistically significant difference between the purchasing averages of the control and test groups within the 95% confidence margin.</p><p>The right approach can be chosen taking into account the economy of the business, as there is no meaningful difference between the Maximum Bidding and Average Bidding methods for the purchase variable (the number of things purchased after the ads were clicked).</p><blockquote><strong><em>References</em></strong></blockquote><p><a href="https://bootcamp.veribilimiokulu.com/bootcamp-programlari/veri-bilimci-yetistirme-programi/">https://bootcamp.veribilimiokulu.com/bootcamp-programlari/veri-bilimci-yetistirme-programi</a></p><p><a href="https://courses.miuul.com/">https://courses.miuul.com/</a></p><p><a href="https://en.wikipedia.org/wiki/A/B_testing">https://en.wikipedia.org/wiki/A/B_testing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db3c554596c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>