<?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 iktueren semih on Medium]]></title>
        <description><![CDATA[Stories by iktueren semih on Medium]]></description>
        <link>https://medium.com/@iktuerensemih?source=rss-e82dd6f636da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*okyiaHBpblkRGw3ouUDczg.jpeg</url>
            <title>Stories by iktueren semih on Medium</title>
            <link>https://medium.com/@iktuerensemih?source=rss-e82dd6f636da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:53:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iktuerensemih/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[time series analysis[2]]]></title>
            <link>https://medium.com/@iktuerensemih/time-series-analysis-2-fa2a33ac3200?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa2a33ac3200</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[exponential]]></category>
            <category><![CDATA[forecast-accuracy]]></category>
            <category><![CDATA[seasonal-depression]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 20:34:22 GMT</pubDate>
            <atom:updated>2023-08-07T20:34:22.901Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>interlude</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQy0VLOlb9Zn4JF03X0vrg.png" /></figure><h3>Theil’s U</h3><p>In the previous article, if we continue with the example we provided, when applying a linear model to the T*E value and the quarterly period graph, the R-squared (R2) value becomes as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FN2hL7c71lv0pc-QqpR8cQ.png" /></figure><p>If we apply an exponential model, the R-squared (R2) value becomes as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRF20bRIMPVUQyFkfv5-qg.png" /></figure><p>When creating a polynomial model, we can achieve a higher R-squared (R2) value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-MabrelWwa0d0193ZyJ1Q.png" /></figure><h4><em>Theil’s U</em></h4><p><em>The Theil’s U statistic is a measure of forecast accuracy that compares the accuracy of a forecast to the accuracy of a naïve or simple model, usually the mean or the random walk model.</em></p><pre>import numpy as np<br>def theils_u(y_actual, y_forecast):<br>    n = len(y_actual)<br>    numerator = np.sqrt(np.mean(((y_actual - y_forecast) / y_actual)**2))<br>    denominator = np.sqrt(np.mean(((y_actual - np.roll(y_actual, 1)) / y_actual)**2))<br>    u = numerator / denominator<br>    return u</pre><p><em>U = 0: This indicates that the forecast model’s performance is exactly the same as the benchmark model. In other words, your model is not adding any value beyond the simple benchmark. This is not necessarily a good result, as you want your model to perform better than a basic model.</em></p><p><em>U &lt; 1: A value less than 1 suggests that your forecast model is better than the benchmark model. The smaller the U, the better the forecast model’s performance relative to the benchmark. Values closer to 0 indicate a more accurate model.</em></p><p><em>U &gt; 1: A value greater than 1 indicates that the forecast model is performing worse than the benchmark model. This could mean that your model’s predictions are less accurate than simply using a basic model.</em></p><p><em>It’s important to note that the interpretation of Theil’s U can vary depending on the context and the specific benchmark model you’re comparing against. Generally, you would want to achieve a Theil’s U value less than 1 to demonstrate that your forecast model is providing better predictions than a simple benchmark. However, the ideal value can depend on the specific problem, the dataset, and the level of accuracy required.</em></p><p><em>Ultimately, Theil’s U is just one measure among many to evaluate forecast accuracy. It’s often used in conjunction with other metrics like Mean Absolute Percentage Error (MAPE), Mean Squared Error (MSE), or Root Mean Squared Error (RMSE) to get a comprehensive view of how well your model is performing.</em></p><p>If our model has high variance, we can resort to taking the logarithmic value to mitigate this, and to further flatten the data, we might consider taking the second logarithmic value as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6thqeTkjONTnP5zhTANlwA.png" /><figcaption>Raw Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEixqICreWEKegoEsexR2A.png" /><figcaption>1st Log and 2nd Log</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*G2hTD19a_Q4i_MTIEqIw8Q.png" /><figcaption>Raw Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*wXqv_TVIIsMn00uUIFM5Ig.png" /><figcaption>1st Log Histogram</figcaption></figure><pre>       Date    Income M$<br>0   2003-Q1   402.000000<br>1   2003-Q2   759.000000<br>2   2003-Q3  2360.000000<br>3   2003-Q4   911.666667<br>4   2004-Q1   578.333333<br>..      ...          ...<br>76  2022-Q1  1965.000000<br>77  2022-Q2  3226.333333<br>78  2022-Q3  5228.666667<br>79  2022-Q4  3370.000000<br>80  2023-Q1  2513.000000</pre><pre>import pandas as pd<br>data=pd.read_excel(&quot;C:/.../trl_data.xlsx&quot;)<br>dates=pd.date_range(&quot;2003&quot;,periods=len(data[&quot;Date&quot;]),freq=&quot;Q&quot;)<br>data[&quot;Date&quot;]=dates<br>print(data)</pre><pre>         Date    Income M$<br>0  2003-03-31   402.000000<br>1  2003-06-30   759.000000<br>2  2003-09-30  2360.000000<br>3  2003-12-31   911.666667<br>4  2004-03-31   578.333333<br>..        ...          ...<br>76 2022-03-31  1965.000000<br>77 2022-06-30  3226.333333<br>78 2022-09-30  5228.666667<br>79 2022-12-31  3370.000000<br>80 2023-03-31  2513.000000</pre><pre>data.set_index(&quot;Date&quot;,inplace=True)<br>import matplotlib.pyplot as plt<br>data.plot()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*jjxJfsC9A751_Q48lSYZjg.png" /></figure><pre>from statsmodels.tsa.seasonal import seasonal_decompose as sm<br>decomp=sm(data[&quot;Income M$&quot;],model=&quot;add&quot;,period=4)<br>decomp2nd=sm(data[&quot;Income M$&quot;],model=&quot;mul&quot;,period=4)<br>plt.figure(figsize=(16, 9))<br>decomp2nd.plot()<br>decomp.plot()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*Q0ZDpiewRlacMB14NpNOig.png" /></figure><pre>import plotly.express as px<br>import pandas as pd<br>from statsmodels.tsa.seasonal import seasonal_decompose<br>decomp = seasonal_decompose(data[&quot;Income M$&quot;], model=&quot;add&quot;, period=4)<br>decomp_df = pd.DataFrame({<br>    &quot;Date&quot;: data.index,<br>    &quot;Observed&quot;: decomp.observed,<br>    &quot;Trend&quot;: decomp.trend,<br>    &quot;Seasonal&quot;: decomp.seasonal,<br>    &quot;Residual&quot;: decomp.resid<br>})<br><br>fig = px.line(decomp_df, x=&quot;Date&quot;, y=[&quot;Observed&quot;, &quot;Trend&quot;, &quot;Seasonal&quot;, &quot;Residual&quot;],<br>              title=&quot;Seasonal Decomposition of Income&quot;,<br>              labels={&quot;value&quot;: &quot;Value&quot;, &quot;variable&quot;: &quot;Component&quot;},<br>              line_shape=&quot;linear&quot;)<br><br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*GPbgyIEs4RiWVPla0ykF-A.png" /></figure><pre>import numpy as np<br>print(np.std(decomp.resid))<br>print(np.std(decomp2nd.resid))</pre><pre>221.72067557382204<br>0.12252222554747176</pre><pre>decomp3rd=sm(np.log(data[&quot;Income M$&quot;]),model=&quot;add&quot;,period=4)<br>decomp4th=sm(np.log(data[&quot;Income M$&quot;]),model=&quot;mul&quot;,period=4)<br>print(np.std(decomp.resid))<br>print(np.std(decomp2nd.resid))<br>print(np.std(decomp3rd.resid))<br>print(np.std(decomp4th.resid))</pre><pre>221.72067557382204<br>0.12252222554747176<br>0.1286591712123996<br>0.01823613285598757</pre><p>In the logarithmic version of the multiplicative model, it can be observed that the deviations are significantly reduced, leaving a clear margin.</p><pre>de=sm(data[&quot;Income M$&quot;],model=&quot;mul&quot;,period=4)<br>analyse=pd.concat([de.observed, de.trend, de.seasonal, de.observed/de.seasonal],axis=1)<br>analyse.columns=[&quot;Original Observation&quot;,&quot;Trend&quot;,&quot;Seasonal&quot;,&quot;Seasonal Correction&quot;]<br>print(analyse)</pre><pre>            Original Observation        Trend  Seasonal  Seasonal Correction<br>Date                                                                        <br>2003-03-31            402.000000          NaN  0.535932           750.095064<br>2003-06-30            759.000000          NaN  0.886165           856.499862<br>2003-09-30           2360.000000  1130.208333  1.684562          1400.957805<br>2003-12-31            911.666667  1196.958333  0.893341          1020.513213<br>2004-03-31            578.333333  1273.875000  0.535932          1079.116862<br>...                          ...          ...       ...                  ...<br>2022-03-31           1965.000000  3141.666667  0.535932          3666.509454<br>2022-06-30           3226.333333  3365.916667  0.886165          3640.782682<br>2022-09-30           5228.666667  3516.000000  1.684562          3103.873464<br>2022-12-31           3370.000000          NaN  0.893341          3772.354142<br>2023-03-31           2513.000000          NaN  0.535932          4689.027103<br><br>[81 rows x 4 columns]</pre><pre>import statsmodels.api as sa<br>X=sa.add_constant(index)<br>model=sa.OLS(analyse[&quot;Seasonal Correction&quot;],X)<br>result=model.fit()<br>print(result.summary())</pre><pre>OLS Regression Results                            <br>===============================================================================<br>Dep. Variable:     Seasonal Correction   R-squared:                       0.386<br>Model:                             OLS   Adj. R-squared:                  0.379<br>Method:                  Least Squares   F-statistic:                     49.73<br>Date:                 Mon, 07 Aug 2023   Prob (F-statistic):           5.95e-10<br>Time:                         20:47:21   Log-Likelihood:                -626.72<br>No. Observations:                   81   AIC:                             1257.<br>Df Residuals:                       79   BIC:                             1262.<br>Df Model:                            1                                         <br>Covariance Type:             nonrobust                                         <br>==============================================================================<br>                 coef    std err          t      P&gt;|t|      [0.025      0.975]<br>------------------------------------------------------------------------------<br>const       1251.4810    125.967      9.935      0.000    1000.751    1502.211<br>x1            18.8204      2.669      7.052      0.000      13.508      24.133<br>==============================================================================<br>Omnibus:                        9.893   Durbin-Watson:                   0.516<br>Prob(Omnibus):                  0.007   Jarque-Bera (JB):               19.532<br>Skew:                          -0.317   Prob(JB):                     5.74e-05<br>Kurtosis:                       5.321   Cond. No.                         95.3<br>==============================================================================<br><br>Notes:<br>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.</pre><p><em>The model shows a moderate level of explanatory power (R-squared) with a value of 0.386, suggesting that around 38.6% of the variability in the Seasonal Correction can be attributed to the independent variable. The low p-values for the intercept and coefficient of x1 indicate that both of these variables are statistically significant in explaining the variation in the dependent variable. Additionally, the AIC and BIC values provide insight into model selection, with lower values indicating better fit, so further consideration of model fit and assumptions is recommended. The Jarque-Bera test indicates potential departure from normality in the residuals, suggesting that some aspects of the model might need to be investigated further.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2a33ac3200" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[time series analysis]]></title>
            <link>https://medium.com/@iktuerensemih/time-series-analysis-da4d12f57282?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/da4d12f57282</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[decomposition]]></category>
            <category><![CDATA[moving-average]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 13:47:10 GMT</pubDate>
            <atom:updated>2023-08-05T13:47:10.905Z</atom:updated>
            <content:encoded><![CDATA[<p>prelude</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7RLQK1yLwYLSy_0B0L3qQ.png" /></figure><p>The frequency of data points is the topic we will be focusing on. Our aim is to predict how observations will behave in the future. Financial risk is the most commonly used area for this purpose. It is also utilized for weather, earthquake, and ocean movements. Some other areas of application that come to mind are supply analysis, inventory management, and migration analysis.</p><p>We will follow a path from simple structures to deep learning architectures.</p><p>Is every data point dependent on time? How can we determine if it is not a time series?</p><p>We can divide data into two main categories: quantitative data and qualitative data.</p><p>Cross-sectional data captures a snapshot of a particular point in time.</p><pre>observation  Gender  Age  Income<br>1            Male    35    85K<br>2            Male    19    65K<br>3            Female  27    54K<br>4            Male    39    10K</pre><p>As stated in the previous information, cross-sectional data refers to observation data that appears to be taken at a specific point in time. It represents a snapshot captured at a single moment. For example, data obtained from a survey can be considered cross-sectional data. These data reflect the state of affairs existing at a particular point, but they are not suitable for observing changes over time.</p><pre>Country    GDP<br>1          105<br>2          245<br>3          195<br></pre><p>When we collect data over a period of time instead of a specific point in time, a time series structure is formed..</p><pre>Date  1    2    3<br>2022  10  14    17<br>2023  12  16    14<br>2024  13  14    17</pre><p>Panel data is a combination of the two structures. It involves data that is both cross-sectional and time series in nature. In the example below, each row represents a specific entity observed over time, forming a panel of data.</p><pre>Coutry    Date    GDP<br>1         2022    10<br>1         2023    12<br>1         2024    14<br>2         2022    8<br>2         2023    6<br>2         2024    4<br>3         2022    11<br>3         2023    14<br>3         2024    16</pre><p>The column structure is precisely a time series. The combination of these two structures is referred to as panel data.</p><p>The module datetime in Python is ideal for time measurement. Creating a datetime object can be done using the code. x=dt.datetime(2022,5,13,24,48) will create a datetime object for us. In this example, it will create a datetime object representing May 13, 2022, at 24:48 (which is equivalent to 00:48 of the next day). This object allows us to perform operations and manipulate time-related information. combine, replace are frequently used time management methods. strftime we can change the order of day, month, year and time to suit you. timedelta we can find the difference between hours, days, years, minutes in the desired unit.</p><pre>import datetime as dt<br>import pandas as pd<br>_date=[&quot;2024-07-13&quot;,&quot;2023-06-16&quot;,&quot;2022-09-01&quot;]<br>_data=[100,250,400]<br><br>df=pd.DataFrame({&quot;Date&quot;:_date,&quot;Income&quot;:_data})<br>print(df)<br><br>&quot;&quot;&quot;<br>         Date  Income<br>0  2024-07-13     100<br>1  2023-06-16     250<br>2  2022-09-01     400<br></pre><p>Okay, so why would we analyze time series data and how will we do it? Let’s assume we have knowledge of Python and data analysis to continue the topic</p><p>We know that there is basically a regression structure in machine learning. in the simple regression model<br>Y = β₀ + β₁X + ε<br><em>Y represents the dependent variable. X represents the argument. β₀ represents the intercept, the value at the point where it intersects the Y axis. β₁ represents the slope coefficient, showing the effect of a one-unit increase in the variable X on Y. ε represents the error term, random errors that the model cannot explain.</em><br>In regression analysis, the order is not important.</p><pre>import numpy as np<br>from sklearn.linear_model import LinearRegression<br><br>X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)<br>Y = np.array([2, 4, 6, 8, 10])<br><br>model = LinearRegression()<br>model.fit(X, Y)<br><br>new_X = np.array([6]).reshape(-1, 1)<br>predicted_Y_1 = model.predict(new_X)<br>print(predicted_Y_1)<br><br>X_reordered = np.array([5, 3, 1, 4, 2]).reshape(-1, 1)<br>Y_reordered = np.array([10, 6, 2, 8, 4])<br><br>model_reordered = LinearRegression()<br>model_reordered.fit(X_reordered, Y_reordered)<br><br>predicted_Y_2 = model_reordered.predict(new_X)<br>print(predicted_Y_2)<br><br>&quot;&quot;&quot;<br>[12.]<br>[12.]<br></pre><h3><strong>Time series functions consist of four components.</strong></h3><p><strong>Trend (Tt):<br></strong>Trend represents the long-term movement in a time series. It can be either increasing or decreasing in nature.</p><p><strong>Cyclical Movement (Ct — Conjectural Movement):<br></strong>These are changes that occur over the long term in a time series. They appear more frequently compared to trends.</p><p><strong>Seasonal Movement (St):<br></strong>These are very common patterns that repeat over specific time intervals. For example, if you are an ice cream vendor, you might observe a significant increase and decrease in sales during summer and winter seasons, respectively.</p><p><strong>Irregular Movement (Et):<br></strong>These are entirely random and unpredictable movements in a time series. We cannot determine the direction or magnitude of such irregular movements beforehand.</p><p><em>Moving average at time t, denoted by MA(t), is calculated as the average of a specified number of consecutive data points in a time series, typically centered around the current time point t. Let’s assume we use ’n’ data points for the moving average calculation. The formula for the moving average at time t is:</em></p><p><em>MA(t) = (x(t) + x(t-1) + x(t-2) + … + x(t-n+1)) / n</em></p><p><em>where x(t) is the value of the time series at time</em></p><p><em>Centered Moving Average The centered moving average at time t, denoted by CMA(t), is similar to the regular moving average, but it uses an equal number of data points on both sides of the current time point t, making it centered. If we use ‘2n+1’ data points for the centered moving average calculation, the formula is:</em></p><p><em>CMA(t) = (x(t-n) + x(t-n+1) + … + x(t) + … + x(t+n-1) + x(t+n)) / (2n+1)</em></p><p><em>where x(t) is the value of the time series at time t, and ’n’ represents the number of data points on each side of the current time point t.</em></p><pre>Quarterly Tourism Statistics<br>Year Qtr   Income M$   MA(Green)   CMA(Red)<br>2003 Q1    $402,00   <br>2003 Q2    $759,00   <br>2003 Q3    $2.360,00   $1.108,17   $1.130,21 <br>2003 Q4    $911,67     $1.152,25   $1.196,96 <br>2004 Q1    $578,33     $1.241,67   $1.273,88<br>.<br>.<br>2022 Q1    $1.965,00   $2.999,00   $3.141,67 <br>2022 Q2    $3.226,33   $3.284,33   $3.365,92 <br>2022 Q3    $5.228,67   $3.447,50   $3.516,00 <br>2022 Q4    $3.370,00   $3.584,50  <br>2023 Q1    $2.513,00</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cq-CohHQl9Sd7DA1rZKuxA.png" /><figcaption>MA vs CMA</figcaption></figure><h4><strong>Decomposition models</strong></h4><p><em>Aggregate Model: Ty = Tt + (Ct) + St + Et</em></p><p><em>Multiplicative Model: YT = Tt * (Ct) * St * Et</em></p><p>In a dataset with high variance, movements can occur sharply. In cases where the variance is low, the Aggregate Model is preferred, while in situations with high variance, the Multiplicative Model is preferred.</p><p>Seasonality follows a cyclical pattern within the same time intervals, whereas cyclicality does not progress in the same manner. Peaks and troughs in house prices and interest rates are related to the state of the economy. People’s preferences for buying houses often coincide with school holidays.</p><p>In the case of house prices, both seasonality and cyclicality exist. Depending on the data structure, the formulation may be modified when seasonality or cyclicality is dominant. For example, if seasonality does not provide meaningful data, it can be removed or adjusted accordingly.</p><h4><strong>Aggregate Model</strong></h4><p>We start by taking the average of the four quarters on a dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7663URHcEeoSm3Zlg98fA.png" /><figcaption>An Overview with MA4 and CMA</figcaption></figure><p><em>Ty=Tt+St+Ct+Et<br>St+Et=Yt-Tt</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jOsPmxFq89-LFX_2RV02Q.png" /><figcaption>Substraction of CMA value from Quarter Value</figcaption></figure><p>Although our structure is seasonal, it contains irregularity. We can clearly observe that tourism revenues reach a low point in Q1 and peak in Q3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPZ_v6T3L-DQbtXjPKr1JQ.png" /><figcaption>Naked Seasonal Movement</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71BHGFTsVxsFaCGZ_hh8YQ.png" /><figcaption>Yt-St=Tt+Et</figcaption></figure><p><em>Y = β₀ + β₁X + ε</em></p><p><em>Y’t = T’t+St</em></p><p><em>T’t=β₀ + β₁Xt</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8n8IJMnR1etHfPDKW6HAg.png" /><figcaption>Real values vs predicted ones considering linear regression</figcaption></figure><h4><em>Multiplicative Model</em></h4><p>St*Et=Yt/Et</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVb8LN8bVsmsqtXfEdjWTw.png" /></figure><p>In the Multiplicative Model, we can achieve the desired outcome by dividing instead of subtracting when adding or extracting the same set of data, using equations according to the formula. I won’t perform all the operations separately for each, but the comparison between predicted and actual graphs is as follows</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da4d12f57282" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[probability distribution]]></title>
            <link>https://medium.com/@iktuerensemih/probability-distribution-782018244121?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/782018244121</guid>
            <category><![CDATA[bernoulli]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[game-theory]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 01:13:14 GMT</pubDate>
            <atom:updated>2023-06-27T01:13:14.614Z</atom:updated>
            <content:encoded><![CDATA[<p>DATA ANALYSIS STUDY NOTES[3]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovgj6JClyZPKQaCw6FxPfQ.png" /></figure><p><strong>gaussian distribution </strong>or bell curve, is a probability distribution that is symmetric and bell-shaped. It is characterized by two parameters: the mean (μ) and the standard deviation (σ).</p><p>The mean of a normal distribution represents the average or central value around which the data tends to cluster. The standard deviation indicates the spread or dispersion of the data points around the mean.</p><p><strong>a confidence interval</strong> is a range of values that is used to estimate an unknown population parameter, such as the mean, with a certain level of confidence. The confidence interval for the mean in a normal distribution is typically calculated using the formula:</p><p><em>Confidence Interval = [Mean — (Z * (σ / √n)), Mean + (Z * (σ / √n))]</em></p><p><strong>random variable</strong> is a variable whose value is determined by the outcome of a random event or process. It assigns a numerical value to each possible outcome of the event.</p><p><strong>a discrete random variable</strong> can take on a countable number of distinct values. These values are typically integers or whole numbers. Examples of discrete random variables include the number of heads obtained in a series of coin flips or the number of students in a classroom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZwCML1V57G4nb0tq5-6dw.png" /></figure><pre>import random<br>from collections import Counter<br>import matplotlib.pyplot as plt<br>num_flips = 10<br>flips = [random.choice([&quot;Heads&quot;, &quot;Tails&quot;]) for _ in range(num_flips)]<br>outcome_counts = Counter(flips)<br>print(&quot;Table Content (Discrete Random Variable):&quot;)<br>print(&quot;{:&lt;10s} {:&lt;10s}&quot;.format(&quot;Outcome&quot;, &quot;Count&quot;))<br>for outcome, count in outcome_counts.items():<br>    print(&quot;{:&lt;10s} {:&lt;10d}&quot;.format(outcome, count))<br>outcomes = outcome_counts.keys()<br>counts = outcome_counts.values()<br>plt.bar(outcomes, counts)<br>plt.xlabel(&#39;Outcome&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Discrete Random Variable&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*wB8Np7_QqJqpGghxNqfLQA.png" /></figure><p><strong>a continuous random variable</strong> can take on any value within a specific range or interval. These values are typically real numbers. Examples of continuous random variables include the height of a person, the time it takes to complete a task, or the temperature in a given location.</p><pre>import random<br>import numpy as np<br>import matplotlib.pyplot as plt<br>num_values = 1000<br>values = np.random.normal(loc=0, scale=1, size=num_values)<br>hist, bin_edges = np.histogram(values, bins=10)<br>print(&quot;Table Content (Continuous Random Variable):&quot;)<br>print(&quot;{:&lt;15s} {:&lt;10s}&quot;.format(&quot;Bin Range&quot;, &quot;Count&quot;))<br>for i in range(len(hist)):<br>    bin_range = &quot;{:.2f} - {:.2f}&quot;.format(bin_edges[i], bin_edges[i + 1])<br>    print(&quot;{:&lt;15s} {:&lt;10d}&quot;.format(bin_range, hist[i]))<br>plt.bar(bin_edges[:-1], hist, width=np.diff(bin_edges), align=&#39;edge&#39;)<br>plt.xlabel(&#39;Bin Range&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Continuous Random Variable&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Utfu6IkEWkz9HViaundZOg.png" /></figure><p><strong>expected value</strong> of a random variable represents the average value that one would expect to obtain if the random experiment or process were repeated a large number of times. It is often denoted as E(X), where X represents the random variable.</p><p><em>E(X) = Σ(x * P(X = x))</em></p><p><strong>law of large numbers</strong> is a fundamental concept in probability theory and statistics. It states that as the number of observations or trials increases, the average of the observed values tends to approach the expected value of the random variable.</p><pre>import random<br>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>num_rolls = 1000<br>rolls = []<br>averages = []<br>for i in range(1, num_rolls + 1):<br>    roll = random.randint(1, 6)<br>    rolls.append(roll)<br>    average = np.mean(rolls)<br>    averages.append(average)<br>    if i % 100 == 0:<br>        plt.figure()<br>        sns.lineplot(x=range(i), y=rolls, color=&#39;blue&#39;, label=&#39;Roll&#39;)<br>        sns.lineplot(x=range(i), y=averages, color=&#39;red&#39;, label=&#39;Average&#39;)<br>        plt.xlabel(&#39;Number of Rolls&#39;)<br>        plt.ylabel(&#39;Value&#39;)<br>        plt.title(&#39;Roll Results and Average&#39;)<br>        plt.legend()<br>        plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pl3Ra1ziQjgtbgXc-vn3GA.png" /></figure><p><strong>probability distribution</strong> is a concept used in probability theory and statistics. It refers to a mathematical function that describes the probabilities of the possible outcomes of an event or a random variable.</p><p><strong>PMF </strong>The Probability Mass Function is used for discrete random variables, which take on a countable set of possible values. The PMF gives the probability of each possible outcome occurring. It assigns a probability to each value of the random variable, indicating the likelihood of that value being observed.</p><p>The PMF is denoted as P(X = x), where X represents the random variable and x represents a specific value. The PMF satisfies two conditions: it must be non-negative for all values, and the sum of probabilities over all possible values must equal 1.</p><p>For example, in the case of rolling a fair six-sided die, the PMF would assign a probability of 1/6 to each possible outcome (1, 2, 3, 4, 5, 6).</p><p><strong>PDF</strong> The Probability Density Function is used for continuous random variables, which can take on any value within a certain range. The PDF describes the likelihood of observing different values within that range. Unlike the PMF, which gives the probability at specific values, the PDF gives the probability of the random variable falling within a particular interval.</p><p>The PDF is denoted as f(x), where x represents a specific value or interval. The integral of the PDF over a range represents the probability of the random variable falling within that range.</p><p>For example, the PDF of a standard normal distribution (bell curve) is defined by the formula f(x) = (1 / sqrt(2π)) * exp(-x²/2). The PDF describes the likelihood of observing different values of a normally distributed variable.</p><p><strong>CDF</strong> is a fundamental concept in probability theory and statistics. It describes the probability that a random variable takes on a value less than or equal to a given value.</p><p><strong>bernoulli distribution</strong> is a discrete probability distribution that can only take on two values: 0 or 1. The probability of getting a 1 is denoted by p, and the probability of getting a 0 is denoted by 1 — p.</p><p>Bernoulli distributions are often used to model binary events, such as flipping a coin or winning a game. For example, if we flip a coin, the probability of getting heads is p, and the probability of getting tails is 1 — p.</p><p>The Bernoulli distribution is a special case of the binomial distribution, which is a discrete probability distribution that can take on any number of values between 0 and n. The binomial distribution is often used to model the number of successes in a sequence of n trials, where each trial has a probability of success of p.</p><p>The Bernoulli distribution is a simple but powerful distribution that can be used to model a variety of binary events. It is also a building block for more complex distributions, such as the binomial distribution.</p><p><strong>binomial distribution</strong> is a discrete probability distribution that models the number of successes in a fixed number of independent Bernoulli trials. The probability of success in each trial is denoted by ‘p’, and the number of trials is denoted by ‘n’.</p><p>The probability mass function (PMF) of the binomial distribution is given by the formula:</p><p><em>P(X = k) = C(n, k) * p^k * (1 — p)^(n — k)</em></p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import binom<br>from sklearn.datasets import load_breast_cancer<br>data = load_breast_cancer()<br>target = data.target<br>num_cancer_patients = np.sum(target)<br>p = num_cancer_patients / len(target)<br>n = len(target)<br>k_values = np.arange(0, n+1)<br>pmf = binom.pmf(k_values, n, p)<br>plt.bar(k_values, pmf)<br>plt.xlabel(&quot;Number of Cancer Patients&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.title(&quot;Binomial Distribution: Breast Cancer Patients&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*BBbgf-q3TPTEs66HL01IvQ.png" /></figure><p><strong>poisson distribution</strong> is a discrete probability distribution that describes the probability of a given number of events occurring in a fixed interval of time or space. The Poisson distribution is often used to model events such as the number of phone calls received in a hour, the number of earthquakes in a year, or the number of defects in a batch of products.</p><p><em>P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!}</em></p><p><em>where X is a Poisson random variable, k is the number of events, λ is the mean number of events, and k! is the factorial of k.</em></p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import poisson<br>from sklearn.datasets import load_breast_cancer<br>data = load_breast_cancer()<br>target = data.target<br>avg_cancer_patients = np.mean(target)<br>n = len(target)<br>k_values = np.arange(0, n+1)<br>pmf = poisson.pmf(k_values, avg_cancer_patients)<br>plt.bar(k_values, pmf)<br>plt.xlabel(&quot;Number of Cancer Patients&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.title(&quot;Poisson Distribution: Breast Cancer Patients&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vDkQMV3kaVi2zZ2Rc0Qj-g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=782018244121" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DATA ANALYSIS STUDY NOTES[2]]]></title>
            <link>https://medium.com/@iktuerensemih/data-analysis-study-notes-2-c5279dafa862?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5279dafa862</guid>
            <category><![CDATA[histograms]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[inferential-statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 21:18:59 GMT</pubDate>
            <atom:updated>2023-06-08T21:21:19.964Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inferential statistics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcfONwzdTNbqt2zzQdze1Q.png" /></figure><p>to make valid and reliable inferences about a population based on information obtained from a sample. Since it is usually impractical or impossible to collect data from an entire population, researchers collect a representative sample and use inferential statistics to draw conclusions about the larger population.</p><p><strong>central limit theorem</strong> states that the sum (or average) of a large number of independent and identically distributed random variables, with finite mean and variance, will be approximately normally distributed. This holds true regardless of the shape of the original distribution, as long as the sample size is sufficiently large. The average of repeatedly taken samples from a population converges to the population mean.</p><p>same data different results.</p><pre>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>iris_dataset = sns.load_dataset(&#39;iris&#39;)<br>sepal_lengths = iris_dataset[&#39;sepal_length&#39;].to_numpy()<br>sample_size = 30  <br>num_samples = 1000 <br>random_indices = np.random.randint(low=0, high=len(sepal_lengths), size=(num_samples, sample_size))<br>samples = sepal_lengths[random_indices]<br>sample_means = np.mean(samples, axis=1)<br>plt.hist(sample_means, bins=30, density=True, alpha=0.8)<br>plt.xlabel(&#39;Sample Mean&#39;)<br>plt.ylabel(&#39;Density&#39;)<br>plt.title(&#39;Distribution of Sample Means (Central Limit Theorem)&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*N14fgKsC6Jt-xBA3M7CI3g.png" /></figure><pre>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>iris_dataset = sns.load_dataset(&#39;iris&#39;)<br>sepal_lengths = iris_dataset[&#39;sepal_length&#39;]<br>sample_size = 30  <br>num_samples = 1000 <br>sample_means = np.zeros(num_samples)<br>for i in range(num_samples):<br>    sample = np.random.choice(sepal_lengths, size=sample_size, replace=True)<br>    sample_means[i] = np.mean(sample)<br><br>plt.hist(sample_means, bins=30, density=True, alpha=0.8)<br>plt.xlabel(&#39;Sample Mean&#39;)<br>plt.ylabel(&#39;Density&#39;)<br>plt.title(&#39;Distribution of Sample Means (Central Limit Theorem)&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*N14fgKsC6Jt-xBA3M7CI3g.png" /></figure><p>1st code snippet, random indices are generated using np.random.randint() to select elements from the &quot;sepal_lengths&quot;. This method ensures that each element is selected only once per sample, as replacement is set to False by default. Therefore, the resulting sample means are unique, and the distribution of sample means may be slightly different from the first code snippet.</p><p>2nd code snippet, each sample is generated by randomly choosing elements from the “sepal_lengths” using np.random.choice(). This allows for replacement, meaning the same element can be selected multiple times in the same sample. Consequently, the resulting sample means may have some repeated values.</p><p><strong>standard deviation</strong> The standard deviation is a measure of the spread or dispersion of a dataset. It quantifies the average distance between each data point and the mean of the dataset. In other words, it measures how much individual data points deviate from the mean.</p><p><em>σ = √[Σ((xᵢ — μ)²) / N]</em></p><p><em>σ represents the standard deviation<br>Σ denotes the sum of<br>xᵢ represents each individual data point in the dataset<br>μ represents the mean of the dataset<br>N represents the number of data points in the dataset</em></p><p><strong>standard error</strong>: The standard error, on the other hand, is a measure of the precision or variability of a statistic calculated from a sample. It is specifically used to estimate the uncertainty associated with the sample statistic’s accuracy in estimating a population parameter. The standard error is calculated as the standard deviation of the sample statistic divided by the square root of the sample size.</p><p><em>SE = s / √n</em></p><p><em>SE represents the standard error<br>s represents the standard deviation of the sample statistic<br>n represents the sample size</em></p><pre>import numpy as np<br>import seaborn as sns<br>iris_dataset = sns.load_dataset(&#39;iris&#39;)<br>sepal_lengths = iris_dataset[&#39;sepal_length&#39;].to_numpy()<br>std_dev = np.std(sepal_lengths)<br>sample_size = len(sepal_lengths)<br>std_error = std_dev / np.sqrt(sample_size)<br>print(&quot;Standard Deviation:&quot;, std_dev)<br>print(&quot;Standard Error:&quot;, std_error)</pre><pre>Standard Deviation: 0.8253012917851409<br>Standard Error: 0.06738556829778031</pre><p><em>the standard deviation provides a measure of the variability or spread of the sepal lengths, while the standard error gives an indication of the precision or uncertainty associated with the sample mean as an estimate of the population mean.</em></p><p><strong>z-score</strong> is commonly used in statistical analysis to standardize or normalize data, allowing for comparisons and assessments across different distributions. It helps identify outliers, determine the relative position of data points, and calculate probabilities or percentiles associated with specific values in a distribution</p><p><em>Z = (x — μ) / σ</em></p><p><em>Z is the Z-score<br>x is the data point<br>μ is the mean of the distribution<br>σ is the standard deviation of the distribution</em></p><pre>import numpy as np<br>from sklearn.datasets import fetch_california_housing<br>boston_dataset = load_boston()<br>data = boston_dataset.data<br>feature_names = boston_dataset.feature_names<br>chosen_feature = &#39;RM&#39;<br>feature_index = np.where(feature_names == chosen_feature)[0][0]<br>chosen_feature_data = data[:, feature_index]<br>z_scores = (chosen_feature_data - np.mean(chosen_feature_data)) / np.std(chosen_feature_data)<br>plt.hist(z_scores, bins=20)<br>plt.xlabel(&quot;Z-scores&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.title(&quot;Histogram of Z-scores for AveRooms&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*UhQ9pm3QZailS9_cRrjDtg.png" /></figure><p><em>the histogram of Z-scores allows you to explore the distribution characteristics of the chosen feature and identify any notable patterns or anomalies. It can be a useful tool in exploratory data analysis and understanding the nature of the data.</em></p><p><strong>z table </strong>is based on the standard normal distribution, which is a continuous probability distribution with a mean of 0 and a standard deviation of 1. The mathematical equation for the standard normal distribution is:</p><p><em>f(x) = (1 / √(2π)) * e^(-x² / 2)</em></p><p><em>f(x) is the probability density function (PDF) of the standard normal distribution at a given point x.<br>π is the mathematical constant pi.<br>e is the mathematical constant Euler’s number.</em></p><p><em>z-score is a measure of how many standard deviations an observation or data point is from the mean of the distribution. The formula for calculating the Z-score of a data point x, given the mean (μ) and standard deviation (σ) of the distribution, is:</em></p><p><em>Z = (x — μ) / σ</em></p><p>The Z-table typically lists positive Z-scores, starting from 0.00 and going up to a certain value (e.g., 3.99). The table provides the corresponding cumulative probability for each Z-score.</p><p>To use the Z-table, you locate the Z-score of interest in the table and find the corresponding cumulative probability. This probability represents the area under the curve to the left of that Z-score.</p><p><strong>coherence degree</strong> The Sebesta Degree, also known as the Coherence Degree, is a statistical measure that quantifies the degree of coherence or interdependence between two variables, usually denoted as X and Y. It is based on the concept of covariance and correlation.</p><p><em>SD = (cov(X, Y)) / (std(X) * std(Y))</em></p><p><em>cov(X, Y) represents the covariance between variables X and Y.<br>std(X) represents the standard deviation of variable X.<br>std(Y) represents the standard deviation of variable Y.</em></p><p>The numerator, cov(X, Y), measures the extent to which X and Y vary together. It indicates the linear relationship between the variables, with positive values indicating a positive linear relationship, negative values indicating a negative linear relationship, and zero indicating no linear relationship.</p><p><strong>t-distribution</strong> a probability distribution that is used in statistical inference for small sample sizes when the population standard deviation is unknown. It is a symmetric probability distribution that closely resembles the standard normal distribution (Z-distribution), but with slightly heavier tails.</p><p>The t-distribution is characterized by its degrees of freedom (df), which determine its shape. The degrees of freedom represent the sample size minus one (n-1) in most statistical applications. As the degrees of freedom increase, the t-distribution converges to the standard normal distribution.</p><p><em>f(t) = C * (1 + (t² / df))^(-(df+1)/2)</em></p><ul><li><em>t is the random variable</em></li><li><em>df is the degrees of freedom</em></li><li><em>C is a normalization constant that ensures the total area under the curve is equal to 1</em></li></ul><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import load_iris<br>iris = load_iris()<br>data = iris.data[:, 0]  <br>df = len(data) - 1<br>mean = np.mean(data)<br>std = np.std(data)<br>x = np.linspace(stats.t.ppf(0.01, df, loc=mean, scale=std), stats.t.ppf(0.99, df, loc=mean, scale=std), 100)<br>pdf = stats.t.pdf(x, df, loc=mean, scale=std)<br>plt.hist(data, bins=15, density=True, alpha=0.5, label=&#39;Data&#39;)<br>plt.plot(x, pdf, &#39;r-&#39;, label=&#39;t-distribution&#39;)<br>plt.xlabel(&#39;Sepal Length (cm)&#39;)<br>plt.ylabel(&#39;Probability Density&#39;)<br>plt.title(&#39;T-Distribution with Iris Sepal Length&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*wJ5jx5S3qdY4SNYuMokADg.png" /></figure><p><em>By visually comparing the histogram of the data with the t-distribution curve, we can evaluate the goodness of fit. If the t-distribution closely matches the shape of the data, it suggests that the data follows a t-distribution pattern. However, if there are significant deviations or mismatches, it indicates that the t-distribution may not be an ideal fit for the data.</em></p><p><em>It’s important to note that the interpretation of the results should consider the assumptions and limitations of the t-distribution. The t-distribution assumes that the data is normally distributed and that the samples are independent and identically distributed. Deviations from these assumptions can affect the reliability of the results.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5279dafa862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Descriptive statistics about #Etherium prices]]></title>
            <link>https://medium.com/@iktuerensemih/descriptive-statistics-about-ether-price-da9812c8b360?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/da9812c8b360</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[descriptive-statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[central-tendency]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 22:16:17 GMT</pubDate>
            <atom:updated>2023-06-06T22:23:08.081Z</atom:updated>
            <content:encoded><![CDATA[<h4>data analysis study notes[1]</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAF7oxE_DqNBSL37aq_Jag.png" /></figure><p><strong>observation</strong> is the term given to each value within a data set</p><p><strong>quantitative</strong> refers to data or variables that can be measured or expressed numerically. Examples of quantitative variables include age, height, weight, or numerical ratings.</p><p><strong>qualitative</strong> refers to data or variables that are categorical or descriptive in nature and cannot be easily measured or expressed numerically. Examples of qualitative variables include gender, color, marital status, or opinions.</p><p><strong>continuous</strong> refers to variables or data that can take on any value within a certain range. These variables are typically measured on a scale and can have fractional or decimal values. Examples of continuous variables include time, temperature, or distance.</p><p><strong>discrete</strong> refers to variables or data that can only take on specific, distinct values. These values are often whole numbers or categories. Examples of discrete variables include the number of siblings a person has, the number of cars in a parking lot, or the types of animals in a zoo.</p><p><strong>nominal</strong> Nominal data refers to categorical variables where the values represent different categories or groups. The values are typically labels or names without any inherent order or numerical significance. Examples include gender (male, female), colors (red, blue, green), or types of animals (dog, cat, bird).</p><p><strong>ordinal</strong> Ordinal data also represents categorical variables, but the values have an inherent order or ranking associated with them. While the intervals between values may not be uniform, the order of the values is meaningful. Examples of ordinal data include educational attainment (high school, bachelor’s degree, master’s degree), Likert scale ratings (strongly agree, agree, neutral, disagree, strongly disagree), or survey response options (very satisfied, satisfied, neutral, dissatisfied, very dissatisfied).</p><p><strong>metric</strong> (or Interval/Ratio): Metric data refers to variables that have both a meaningful order and a consistent interval or ratio between values. These variables are numerical in nature and allow for mathematical operations. Examples include age, weight, temperature in Celsius or Fahrenheit, or height. Interval scales have equal intervals between values (e.g., temperature in Celsius), while ratio scales have a meaningful zero point (e.g., weight, height).</p><h3>Descriptive statistics</h3><p>Refers to the branch of statistics that focuses on summarizing, organizing, and describing the main characteristics or features of a dataset. It involves calculating various measures to provide a concise and meaningful overview of the data.</p><p>Common descriptive statistics include measures of central tendency (such as mean, median, and mode), measures of dispersion (such as range, standard deviation, and variance), and measures of distribution shape (such as skewness and kurtosis). Descriptive statistics also encompass graphical representations, such as histograms, box plots, and scatter plots, which help visualize the distribution and patterns in the data.</p><h3>Measures of central tendency</h3><p><strong>mean</strong> The mean, also known as the average, is calculated by summing up all the values in a dataset and dividing the sum by the total number of values. It is a measure of central tendency and provides an overall representation of the data. The mean is sensitive to extreme values and can be affected by outliers.</p><p><em>μ = (x₁ + x₂ + x₃ + … + xₙ) / n</em></p><p><em>x₁, x₂, x₃, …, xₙ are the individual values in the dataset, and n is the total number of values in the dataset.</em></p><p><strong>median</strong> The median is the middle value in a dataset when the values are arranged in ascending or descending order. If there is an even number of values, the median is calculated by taking the average of the two middle values. The median is also a measure of central tendency but is less affected by outliers compared to the mean.</p><p><em>M = (x[(n+1)/2] + x[(n+1)/2 + 1]) / 2</em></p><p><em>first, arrange the values in ascending or descending order. If n is odd, the median (M) is the middle value. If n is even, the median is the average of the two middle values x is the ordered dataset, n is the total number of values, and [(n+1)/2] represents the integer division.</em></p><p><strong>mode</strong> The mode is the value that appears most frequently in a dataset. It represents the most common value or category in the data. Unlike the mean and median, the mode is applicable to both numerical and categorical data.</p><p>For a numerical dataset:</p><p>Count the number of occurrences of each value.<br>Identify the value(s) with the highest frequency. These are the mode(s) of the dataset.<br>For a categorical dataset:</p><p>Count the occurrences of each category.<br>Identify the category or categories with the highest frequency. These are the mode(s) of the dataset.</p><p><strong>histogram</strong> is a graphical representation of the distribution of a dataset. It displays the frequencies or counts of data within specific intervals, called bins or classes, along the horizontal axis. The vertical axis represents the frequency or relative frequency of data falling within each bin.</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br>data = sns.load_dataset(&#39;tips&#39;)<br>total_bill_data = data[&#39;total_bill&#39;]<br>median_value = total_bill_data.median()<br>sns.histplot(total_bill_data, kde=True)<br>plt.xlabel(&#39;Total Bill&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Histogram of Total Bill&#39;)<br>plt.axvline(median_value, color=&#39;r&#39;, linestyle=&#39;--&#39;, label=&#39;Median&#39;)<br>plt.legend()<br>plt.show()<br>print(&quot;Median:&quot;, median_value)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*VqEJqEx8AuHHQmCY59UwAg.png" /></figure><p><strong>quartiles</strong> are values that divide a dataset into four equal parts, with each part representing a quarter or 25% of the data. Quartiles are useful for understanding the spread and distribution of data, particularly in box plots and other visualizations. They provide insights into the central tendency and variability of the dataset.</p><pre>from sklearn.datasets import load_iris<br>import numpy as np<br>iris = load_iris()<br>data = iris.data[:, 0] <br>q1 = np.percentile(data, 25)<br>q2 = np.percentile(data, 50)<br>q3 = np.percentile(data, 75)<br>print(&quot;Q1:&quot;, q1)<br>print(&quot;Q2 (Median):&quot;, q2)<br>print(&quot;Q3:&quot;, q3)</pre><p>Q1: 5.1<br>Q2 (Median): 5.8<br>Q3: 6.4</p><h3>Measures of central dispersion</h3><p><strong>range</strong> The range is the difference between the maximum and minimum values in a dataset, indicating the span of the data.</p><p><em>The range can be calculated using the following formula: Range = Maximum Value — Minimum Value</em></p><p><strong>variance</strong> Variance measures the average squared deviation of each value from the mean. It quantifies the dispersion of data points around the mean.</p><p><em>The variance can be calculated using the following formula: Variance = (Sum of squared deviations from the mean) / (Number of observations)</em></p><p><strong>standard deviation</strong> The standard deviation is the square root of the variance. It represents the average distance between each data point and the mean, providing a measure of the spread of the data.</p><p><em>Standard Deviation (σ) = √(Sum of (x — μ)² / N)</em></p><p><em>x represents each individual data point in the dataset<br>μ (mu) represents the mean (average) of the dataset<br>N represents the total number of data points in the dataset</em></p><p><em>The standard deviation can be calculated as the square root of the variance: Standard Deviation = Square root of Varianc</em></p><pre>import seaborn as sns<br>import numpy as np<br>iris = sns.load_dataset(&#39;iris&#39;)<br>sepal_length_data = iris[&#39;sepal_length&#39;]<br>data_range = np.max(sepal_length_data) - np.min(sepal_length_data)<br>data_variance = np.var(sepal_length_data)<br>data_std_deviation = np.std(sepal_length_data)<br>print(&quot;Range:&quot;, data_range)<br>print(&quot;Variance:&quot;, data_variance)<br>print(&quot;Standard Deviation:&quot;, data_std_deviation)</pre><p>Range: 3.6000000000000005<br>Variance: 0.6811222222222222<br>Standard Deviation: 0.8253012917851409</p><p><strong>variance </strong>is a measure of the spread or dispersion of a dataset. It quantifies the average squared deviation of each value from the mean. A high variance indicates that the data points are more widely spread out from the mean, while a low variance suggests that the data points are closer to the mean and less dispersed.</p><p><em>Variance (σ²) = (Σ(x — μ)²) / N</em></p><p><em>Σ represents the summation symbol<br>x represents each individual data point in the dataset<br>μ (mu) represents the mean (average) of the dataset<br>N represents the total number of data points in the dataset</em></p><p><strong>skewness </strong>is a statistical measure that describes the asymmetry of a probability distribution or dataset. It provides information about the shape and tail of the distribution. In other words, skewness quantifies the extent to which the data deviate from a symmetric bell-shaped distribution.</p><p><em>Skewness = (3 * (Mean — Median)) / Standard Deviation</em></p><pre>import numpy as np<br>import seaborn as sns<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br>np.random.seed(0)<br>sample_size = 1000<br>symmetric_sample = np.random.normal(loc=0, scale=1, size=sample_size)<br>skewness = stats.skew(symmetric_sample)<br>plt.figure(figsize=(8, 6))<br>sns.histplot(symmetric_sample, kde=True)<br>plt.xlabel(&#39;Values&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.titl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*CH90BYj-QgZ2ZvW_tpTnTw.png" /><figcaption>symmetric histogram</figcaption></figure><pre>np.random.seed(0)<br>sample_size = 1000<br>asymmetric_sample = np.random.gamma(shape=2, scale=2, size=sample_size)<br>skewness = stats.skew(asymmetric_sample)<br>plt.figure(figsize=(8, 6))<br>sns.histplot(asymmetric_sample, kde=True)<br>plt.xlabel(&#39;Values&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Histogram of Asymmetric Sample\nSkewness: {:.2f}&#39;.format(skewness))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*3ijiwIzDi0ptjMHYgP4paQ.png" /><figcaption>asymmetric histogram</figcaption></figure><p><strong>kurtosis</strong> is a measure that describes the shape and peakedness of a probability distribution or dataset. It quantifies the degree to which the tails of a distribution deviate from the tails of a normal distribution.</p><p><em>Kurtosis = (Σ(x — μ)⁴ / N) / (σ⁴)</em></p><p><em>Σ represents the summation symbol<br>x represents each individual data point in the dataset<br>μ (mu) represents the mean (average) of the dataset<br>N represents the total number of data points in the dataset<br>σ represents the standard deviation of the dataset</em></p><p>Positive kurtosis: A distribution with positive kurtosis has heavier tails and a more peaked central region compared to a normal distribution. It indicates the presence of outliers or extreme values in the dataset.</p><p>Negative kurtosis: A distribution with negative kurtosis has lighter tails and a flatter central region compared to a normal distribution. It suggests that the dataset has fewer outliers or extreme values.</p><p>Zero kurtosis: A distribution with zero kurtosis is said to have “mesokurtic” behavior. It means the distribution has similar tail behavior as a normal distribution.</p><pre>import seaborn as sns<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br>iris = sns.load_dataset(&#39;iris&#39;)<br>sepal_width_data = iris[&#39;sepal_width&#39;]<br>kurtosis = stats.kurtosis(sepal_width_data)<br>plt.figure(figsize=(8, 6))<br>sns.histplot(sepal_width_data, kde=True)<br>print(&quot;Kurtosis:&quot;, kurtosis)<br>plt.xlabel(&#39;Sepal Width&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Histogram of Sepal Width\nKurtosis: {:.2f}&#39;.format(kurtosis))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*Dx6KCGSHKtaK40gH6caLyA.png" /></figure><h3>Descriptive statistics about Ether price</h3><pre><br>import cryptocompare<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import scipy.stats as stats<br>eth_prices = cryptocompare.get_historical_price_day(&#39;ETH&#39;, currency=&#39;USD&#39;, limit=1000)<br>eth_values = [day[&#39;close&#39;] for day in eth_prices]<br>mean = np.mean(eth_values)<br>median = np.median(eth_values)<br>mode = stats.mode(eth_values)[0][0]<br>variance = np.var(eth_values)<br>std_deviation = np.std(eth_values)<br>skewness = stats.skew(eth_values)<br>kurtosis = stats.kurtosis(eth_values)<br>plt.figure(figsize=(8, 6))<br>sns.histplot(eth_values, kde=True)<br>plt.xlabel(&#39;Ethereum Prices (USD)&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Histogram of Ethereum 1-Year Prices&#39;)<br>print(&quot;Descriptive Statistics:&quot;)<br>print(&quot;Mean:&quot;, mean)<br>print(&quot;Median:&quot;, median)<br>print(&quot;Mode:&quot;, mode)<br>print(&quot;Variance:&quot;, variance)<br>print(&quot;Standard Deviation:&quot;, std_deviation)<br>print(&quot;Skewness:&quot;, skewness)<br>print(&quot;Kurtosis:&quot;, kurtosis)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*F8aduL3QKeyyxChGHguE1w.png" /><figcaption>eth/usd</figcaption></figure><pre>Descriptive Statistics:<br>Mean: 2059.8002997002995<br>Median: 1817.48<br>Mode: 3406.48<br>Variance: 1105519.9798276825<br>Standard Deviation: 1051.4371021738211<br>Skewness: 0.5134348840902521<br>Kurtosis: -0.3848591282003966</pre><p><strong><em>Mean</em></strong><em>: The average price of Ethereum over the year was $2059.80. This provides insight into the overall level of Ethereum prices during the specified period.</em></p><p><strong><em>Median</em></strong><em>: The middle price of Ethereum in the dataset is $1817.48. The median helps us understand the central tendency of the data and indicates that the distribution is not heavily skewed by extreme outliers.</em></p><p><strong><em>Mode</em></strong><em>: The most frequent price in the dataset is $3406.48. This indicates that there were instances when Ethereum traded at this price more frequently than other values.</em></p><p><strong><em>Variance</em></strong><em>: The Ethereum prices exhibit a variance of $1,105,519.98. This reflects the spread or dispersion of the data points around the mean. A higher variance suggests higher volatility or price fluctuations.</em></p><p><strong><em>Standard Deviation</em></strong><em>: The standard deviation of the dataset is $1051.44. It provides a measure of the dispersion of the Ethereum prices from the mean. A larger standard deviation indicates a wider range of price movements.</em></p><p><strong><em>Skewness</em></strong><em>: The skewness value of 0.51 suggests a slight right-skewness in the distribution of Ethereum prices. This means that there may be a longer tail on the right side, indicating the presence of relatively higher prices.</em></p><p><strong><em>Kurtosis</em></strong><em>: The kurtosis value of -0.38 indicates a slightly flatter distribution compared to a normal distribution. This implies that the Ethereum prices have fewer extreme values or outliers compared to a normal distribution.</em></p><h4>Considering these outputs, here are some financial insights:</h4><p><em>Ethereum Price Trend: The average price of Ethereum over the year provides an idea of the general price level. Traders and investors can assess whether the current price is above or below the average to make informed decisions.</em></p><p><em>Price Volatility: The high variance and standard deviation indicate significant price fluctuations in Ethereum. Traders should consider the level of volatility when developing trading strategies and risk management plans.</em></p><p><em>Market Sentiment: Skewness provides an indication of the distribution’s shape. The slight right-skewness suggests that there were instances of relatively higher Ethereum prices, which may indicate positive market sentiment or bullishness.</em></p><p><em>Outlier Analysis: The kurtosis value suggests that the distribution of Ethereum prices has fewer extreme values compared to a normal distribution. Traders should be aware of any outliers or unusual price movements that could impact trading decisions.</em></p><p><em>It’s important to note that these statistics provide a summary of the historical Ethereum price data and should be considered alongside other factors such as market conditions, news events, and fundamental analysis when making financial decisions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da9812c8b360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[deep learning _ study notes [1 not finished]]]></title>
            <link>https://medium.com/@iktuerensemih/deep-learning-study-notes-1-not-finished-98acb818c016?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/98acb818c016</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cost-function]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[calculus]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Wed, 31 May 2023 22:21:09 GMT</pubDate>
            <atom:updated>2023-05-31T22:21:09.974Z</atom:updated>
            <content:encoded><![CDATA[<h3>[logistic regression model, loss function, cost function, vectorization]</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5MZi4NnNTzoj-wPDOncMw.png" /><figcaption>[dall-e]</figcaption></figure><p>Let’s consider the task of creating a model that tells us whether an image is a cat or not, based on a traditional example. Let X be the input data, and y^ represent the predicted value that tells us if X is a cat or not.</p><p>y^ = P(y = 1|X) predicted vaule is y^ which we want it to y=1 according to X varriable. Assume that X is a vector of real numbers, with a size of 64x64 pixels and divided into RGB three color channels. X ∈ R^(nx)</p><p>We assume that we have two parameters: w ∈ R^(nx) and b ∈ R.</p><p>The output y^ = w^TX + b formulation cannot give us the desired result. We want y^ to take a value between 0 and 1, representing the probability of X being a cat.</p><p>If we introduce the logistic regression structure into the sigmoid function: w^TX + b = z</p><p>S(z) = 1 / (1 + e^(-z))</p><p>If the z value is a very large positive number, the result will approach 1.</p><p>If the z value is a very large negative number, the result will approach 0.</p><p>In deep learning, we need X0 parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*MHoPU039IN2EUAzG6mPqxA.png" /><figcaption>the b and w parameters</figcaption></figure><p>y^ = S(w^TX+b), where S(z) = 1/(1+e^-z)</p><p>Loss (error) function L(y^,y) =1/2(y^-y)² but in logistic regression people usually do not use this function this is costing optimization problem, we will get there later.</p><p>the useful version of loss function in this regression is as<br>L(y^,y)= -(ylogy^ + (1-y)log(1-y^))</p><p>if y=1&gt;&gt; result will be -logy^ and we deserve it to as big as possible</p><p>if y=0&gt;&gt; result will be ^log(1-y) we deserve as small as possible</p><p>if we apply it i=1 to m serie we will get the cost function and it is as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*Txo4ZzZ_tIMqJd74BaJMmw.png" /></figure><p>Gradient Descent</p><p>We want to minimize J(w, b) considering the three-dimensional axis, where w and b represent (x,y axis) the height of the value is J(w,b). Our goal is to find the minimum value of J(w, b) since it is a convex function. The initialization method does not matter as it is convex the correct result will be found.</p><p>consider we have x1 and x2, surely we will have w1 and w2 and b value. In logistic regression our aim is reduce the w and b.</p><pre>z=w1x1+w2x2+b &gt;&gt;a=S(z) &gt;&gt; L(a,y) [we use a as varriable isntead of y^]<br>da=dL(a,y)/da<br>d/d(a)(-ylog(a)) = -y * (1/a)<br>d/d(a)((1 - y)log(1 - a))<br>u = 1 - a<br>v = log(u)<br>d/d(a)((1 - y)log(1 - a)) = d(v)/d(u) * d(u)/d(a) = (1 - y) * (1/u) * (-1)<br>d/d(a)((1 - y)log(1 - a)) = (1 - y) * (1/(1 - a)) * (-1) = -(1 - y)/(1 - a)<br>dL(a, y)/da = -y * (1/a) - (1 - y)/(1 - a)<br>dL(a, y)/da = (-y/a) + (1 - y)/(1 - a)<br>(-y/a) + (1 - y)/(1 - a)<br><br><br>dL/da = -y/a + (1 - y)/(1 - a)<br>da/dz = d(σ(z))/dz = σ(z) * (1 - σ(z))<br>dz = dL/da * da/dz<br>= (-y/a + (1 - y)/(1 - a)) * (σ(z) * (1 - σ(z)))<br>= (-y/a + (1 - y)/(1 - a)) * (a * (1 - a))<br>= (-y + a(1 - y))/(a(1 - a))<br>= (a - y)/(a(1 - a))<br>dz = (a - y)/(a(1 - a))<br>L(a, y) = -ylog(a) + (1 - y)log(1 - a)<br>=a-y</pre><p>for i=1 to m example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*WkstNHKm-vwWeg2RxBhTAA.png" /></figure><p>w1=w1-alpha.dw1</p><p>w2=w2-alpha.dw2</p><p>b=b-alpha.db</p><p>for a simple calculation there should be 4 times for loops which will kill the performce of model. preventing this vectorisation is the key.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98acb818c016" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Price Prediction [LSTM]]]></title>
            <link>https://medium.com/@iktuerensemih/ml-price-prediction-lstm-a0420ce9ec64?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0420ce9ec64</guid>
            <category><![CDATA[price-prediction]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Tue, 16 May 2023 09:56:09 GMT</pubDate>
            <atom:updated>2023-05-16T18:12:58.231Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine Learning with Python[33]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*MH9GCwx7UUByw_meKzC6UA.png" /><figcaption>[nightcafe]</figcaption></figure><p>Today, we will conduct a small study on price prediction using LSTM. For this study,</p><ol><li><em>Deep learning is a subset of machine learning that utilizes deep neural networks with multiple layers to automatically learn hierarchical representations of data. It excels in handling large and complex datasets and has achieved remarkable performance in various tasks, such as image and speech recognition.</em></li><li><em>A neural network is a computational model inspired by the structure and function of the biological brain. It consists of interconnected artificial neurons that process and transmit information to perform tasks like pattern recognition, classification, and regression.</em></li><li><em>GPU (Graphics Processing Unit) and TPU (Tensor Processing Unit) are specialized hardware accelerators used to speed up the computation of neural networks by parallelizing operations.</em></li><li><em>RNN (Recurrent Neural Network) is a type of neural network that has feedback connections, allowing information to persist over time and process sequential data.</em></li><li><em>LSTM (Long Short-Term Memory) is a type of recurrent neural network (RNN) architecture that is designed to handle long-term dependencies and solve the vanishing gradient problem.</em></li></ol><pre>import pandas as pd<br>import yfinance as yf<br>from datetime import date, timedelta</pre><p>As stock I chosed BIMAS.IS and I though that there is a possible relationship with stock values of IST with USDTRY prices also I involved it. For your choice you can add CDS, interest rates and further data.</p><pre>today = date.today()<br>end_date = today.strftime(&quot;%Y-%m-%d&quot;)<br>start_date = (today - timedelta(days=5000)).strftime(&quot;%Y-%m-%d&quot;)<br><br>data_xu100 = yf.download(&#39;BIMAS.IS&#39;, start=start_date, end=end_date, progress=False)<br>data_xu100.reset_index(drop=True, inplace=True)<br>data.tail()</pre><pre> Open High     Low           Close       Adj       Close     Volume<br>3524 157.000000 166.199997 156.000000 165.500000 165.500000 10768564<br>3525 165.500000 166.100006 157.600006 158.600006 158.600006 6678691<br>3526 158.399994 174.399994 158.100006 174.399994 174.399994 9767891<br>3527 177.699997 190.199997 174.800003 177.300003 177.300003 10095871<br>3528 159.600006 161.100006 159.600006 159.600006 159.600006 12879876</pre><pre>data_usdtry = yf.download(&#39;USDTRY=X&#39;, start=start_date, end=end_date, progress=False)<br>data_usdtry.reset_index(drop=True, inplace=True)<br><br>data_usdtry = data_usdtry[[&#39;Close&#39;]] <br>data_xu100 = data_xu100[data_xu100.index.isin(data_usdtry.index)]<br>data_usdtry = data_usdtry[data_usdtry.index.isin(data_xu100.index)]</pre><pre>import plotly.graph_objects as go<br>figure = go.Figure(data=[go.Candlestick(x=data.index,<br>                                        open=data[&quot;Open&quot;],<br>                                        high=data[&quot;High&quot;],<br>                                        low=data[&quot;Low&quot;],<br>                                        close=data[&quot;Close&quot;])])<br>figure.update_layout(title=&quot;BIMAS.IS&quot;)<br>figure.update_xaxes(rangeslider_visible=False)<br>figure.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChxJWWBOBNut1Rwr-nrW7w.png" /></figure><pre>from sklearn.model_selection import train_test_split<br>from keras.models import Sequential<br>from keras.layers import Dense, LSTM<br><br>X = pd.concat([data_xu100[[&#39;Open&#39;, &#39;High&#39;, &#39;Low&#39;, &#39;Volume&#39;]], data_usdtry], axis=1).values<br>y = data_xu100[&#39;Close&#39;].values<br>y = y.reshape(-1, 1)<br><br>X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)<br><br>model = Sequential()<br>model.add(LSTM(128, return_sequences=True, input_shape=(X_train.shape[1], 1)))<br>model.add(LSTM(64, return_sequences=False))<br>model.add(Dense(25))<br>model.add(Dense(1))<br>model.compile(optimizer=&quot;adam&quot;, loss=&quot;mean_squared_error&quot;)<br>model.fit(X_train, y_train, batch_size=1, epochs=30)</pre><pre>Model: &quot;sequential_1&quot;<br>_________________________________________________________________<br> Layer (type)                Output Shape              Param #   <br>=================================================================<br> lstm_2 (LSTM)               (None, 3, 128)            66560     <br>                                                                 <br> lstm_3 (LSTM)               (None, 64)                49408     <br>                                                                 <br> dense_2 (Dense)             (None, 25)                1625      <br>                                                                 <br> dense_3 (Dense)             (None, 1)                 26        <br>                                                                 <br>=================================================================<br>Total params: 117,619<br>Trainable params: 117,619<br>Non-trainable params: 0</pre><pre>y_pred = model.predict(X_test)<br>loss = model.evaluate(X_test, y_test)<br>mae = mean_absolute_error(y_test, y_pred)<br>rmse = np.sqrt(mean_squared_error(y_test, y_pred))</pre><pre>Epoch 1/30<br>2824/2824 [==============================] - 8s 2ms/step - loss: 17.2505   <br>Epoch 2/30<br>2824/2824 [==============================] - 6s 2ms/step - loss: 1.4266<br>Epoch 3/30<br>2824/2824 [==============================] - 6s 2ms/step - loss: 1.2565<br>.<br>.<br>.<br>Epoch 29/30<br>2824/2824 [==============================] - 6s 2ms/step - loss: 0.3842<br>Epoch 30/30<br>2824/2824 [==============================] - 6s 2ms/step - loss: 0.3269</pre><pre>Mean Absolute Error (MAE): 21.328086225360842<br>Root Mean Squared Error (RMSE): 35.38952932521558<br>Loss: 1252.4188232421875</pre><p>To make the model working better, we can go further tunning stages</p><p>1.Normalisation</p><pre>from sklearn.preprocessing import StandardScaler<br><br># Normalize the input features<br>scaler = StandardScaler()<br>X_scaled = scaler.fit_transform(X)<br><br># Split the normalized data into train and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)</pre><p>2. Hyperparameter Tuning</p><pre>from sklearn.model_selection import GridSearchCV<br><br><br>param_grid = {<br>    &#39;lstm_units&#39;: [64, 128, 256],<br>    &#39;dropout_rate&#39;: [0.2, 0.3, 0.4],<br>    &#39;learning_rate&#39;: [0.001, 0.01, 0.1]<br>}<br><br><br>def create_model(lstm_units, dropout_rate, learning_rate):<br>    model = Sequential()<br>    model.add(LSTM(lstm_units, return_sequences=True, input_shape=(X_train.shape[1], 1)))<br>    model.add(LSTM(lstm_units, return_sequences=False))<br>    model.add(Dense(25))<br>    model.add(Dense(1))<br>    model.compile(optimizer=Adam(learning_rate=learning_rate), loss=&quot;mean_squared_error&quot;)<br>    return model<br><br><br>grid_search = GridSearchCV(estimator=KerasRegressor(build_fn=create_model),<br>                           param_grid=param_grid,<br>                           scoring=&#39;neg_mean_squared_error&#39;,<br>                           cv=3)<br><br><br>grid_search.fit(X_train, y_train)<br><br><br>best_params = grid_search.best_params_<br>best_model = grid_search.best_estimator_.model<br><br>y_pred = best_model.predict(X_test)<br>loss = best_model.evaluate(X_test, y_test)</pre><p>3. Regularization</p><pre>from keras.layers import Dropout<br><br>model = Sequential()<br>model.add(LSTM(128, return_sequences=True, input_shape=(X_train.shape[1], 1)))<br>model.add(Dropout(0.2))  # Add a dropout layer<br>model.add(LSTM(64, return_sequences=False))<br>model.add(Dense(25))<br>model.add(Dense(1))<br>model.compile(optimizer=&quot;adam&quot;, loss=&quot;mean_squared_error&quot;)</pre><p>Afterall our model is ready</p><pre>import numpy as np<br><br>features = np.array([[4489.58, 4700.01, 4475.45,9767891,20.55]])<br>features = np.reshape(features, (features.shape[0], features.shape[1], 1))<br>predicted_price = model.predict(features)<br><br>print(&quot;Predicted price:&quot;, predicted_price)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0420ce9ec64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML / Recommender Systems [Collaborative, Content, Popularity, Hybrid]]]></title>
            <link>https://medium.com/@iktuerensemih/ml-recommender-systems-collaborative-content-popularity-hybrid-4f211688cf83?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f211688cf83</guid>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[lightfm]]></category>
            <category><![CDATA[content-based-filtering]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Tue, 02 May 2023 04:01:52 GMT</pubDate>
            <atom:updated>2023-05-02T04:01:52.003Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine Learning with Python[32]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUi8GjurXXuVFL5bLuXpbQ.png" /></figure><p>When we browse an e-commerce website and view a product or like a movie or song, we often see ads or similar products/services recommended to us. This is due to association analysis, which can be studied through Netflix’s recommendation system. By analyzing our data, predictions can be made about what we might be interested in. There are four accepted main approaches to this:</p><h4>Collaborative filtering</h4><p>is a system that works on the assumption that similar users have similar preferences. Its disadvantage is that it requires a lot of data.</p><h4>Content-based filtering</h4><p>is a system that generates recommendations based on individuals’ own preferences and choices. For example, if it assumes that you have bought soap, it can recommend similar hygiene products. Its disadvantage is that it becomes difficult to produce accurate results if there is little data in the past.</p><h4>Popularity-based filtering</h4><p>is a system that makes recommendations parallel to the general trend independent of the user’s history or similar users. For example, it may provide recommendations such as masks or disinfectants during the pandemic period.Hybrid filtering is a system that emerges from the collaboration between collaborative filtering and content-based systems. When used together, it minimizes the disadvantages of both methods. Currently, large platforms use hybrid filtering systems that include general trends.</p><h4>Hybrid filtering</h4><p>is a system that emerges from the collaboration between collaborative filtering and content-based systems. When used together, it minimizes the disadvantages of both methods. Currently, large platforms use hybrid filtering systems that include general trends.</p><h3>collaboration filtering</h3><p><a href="https://grouplens.org/datasets/movielens/">dataset</a></p><pre>import pandas as pd<br>movies=pd.read_csv(&quot;C:/Users/.../movies.csv&quot;)<br>ratings=pd.read_csv(&quot;C:/Users/.../ratings.csv&quot;)<br>print(movies)<br>print(ratings)</pre><pre>     movieId                                      title                                       genres<br>0           1                           Toy Story (1995)  Adventure|Animation|Children|Comedy|Fantasy<br>1           2                             Jumanji (1995)                   Adventure|Children|Fantasy<br>2           3                    Grumpier Old Men (1995)                               Comedy|Romance<br>3           4                   Waiting to Exhale (1995)                         Comedy|Drama|Romance<br>4           5         Father of the Bride Part II (1995)                                       Comedy<br><br><br>        userId  movieId  rating   timestamp<br>0            1        1     4.0   964982703<br>1            1        3     4.0   964981247<br>2            1        6     4.0   964982224<br>3            1       47     5.0   964983815<br>4            1       50     5.0   964982931</pre><pre>df=pd.merge(movies,ratings,on=&quot;movieId&quot;)<br>df=df[[&quot;userId&quot;,&quot;title&quot;,&quot;rating&quot;]]<br>print(df)</pre><pre>        userId                                      title  rating<br>0            1                           Toy Story (1995)     4.0<br>1            5                           Toy Story (1995)     4.0<br>2            7                           Toy Story (1995)     4.5<br>3           15                           Toy Story (1995)     2.5<br>4           17                           Toy Story (1995)     4.5<br>...        ...                                        ...     ...<br>100831     184  Black Butler: Book of the Atlantic (2017)     4.0<br>100832     184               No Game No Life: Zero (2017)     3.5<br>100833     184                               Flint (2017)     3.5<br>100834     184        Bungo Stray Dogs: Dead Apple (2018)     3.5<br>100835     331        Andrew Dice Clay: Dice Rules (1991)     4.0</pre><pre>pivot=df.pivot_table(index=&quot;title&quot;,columns=&quot;userId&quot;,values=&quot;rating&quot;,fill_value=0)<br>print(pivot)</pre><pre>userId                                     1    2    3    4    5    6    7    8    9    10   11   12   ...  599  600  601  602  603  604  605  606  607  608  609  610<br>title                                                                                                  ...                                                           <br><br>&#39;71 (2014)                                   0  0.0  0.0    0    0    0  0.0    0    0  0.0    0  0.0  ...  0.0  0.0  0.0    0    0    0  0.0  0.0    0  0.0    0  4.0<br>&#39;Hellboy&#39;: The Seeds of Creation (2004)      0  0.0  0.0    0    0    0  0.0    0    0  0.0    0  0.0  ...  0.0  0.0  0.0    0    0    0  0.0  0.0    0  0.0    0  0.0<br>&#39;Round Midnight (1986)                       0  0.0  0.0    0    0    0  0.0    0    0  0.0    0  0.0  ...  0.0  0.0  0.0    0    0    0  0.0  0.0    0  0.0    0  0.0<br>&#39;Salem&#39;s Lot (2004)                          0  0.0  0.0    0    0    0  0.0    0    0  0.0    0  0.0  ...  0.0  0.0  0.0    0    0    0  0.0  0.0    0  0.0    0  0.0</pre><pre>from sklearn.metrics import pairwise_distances<br>similarity_matrix=pairwise_distances(pivot,metric=&quot;correlation&quot;)<br>print(similarity_matrix)</pre><pre>[[0.         1.00164204 1.0023241  ... 0.67471266 1.00818543 1.00164204]<br> [1.00164204 0.         0.293474   ... 1.00359434 1.00818543 1.00164204]<br> [1.0023241  0.293474   0.         ... 1.00508734 1.01158546 1.0023241 ]<br> ...<br> [0.67471266 1.00359434 1.00508734 ... 0.         1.0179175  1.00359434]<br> [1.00818543 1.00818543 1.01158546 ... 1.0179175  0.         1.00818543]<br> [1.00164204 1.00164204 1.0023241  ... 1.00359434 1.00818543 0.        ]]</pre><p>Consider that we are investigating similar movies to “The Godfather (1972)”</p><pre>similarity_matrix=pairwise_distances(pivot,metric=&quot;correlation&quot;)<br>indexes=list(pivot.index)<br>movie_index=indexes.index(&quot;Godfather, The (1972)&quot;)<br>similar_indexes=(similarity_matrix[movie_index].argsort()[1:11])<br>for i in similar_indexes:<br>    print(indexes[i])</pre><pre>Godfather: Part II, The (1974)<br>Goodfellas (1990)<br>One Flew Over the Cuckoo&#39;s Nest (1975)<br>Reservoir Dogs (1992)<br>Fargo (1996)<br>Apocalypse Now (1979)<br>Scarface (1983)<br>Casablanca (1942)<br>Alien (1979)<br>Taxi Driver (1976)</pre><p>Bigger <a href="https://www.kaggle.com/datasets/turgutguvenc/movies-metadata">dataset</a> to study further</p><pre>import pandas as pd<br>original_data=pd.read_csv(&quot;C:/Users/.../movies_metadata.csv&quot;)<br>data=original_data.copy()<br>df=data[[&quot;id&quot;,&quot;title&quot;,&quot;overview&quot;]]<br>print(df)</pre><pre>           id                        title                                           overview<br>0         862                    Toy Story  Led by Woody, Andy&#39;s toys live happily in his ...<br>1        8844                      Jumanji  When siblings Judy and Peter discover an encha...<br>2       15602             Grumpier Old Men  A family wedding reignites the ancient feud be...<br>3       31357            Waiting to Exhale  Cheated on, mistreated and stepped on, the wom...<br>4       11862  Father of the Bride Part II  Just when George Banks has recovered from his ...<br>...       ...                          ...                                                ...<br>45461  439050                       Subdue        Rising and falling between a man and woman.<br>45462  111109          Century of Birthing  An artist struggles to finish his work while a...<br>45463   67758                     Betrayal  When one of her hits goes wrong, a professiona...<br>45464  227506             Satan Triumphant  In a small town live two brothers, one a minis...<br>45465  461257                     Queerama  50 years after decriminalisation of homosexual...</pre><p>We have very much of text data here we need to check TF-IDF</p><p>Term frequency-inverse document frequency.</p><ul><li><em>Document 1: “The cat in the hat”</em></li><li><em>Document 2: “The dog in the yard”</em></li><li><em>Document 3: “The cat and the dog”</em></li></ul><p><em>And we want to calculate the TF-IDF score for the word “cat” in each document.</em></p><p><em>First, let’s calculate the term frequency (TF) for “cat” in each document:</em></p><ul><li><em>TF for “cat” in Document 1 = 1 (appears once)</em></li><li><em>TF for “cat” in Document 2 = 0 (does not appear)</em></li><li><em>TF for “cat” in Document 3 = 1 (appears once)</em></li></ul><p><em>Next, let’s calculate the inverse document frequency (IDF) for “cat” across all documents:</em></p><ul><li><em>IDF for “cat” = log(3/2) = 0.176</em></li></ul><p><em>(Note: The IDF score is calculated as the logarithm of the total number of documents in the corpus divided by the number of documents containing the word.)</em></p><p><em>Finally, we can calculate the TF-IDF score for “cat” in each document by multiplying the TF and IDF scores:</em></p><ul><li><em>TF-IDF for “cat” in Document 1 = 1 * 0.176 = 0.176</em></li><li><em>TF-IDF for “cat” in Document 2 = 0 * 0.176 = 0</em></li><li><em>TF-IDF for “cat” in Document 3 = 1 * 0.176 = 0.176 [writingmate sample]</em></li></ul><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>tdidf=TfidfVectorizer(stop_words=&quot;english&quot;)<br>df[&quot;overview&quot;]=df[&quot;overview&quot;].fillna(&quot; &quot;)<br>tdidf_matrix=tdidf.fit_transform(df[&quot;overview&quot;])<br>print(tdidf_matrix.shape)<br></pre><pre>(45466, 75827) # this is vector value of text</pre><pre>from sklearn.metrics.pairwise import linear_kernel<br>similarity_matrix=linear_kernel(tdidf_matrix,tdidf_matrix)<br>indexes=pd.Series(df.index,index=df[&quot;title&quot;]).drop_duplicates()<br>movie_index=indexes[&quot;Toy Story&quot;]<br>movie_similar=list(enumerate(similarity_matrix[movie_index]))<br>sort=sorted(movie_similar,key=lambda x: x[1],reverse=True)<br>sort_score=sort[1:11]<br>sort_index=[i[0] for i in sort_score]<br>output=df[&quot;title&quot;].iloc[sort_index]<br>print(output)</pre><pre>15348                                     Toy Story 3<br>2997                                      Toy Story 2<br>10301                          The 40 Year Old Virgin<br>24523                                       Small Fry<br>23843                     Andy Hardy&#39;s Blonde Trouble<br>29202                                      Hot Splash<br>43427                Andy Kaufman Plays Carnegie Hall<br>38476    Superstar: The Life and Times of Andy Warhol<br>42721    Andy Peters: Exclamation Mark Question Point<br>8327                                        The Champ</pre><h3>hybrid filtering</h3><p>Here is a link to a Colab notebook where you can experiment with LightFM: [<a href="https://colab.research.google.com/drive/1R-S6YAi-kORHR9RbFvLjhoZr_EtD4Epo#scrollTo=INbKlrr09e1Y">link</a>].</p><p><em>Suppose we have three users (A, B, and C) and four items (1, 2, 3, and 4). We also have some implicit feedback data in the form of binary ratings:</em></p><pre>1   2   3   4<br>A   1   0   1   0<br>B   0   1   1   0<br>C   0   0   1   1</pre><p><em>We can represent this data as a sparse matrix, where each row corresponds to a user and each column corresponds to an item:</em></p><pre>[[1, 0, 1, 0],<br> [0, 1, 1, 0],<br> [0, 0, 1, 1]]</pre><p><em>We can use this matrix to train a LightFM model. Let’s say we use the WARP loss function and train for just one epoch. During training, the model will learn a set of user embeddings and a set of item embeddings that capture the relationships between users and items.</em></p><p><em>After training, we can use the model to generate recommendations for a user. Let’s say we want to generate recommendations for user A. We can do this by taking the dot product of user A’s embedding vector and each item’s embedding vector, then sorting the results in descending order to get the top recommendations. Here’s what that calculation looks like:</em></p><pre>user A embedding: [0.81, -0.39]<br>item 1 embedding: [0.56, 0.12]<br>item 2 embedding: [-0.01, 0.91]<br>item 3 embedding: [0.35, 0.49]<br>item 4 embedding: [0.35, 0.49]</pre><pre>recommendation scores:<br>item 3: 0.81 * 0.35 + (-0.39) * 0.49 = 0.065<br>item 1: 0.81 * 0.56 + (-0.39) * 0.12 = 0.399<br>item 2: 0.81 * (-0.01) + (-0.39) * 0.91 = -0.352<br>item 4: 0.81 * 0.35 + (-0.39) * 0.49 = 0.065</pre><pre>top recommendations: items 1 and 3</pre><p><em>So the model recommends items 1 and 3 to user A based on their implicit feedback data and the relationships learned during training [writingmate]</em></p><pre>!pip install lightfm<br><br>import pandas as pd<br>import numpy as np<br>from lightfm import LightFM<br>from lightfm.datasets import fetch_movielens<br><br>data=fetch_movielens()<br>data</pre><pre>{&#39;train&#39;: &lt;943x1682 sparse matrix of type &#39;&lt;class &#39;numpy.int32&#39;&gt;&#39;<br>  with 90570 stored elements in COOrdinate format&gt;,<br> &#39;test&#39;: &lt;943x1682 sparse matrix of type &#39;&lt;class &#39;numpy.int32&#39;&gt;&#39;<br>  with 9430 stored elements in COOrdinate format&gt;,<br> &#39;item_features&#39;: &lt;1682x1682 sparse matrix of type &#39;&lt;class &#39;numpy.float32&#39;&gt;&#39;<br>  with 1682 stored elements in Compressed Sparse Row format&gt;,<br> &#39;item_feature_labels&#39;: array([&#39;T&#39;, &#39;G&#39;, &#39;F&#39;, ..., &#39;S&#39;, &#39;Y&#39;, &#39;S&#39;], dtype=&#39;&lt;U1&#39;),<br> &#39;item_labels&#39;: array([&#39;T&#39;, &#39;G&#39;, &#39;F&#39;, ..., &#39;S&#39;, &#39;Y&#39;, &#39;S&#39;], dtype=&#39;&lt;U1&#39;)}</pre><p>In very large datasets, a sparse matrix structure is created to avoid inflating the dataset with values where the number of views or ratings is zero.</p><pre>from lightfm.evaluation import precision_at_k<br>model = LightFM(loss=&quot;warp&quot;)<br>model.fit(data[&quot;train&quot;], item_features=data[&quot;item_features&quot;])<br>performance = precision_at_k(model, data[&quot;test&quot;], k=5).mean()<br>performance<br><br>#output is 0.09989395</pre><pre># some tunning application gpt advised for this dataset it knows the data<br>data = fetch_movielens(min_rating=4.0)<br><br># Create a weighted feature matrix combining both user and item features<br>item_features = data[&quot;item_features&quot;]<br>user_features = data[&quot;user_features&quot;]<br>combined_features = np.vstack((item_features, user_features))<br>weights = np.concatenate([np.ones(len(item_features)), [2.0] * len(user_features)])<br>combined_features = (combined_features * weights[:, np.newaxis]).astype(np.float32)<br><br># Initialize the model<br>model = LightFM(loss=&quot;warp&quot;, no_components=30, learning_rate=0.05, item_alpha=1e-6, user_alpha=1e-6)<br><br># Fit the model with weighted feature matrix<br>model.fit(data[&quot;train&quot;], item_features=combined_features, epochs=20, num_threads=4)<br><br># Evaluate the model<br>precision = precision_at_k(model, data[&quot;test&quot;], item_features=combined_features, k=5, num_threads=4).mean()</pre><pre>def recommend(model,data,user_ids):<br>  count_user,count_item=data[&quot;train&quot;].shape<br><br>  for i in user_ids:<br>    user_view=data[&quot;item_labels&quot;][data[&quot;train&quot;].tocsr()[i].indices]<br>    score=model.predict(i,np.arange(count_item))<br>    best_score=data[&quot;item_labels&quot;][np.argsort(-score)]<br>    print(&quot;User:{}&quot;.format(i))<br>    print(&quot;Most liked movies&quot;)<br><br>    for j in user_view[:3]:<br>      print(&quot;   {}&quot;.format(j))<br><br>    for k in best_score[:3]:<br>      print(&quot;   {}&quot;.format(k))<br><br>recommend(model,data,[1,100,500])</pre><pre>User:1<br>Most liked movies<br>   T<br>   R<br>   P<br>   C<br>   E<br>   F<br>User:100<br>Most liked movies<br>   T<br>   T<br>   R<br>   F<br>   C<br>   T<br>User:500<br>Most liked movies<br>   T<br>   M<br>   R<br>   R<br>   S<br>   F</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f211688cf83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML / Unsupervised Learning / Natural Language Processing NLP]]></title>
            <link>https://medium.com/@iktuerensemih/ml-unsupervised-learning-natural-language-processing-nlp-86f38d3c1b22?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/86f38d3c1b22</guid>
            <category><![CDATA[lemmatization-vs-stemming]]></category>
            <category><![CDATA[nltk]]></category>
            <category><![CDATA[word-cloud]]></category>
            <category><![CDATA[count-vectorizer]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 03:23:49 GMT</pubDate>
            <atom:updated>2023-04-07T12:25:32.143Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Porterstemmer, WordNetLematizer, Wordcloud, PIL, CountVectorizer]</h3><p>Machine Learning with Python [31]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*dwr0vdTqiQ4-NKyBWEGupw.png" /></figure><p>Natural Language Processing (NLP) is a field of artificial intelligence and computational linguistics that focuses on the interactions between computers and humans in natural language. NLP aims to enable computers to understand, interpret, and generate human language.</p><p>As Reminder before begining :</p><p>text=my name is red will be not recognized, text=&quot;my name is red&quot; print(type(text) will be recognized as str. print(text+&quot;hi there&quot;) will be applicable. (len(text)) will give us 13 as output. (text[0]) will print 1st character. (text[0:5:2])</p><p>text=&quot;My Name is RED&quot; , text.capitalize() will sort as My name is red. (text.title()) My Name Is Red, text.upper() MY NAME IS RED text.swapcase() mY nAME iS red, text.replace(&quot;a&quot;,&quot;A&quot;) My NAme is RED, text.replace(&quot;RED&quot;,Blue) My Name is Blue. text.startswith(&quot;M&quot;) True, text.endswith(&quot;D&quot;) True, text.find(&quot;R&quot;) 11, text.rfind(&quot;R&quot;) 11, text.count(&quot;a&quot;) 1, text.isaplha() False while the space between the words are not in alphapet. text.isalnum() False because of the same reason. text.isdigit() is all digit? text.isspace() is all value space? text.islower(), text.isupper() al characters are big or small? text.istitle() false while is starts small letter</p><p>text=&quot;My-Name-is-Red-45&quot; &gt; text.split(&quot;-&quot;) [‘My’, ‘Name’, ‘is’, ‘Red’, ‘45’] , text2nd=text.split(&quot;-&quot;); sep=&quot;---&quot;; print(sep.join(text2nd)) My — -Name — -is — -Red — -45, text.strip(&quot; &quot;); text.rstrip(&quot; &quot;) will close the gaps start or end point. l=[]; [for i in text: l.append(i)]; print(l) will give [‘M’, ‘y’, ‘-’, ’N’, ‘a’, ‘m’, ‘e’, ‘-’, ‘i’, ‘s’, ‘-’, ‘R’, ‘e’, ‘d’, ‘-’, ‘4’, ‘5’]</p><pre>I appeared in Ghazni when Book of Kings poet Firdusi completed the final line of a quatrain with the<br>most intricate of rhymes, besting the court poets of Shah Mahmud, who ridiculed him as being<br>nothing but a peasant. I was there on the quiver of Book of Kings hero Rüstem when he traveled far<br>and wide in pursuit of his missing steed; I became the blood that spewed forth when he cut the<br>notorious ogre in half with his wondrous sword; and I was in the folds of the quilt upon which he<br>made furious love with the beautiful daughter of the king who’d received him as a guest. Verily and<br>truly, I’ve been everywhere and am everywhere. I emerged as Tur traitorously decapitated his<br>brother Iraj; as legendary armies, spectacular as a dream, clashed on the steppes; and as Alexander’s<br>lifeblood shimmered brightly from his handsome nose after he suffered sunstroke. Yes, Shah Behram<br>Gür spent every night of the week with a different beauty beneath domes of varying color from<br>distant lands, listening to the story she recounted, and I was upon the outfit of the striking maiden he<br>visited on a Tuesday, whose picture he’d fallen in love with, just as I appeared from the crown to the<br>caftan of Hüsrev, who’d fallen in love with Shirin’s picture. Verily, I was visible upon the military<br>banners of armies besieging fortresses, upon the tablecloths covering tables set for feasts, upon the<br>velvet caftans of ambassadors kissing the feet of sultans, and wherever the sword, whose legends<br>children loved, was depicted. Yes, handsome almondeyed apprentices applied me with elegant<br>brushes to thick paper from Hindustan and Bukhara; I embellished Ushak carpets, wall<br>ornamentation, the combs of fighting cocks, pomegranates, the fruits of fabled lands, the mouth of<br>Satan, the subtle accent lines within picture borders, the curled embroidery on tents, flowers barely<br>visible to the naked eye made for the artist’s own pleasure, blouses worn by stunning women with<br>outstretched necks watching the street through open shutters, the sour-cherry eyes of bird statues<br>made of sugar, the stockings of shepherds, the dawns described in legends and the corpses and<br>wounds of thousands, nay, tens of thousands of lovers, warriors and shahs. I love engaging in scenes<br>of war where blood blooms like poppies; appearing on the caftan of the most proficient of bards<br>listening to music on a countryside outing as pretty boys and poets partake of wine; I love<br>illuminating the wings of angels, the lips of maidens, the death wounds of corpses and severed heads<br>bespeckled with blood. I hear the question upon your lips: What is it to be a color?<br>Color is the touch of the eye, music to the deaf, a word out of the darkness. Because I’ve listened to<br>souls whispering—like the susurrus of the wind— from book to book and object to object for tens of<br>thousands of years, allow me to say that my touch resembles the touch of angels. Part of me, the<br>serious half, calls out to your vision while the mirthful half soars through the air with your glances.<br>I’m so fortunate to be red! I’m fiery. I’m strong. I know men take notice of me and that I cannot be<br>resisted. I do not conceal myself: For me, delicacy manifests itself neither in weakness nor in<br>subtlety, but through determination and will. So, I draw attention to myself. I’m not afraid of other<br>colors, shadows, crowds or even of loneliness. How wonderful it is to cover a surface that awaits me<br>with my own victorious being! Wherever I’m spread, I see eyes shine, passions increase, eyebrows<br>rise and heartbeats quicken. Behold how wonderful it is to live! Behold how wonderful to see.<br>Behold: Living is seeing. I am everywhere. Life begins with and returns to me. Have faith in what I tell<br>you. Hush and listen to how I developed such a magnificent red tone. A master miniaturist, an expert<br>in paints, furiously pounded the best variety of dried red beetle from the hottest climes of Hindustan<br>into a fine powder using his mortar and pestle. He prepared five drachmas of the red powder, one<br>drachma of soapwort and a half drachma of lotor. He boiled the soapwort in a pot containing three<br>okkas of water. Next, he mixed thoroughly the lotor into the water. He let it boil for as long as it took<br>to drink an excellent cup of coffee. As he enjoyed his coffee, I grew as impatient as a child about to<br>be born. The coffee had cleared the master’s mind and given him the eyes of a jinn. He sprinkled the<br>red powder into the kettle and carefully mixed the concoction with one of the thin, clean sticks<br>reserved for this task. I was ready to become genuine red, but the issue of my consistency was of</pre><p>A page of My Name is Red novel, dataset as a pdf document of above text</p><pre>import pdfplumber<br>import pandas as pd<br>with pdfplumber.open(&quot;C:/Users/.../my_name_is_red.pdf&quot;) as pdf:<br>    page = pdf.pages[0]<br>    text = page.extract_text()<br>print(text)<br>d1=text.split(&quot;.&quot;)<br>d2=[]<br>for i in d1:<br>    d2.append(i.replace(&quot;\n&quot;,&quot;&quot;).strip(&quot; &quot;))<br>print(d2)<br>df=pd.DataFrame(d2,columns=[&quot;Sentences&quot;])<br>print(df)</pre><pre>0   I appeared in Ghazni when Book of Kings poet F...<br>1   I was there on the quiver of Book of Kings her...<br>2   Verily andtruly, I’ve been everywhere and am e...<br>3   I emerged as Tur traitorously decapitated hisb...<br>4   Yes, Shah BehramGür spent every night of the w...<br>5   Verily, I was visible upon the militarybanners...<br>6   Yes, handsome almondeyed apprentices applied m...<br>7   I love engaging in scenesof war where blood bl...<br>8   I hear the question upon your lips: What is it...<br>9   Because I’ve listened tosouls whispering—like ...<br>10  Part of me, theserious half, calls out to your...<br>...</pre><p>as an example spam Sms dataset. we need to get rid of punctuation marks.</p><p><em>Stop words are commonly used words in a language that are usually filtered out from text data because they are considered to be uninformative and do not contribute much to the meaning of the text. Examples of stop words in English include “the”, “a”, “an”, “in”, “of”, “to”, “and”, “that”, “this”, “but”, “is”, “are”, “was”, “were”, etc.</em>[ChatGPT]</p><p>We need to perform the task of separating sentences into individual words, identifying stop words and removing them, and then rejoining the remaining words into sentences</p><pre>import pandas as pd<br>import nltk<br>nltk.download(&quot;stopwords&quot;)<br>from nltk.corpus import stopwords</pre><pre>original_data=pd.read_csv(&quot;C:/Users/Şebnem/Desktop/tutorials/spam.csv&quot;,encoding=&quot;Windows-1252&quot;)<br>data=original_data.copy()<br>data=data.drop(columns=[&quot;Unnamed: 2&quot;,&quot;Unnamed: 3&quot;,&quot;Unnamed: 4&quot;],axis=1)<br>data=data.rename(columns={&quot;v1&quot;:&quot;Tag&quot;,&quot;v2&quot;:&quot;SMS&quot;})<br>data2nd=data[&quot;SMS&quot;].str.replace(&quot;[^\w\s]&quot;,&quot;&quot;)<br># data3rd=re.sub(&#39;[^a-zA-Z]&#39;,&quot; &quot;,data[&quot;SMS&quot;][0]) # re alternative for loop needed<br>data4th=data2nd.str.replace[(&quot;\d&quot;,&quot;&quot;)] # wil remove digits<br>stop_words=stopwords.words(&quot;english&quot;)<br>stop_words.extend(&quot; n &quot;) # i assumed &quot; n &quot; used instead of &quot;and&quot; i added to list<br>data5th=data4th.apply(lambda x:&quot; &quot;.join(x for x in x.split() if x not in stop_words))</pre><pre>print(data5th.iloc[0])<br>print(data4th.iloc[0])<br>print(origina_data[&quot;v2&quot;][0])</pre><pre>go jurong point crazy available bugis great world la e buffet cine got amore wat<br>go until jurong point crazy available only in bugis n great world la e buffet cine there got amore wat<br>Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat.</pre><p>Alternative with re</p><pre>import re<br>from nltk.stem.porter import PorterStemmer<br>ps=PorterStemmer()</pre><pre>cleared_data=[]<br>for i in range(len(data)):<br>    sort=re.sub(&#39;[^a-zA-Z]&#39;,&#39; &#39;,data[&quot;SMS&quot;][i])<br>    sort=sort.lower()<br>    sort=sort.split()<br>    sort=[ps.stem(word) for word in sort if not word in set(stopwords.words(&quot;english&quot;))]<br>    sort=&#39; &#39;.join(sort)<br>    cleared_data.append(sort)</pre><pre>df=pd.DataFrame(list(zip(data[&quot;SMS&quot;,cleared_data])),columns=[&quot;Original Data&quot;,&quot;Cleared Data&quot;])<br>print(df)</pre><p><em>Stemmers remove suffixes to reduce words to their stems, but this can result in incorrect or non-existent words. Lemmatization considers context and part of speech to determine the base form of a word, making it a more accurate approach than stemmers. While stemmers can be useful in certain applications, lemmatization is generally preferred for better accuracy and relevance in language processing tasks.</em></p><pre>Original Data    Go until jurong point, crazy.. Available only ...<br>Cleared Data     go jurong point <strong>crazi</strong> avail bugi n great world...</pre><pre>nltk.download(&#39;wordnet&#39;)<br>from nltk.stem import WordNetLemmatizer<br>lema=WordNetLemmatizer()</pre><pre>    sort=[lema.lemmatize(word) for word in sort if not word in set(stopwords.words(&quot;english&quot;))]</pre><pre>Original Data    Go until jurong point, crazy.. Available only ...<br>Cleared Data     go jurong point crazy available bugis n great ...</pre><p>Frequency</p><pre>frequency=(df[&quot;Cleared Data&quot;]).apply(lambda x:pd.value_counts(x.split(&quot; &quot;))).sum(axis=0).reset_index()<br>frequency.columns=[&quot;Words&quot;,&quot;Frequency&quot;]<br>print(frequency)<br>print(frequency.info())<br>print(frequency.nunique())</pre><pre>Words  Frequency<br>0            go      313.0<br>1        jurong        1.0<br>2         point       33.0<br>3         crazy       15.0<br>4     available       18.0<br>...         ...        ...<br>7039       heap        1.0<br>7040      lowes        1.0<br>7041   salesman        1.0<br>7042       pity        1.0<br>7043   bitching        1.0</pre><pre> 0   Words      7044 non-null   object<br> 1   Frequency  7044 non-null   float64</pre><pre>Words        7044<br>Frequency     150</pre><pre>import matplotlib.pyplot as plt</pre><pre>filter=frequency[frequency[&quot;Frequency&quot;]&gt;250]<br>filter.plot.bar(x=&quot;Words&quot;,y=&quot;Frequency&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VHmtOtOuQfmOScGt_83fDg.png" /></figure><pre>from wordcloud import WordCloud<br>plt.figure(figsize=(5,5))<br>cloud=WordCloud().generate(df[&quot;Cleared Data&quot;][0])<br>plt.imshow(cloud)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ks6K5eC-M52d_eMW9Xc4Cw.png" /></figure><p>Wordcloud(background_color=&quot;White&quot;,max_words=7,colormap=&quot;rainbow&quot;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*dc_otF8byvNIm8U4wQLqZA.png" /></figure><pre>import numpy as np<br>from PIL import Image<br>picture=np.array(Image.open(&quot;C:/Users/Şebnem/Desktop/tutorials/Abe.jpg&quot;))<br>cloud=WordCloud(background_color=&quot;White&quot;,mask=picture,colormap=&quot;rainbow&quot;).generate(df[&quot;Cleared Data&quot;][0])<br>plt.imshow(cloud)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*dwr0vdTqiQ4-NKyBWEGupw.png" /></figure><pre>words=dict(frequency.values)<br>cloud=WordCloud(background_color=&quot;White&quot;,mask=picture,colormap=&quot;rainbow&quot;,max_words=250).generate_from_frequencies(words)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*6x69yGOT82RILBKY_jNQZw.png" /></figure><pre>Text Sample               Vector Representation</pre><pre>&quot;hi there my name is red&quot; [1 1 1 1 1 0 0 0 0]<br>&quot;hey you my name was red&quot; [0 0 1 1 0 1 0 0 0]<br>&quot;ola my name will be red&quot; [0 0 1 1 0 0 1 1 1]</pre><pre>from sklearn.feature_extraction.text import CountVectorizer<br>cv=CountVectorizer(max_features=500)<br>matrix=cv.fit_transform(cleared_data).toarray()<br>matrix_df=pd.DataFrame(matrix,columns=cv.get_feature_names_out())<br>print(matrix_df)</pre><pre>able  abt  account  actually  address  aft  afternoon  age  ah  aight  already  alright  ...  xmas  xx  xxx  ya  yeah  year  yes  yesterday  yet  yo  yr  yup<br>0        0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>1        0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>2        0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>3        0    0        0         0        0    0          0    0   0      0        1        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>4        0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>...    ...  ...      ...       ...      ...  ...        ...  ...  ..    ...      ...      ...  ...   ...  ..  ...  ..   ...   ...  ...        ...  ...  ..  ..  ...  <br>5567     0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>5568     0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>5569     0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>5570     0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  <br>5571     0    0        0         0        0    0          0    0   0      0        0        0  ...     0   0    0   0     0     0    0          0    0   0   0    0  </pre><pre>[5572 rows x 500 columns]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86f38d3c1b22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML / Unsupervised Learning / Association Rule Learning [Apriori , Eclat]]]></title>
            <link>https://medium.com/@iktuerensemih/ml-unsupervised-learning-association-rule-learning-apriori-eclat-c46afe82e9ed?source=rss-e82dd6f636da------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46afe82e9ed</guid>
            <category><![CDATA[eclat]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[apriori]]></category>
            <category><![CDATA[mlxtend]]></category>
            <category><![CDATA[association-rule]]></category>
            <dc:creator><![CDATA[iktueren semih]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 21:51:10 GMT</pubDate>
            <atom:updated>2023-04-07T12:26:17.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML / Unsupervised Learning / Association Rule Learning [Apriori , Eclat]</h3><p>Machine Learning with Python[30]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oV2e6nLRnywp5W_K1r9Vlg.png" /><figcaption>dall-e[ML / Unsupervised Learning / Association Rule Learning [Apriori , Eclat] colorful dark enjoyable]</figcaption></figure><p>Association Rule Learning is a structure that tries to learn the relationships between variables and is also used in data mining algorithms.</p><p>For example, if we buy a soda from the market and also buy chocolate or chips, and we assume that there are others similar to us. Then, this behavior pattern will be effective in shelf layout and campaigns.</p><p>Basket Analysis is an analysis carried out to find the relationship between the sales of different products and to develop marketing strategies accordingly.</p><p>Recommendation algorithms have emerged from this structure.</p><pre>Customer         Shopping Basket<br>C1024             a<br>C1943             a, b, e, f, h<br>C827              a, b, c<br>C315              c, e, f<br><br>Rule customer whom purchase a,b are buying c with it or not ?<br>X-&gt;{a,b}<br>Y-&gt;{c}<br> <br>Support     (X-&gt;Y) ={a,b,c}/Customer.sum() &gt;&gt; 1/4 =%25<br>Confidence  (X-&gt;Y) ={a,b,c}/{a,b}          &gt;&gt; 1/2 =%50</pre><pre>Customer    a b c d e f g h<br>C1024       1 0 0 0 0 0 0 0<br>C1943       1 1 0 0 1 1 0 1<br>C827        1 1 1 0 0 0 0 0<br>C315        0 0 1 0 1 1 0 0<br>Frequency   3 2 2 0 2 2 0 1</pre><p><a href="https://www.kaggle.com/datasets/shazadudwadia/supermarket">dataset</a></p><pre>import pandas as pd<br>original_data=pd.read_csv(&quot;C:/Users/.../GroceryStoreDataSet.csv&quot;,header=None)<br>data=original_data.copy()<br>data.columns=[&quot;Product&quot;]<br>data=list(data[&quot;Product&quot;].apply(lambda x:x.split(&quot;,&quot;)))<br>print(data)</pre><pre>[[&#39;MILK&#39;, &#39;BREAD&#39;, &#39;BISCUIT&#39;],<br> [&#39;BREAD&#39;, &#39;MILK&#39;, &#39;BISCUIT&#39;, &#39;CORNFLAKES&#39;],<br> [&#39;BREAD&#39;, &#39;TEA&#39;, &#39;BOURNVITA&#39;], [&#39;JAM&#39;, &#39;MAGGI&#39;, &#39;BREAD&#39;, &#39;MILK&#39;],<br> [&#39;MAGGI&#39;, &#39;TEA&#39;, &#39;BISCUIT&#39;], [&#39;BREAD&#39;, &#39;TEA&#39;, &#39;BOURNVITA&#39;],<br> [&#39;MAGGI&#39;, &#39;TEA&#39;, &#39;CORNFLAKES&#39;], [&#39;MAGGI&#39;, &#39;BREAD&#39;, &#39;TEA&#39;, &#39;BISCUIT&#39;],<br> [&#39;JAM&#39;, &#39;MAGGI&#39;, &#39;BREAD&#39;, &#39;TEA&#39;], [&#39;BREAD&#39;, &#39;MILK&#39;], [&#39;COFFEE&#39;, &#39;COCK&#39;, <br>&#39;BISCUIT&#39;, &#39;CORNFLAKES&#39;], [&#39;COFFEE&#39;, &#39;COCK&#39;, &#39;BISCUIT&#39;, &#39;CORNFLAKES&#39;],<br> [&#39;COFFEE&#39;, &#39;SUGER&#39;, &#39;BOURNVITA&#39;], [&#39;BREAD&#39;, &#39;COFFEE&#39;, &#39;COCK&#39;],<br> [&#39;BREAD&#39;, &#39;SUGER&#39;, &#39;BISCUIT&#39;], [&#39;COFFEE&#39;, &#39;SUGER&#39;, &#39;CORNFLAKES&#39;],<br> [&#39;BREAD&#39;, &#39;SUGER&#39;, &#39;BOURNVITA&#39;], [&#39;BREAD&#39;, &#39;COFFEE&#39;, &#39;SUGER&#39;],<br> [&#39;BREAD&#39;, &#39;COFFEE&#39;, &#39;SUGER&#39;], [&#39;TEA&#39;, &#39;MILK&#39;, &#39;COFFEE&#39;, &#39;CORNFLAKES&#39;]]</pre><pre>from mlxtend.preprocessing import TransactionEncoder<br>te=TransactionEncoder()<br>te_data=te.fit_transform(data)<br>data=pd.DataFrame(te_data,columns=te.columns_)<br>print(data)</pre><pre>    BISCUIT  BOURNVITA  BREAD   COCK  COFFEE  CORNFLAKES    JAM  MAGGI   MILK  SUGER    TEA<br>0      True      False   True  False   False       False  False  False   True  False  False<br>1      True      False   True  False   False        True  False  False   True  False  False<br>2     False       True   True  False   False       False  False  False  False  False   True<br>3     False      False   True  False   False       False   True   True   True  False  False<br>4      True      False  False  False   False       False  False   True  False  False   True<br>5     False       True   True  False   False       False  False  False  False  False   True<br>6     False      False  False  False   False        True  False   True  False  False   True<br>7      True      False   True  False   False       False  False   True  False  False   True<br>8     False      False   True  False   False       False   True   True  False  False   True<br>9     False      False   True  False   False       False  False  False   True  False  False<br>10     True      False  False   True    True        True  False  False  False  False  False<br>11     True      False  False   True    True        True  False  False  False  False  False<br>12    False       True  False  False    True       False  False  False  False   True  False<br>13    False      False   True   True    True       False  False  False  False  False  False<br>14     True      False   True  False   False       False  False  False  False   True  False<br>15    False      False  False  False    True        True  False  False  False   True  False<br>16    False       True   True  False   False       False  False  False  False   True  False<br>17    False      False   True  False    True       False  False  False  False   True  False<br>18    False      False   True  False    True       False  False  False  False   True  False<br>19    False      False  False  False    True        True  False  False   True  False   True</pre><pre>from mlxtend.frequent_patterns import apriori<br>df1=apriori(data,min_support=0.05,use_colnames=True)<br>print(df1)</pre><pre>    support                             itemsets<br>0      0.35                            (BISCUIT)<br>1      0.20                          (BOURNVITA)<br>2      0.65                              (BREAD)<br>3      0.15                               (COCK)<br>4      0.40                             (COFFEE)<br>..      ...                                  ...<br>78     0.05         (MAGGI, TEA, BREAD, BISCUIT)<br>79     0.10  (CORNFLAKES, COFFEE, BISCUIT, COCK)<br>80     0.05            (MAGGI, JAM, MILK, BREAD)<br>81     0.05             (MAGGI, TEA, JAM, BREAD)<br>82     0.05      (CORNFLAKES, TEA, MILK, COFFEE)<br><br>[83 rows x 2 columns]</pre><pre>from mlxtend.frequent_patterns import apriori,association_rules<br>df2=association_rules(df1,metric=&quot;confidence&quot;,min_threshold=0.5)<br>print(df2)</pre><pre>           antecedents           consequents  antecedent support  consequent support  support  confidence       lift  leverage  conviction  zhangs_metric<br>0             (BISCUIT)               (BREAD)                0.35                0.65     0.20    0.571429   0.879121   -0.0275    0.816667      -0.174603<br>1                (COCK)             (BISCUIT)                0.15                0.35     0.10    0.666667   1.904762    0.0475    1.950000       0.558824<br>2          (CORNFLAKES)             (BISCUIT)                0.30                0.35     0.15    0.500000   1.428571    0.0450    1.300000       0.428571<br>3           (BOURNVITA)               (BREAD)                0.20                0.65     0.15    0.750000   1.153846    0.0200    1.400000       0.166667<br>4           (BOURNVITA)               (SUGER)                0.20                0.30     0.10    0.500000   1.666667    0.0400    1.400000       0.500000<br>..                  ...                   ...                 ...                 ...      ...         ...        ...       ...         ...            ...<br>141   (TEA, CORNFLAKES)        (COFFEE, MILK)                0.10                0.05     0.05    0.500000  10.000000    0.0450    1.900000       1.000000<br>142       (TEA, COFFEE)    (CORNFLAKES, MILK)                0.05                0.10     0.05    1.000000  10.000000    0.0450         inf       0.947368<br>143         (TEA, MILK)  (CORNFLAKES, COFFEE)                0.05                0.20     0.05    1.000000   5.000000    0.0400         inf       0.842105<br>144  (CORNFLAKES, MILK)         (TEA, COFFEE)                0.10                0.05     0.05    0.500000  10.000000    0.0450    1.900000       1.000000<br>145      (COFFEE, MILK)     (TEA, CORNFLAKES)                0.05                0.10     0.05    1.000000  10.000000    0.0450         inf       0.947368</pre><p>The Eclat algorithm can be considered as a modified version of the Apriori algorithm.</p><pre>data_2nd=pd.DataFrame(data)<br>print(data_2nd)</pre><pre>         0       1           2           3<br>0     MILK   BREAD     BISCUIT        None<br>1    BREAD    MILK     BISCUIT  CORNFLAKES<br>2    BREAD     TEA   BOURNVITA        None<br>3      JAM   MAGGI       BREAD        MILK<br>4    MAGGI     TEA     BISCUIT        None<br>5    BREAD     TEA   BOURNVITA        None<br>6    MAGGI     TEA  CORNFLAKES        None<br>7    MAGGI   BREAD         TEA     BISCUIT<br>8      JAM   MAGGI       BREAD         TEA</pre><pre>from pyECLAT import ECLAT<br>min_product=2<br>min_support=0.2<br>max_product=max([len(x) for x in data])<br><br>ec=ECLAT(data_2nd,verbose=True)<br>a,b=ec.fit(min_support=min_support,min_combination=min_product,max_combination=max_product)<br>print(b)</pre><pre>Combination 2 by 2<br>36it [00:00, 845.79it/s]<br>Combination 3 by 3<br>84it [00:00, 927.71it/s]<br>Combination 4 by 4<br>126it [00:00, 811.92it/s]<br>{&#39;MILK &amp; BREAD&#39;: 0.2, &#39;SUGER &amp; COFFEE&#39;: 0.2, &#39;SUGER &amp; BREAD&#39;: 0.2, &#39;MAGGI &amp; TEA&#39;: 0.2, &#39;BISCUIT &amp; BREAD&#39;: 0.2, &#39;COFFEE &amp; CORNFLAKES&#39;: 0.2, &#39;TEA &amp; BREAD&#39;: 0.2}</pre><pre>import pandas as pd<br>original_data=pd.read_csv(&quot;C:/Users/.../Online Retail.csv&quot;)<br>data=original_data.copy()<br>data=data.dropna()<br>data=data[~data[&quot;InvoiceNo&quot;].str.contains(&quot;C&quot;)]<br>data_2nd=data[&quot;Country&quot;].value_counts()<br>print(data_2nd)</pre><pre>United Kingdom          354345<br>Germany                   9042<br>France                    8342<br>EIRE                      7238<br>Spain                     2485<br>Netherlands               2363<br>Belgium                   2031<br>Switzerland               1842<br>Portugal                  1462<br>Australia                 1185<br>Norway                    1072<br>...</pre><pre>country=data[data[&quot;Country&quot;]==&quot;United Kingdom&quot;]<br>basket=country.iloc[:,[0,2,3]]<br>basket=basket.groupby([&quot;InvoiceNo&quot;,&quot;Description&quot;])[&quot;Quantity&quot;].sum().unstack().reset_index().set_index(&quot;InvoiceNo&quot;)<br>basket_arranged = basket.applymap(lambda x: 0 if x &lt;= 0 else 1)<br>print(basket_arranged)</pre><pre> - eclat study pr.py&quot;<br>Description   4 PURPLE FLOCK DINNER CANDLES   50&#39;S CHRISTMAS GIFT BAG LARGE  ...  ZINC WIRE KITCHEN ORGANISER  ZINC WIRE SWEETHEART LETTER TRAY<br>InvoiceNo                                                                    ...<br>536365                                    0                               0  ...                            0                                 0<br>536366                                    0                               0  ...                            0                                 0<br>536367                                    0                               0  ...                            0                                 0<br>536368                                    0                               0  ...                            0                                 0<br>536369                                    0                               0  ...                            0                                 0</pre><pre>from mlxtend.frequent_patterns import apriori,association_rules<br>df1=apriori(basket_arranged.astype(&quot;bool&quot;),min_support=0.02,use_colnames=True)<br>df2=association_rules(df1,metric=&quot;confidence&quot;)<br>print(df2.iloc[0])</pre><pre>antecedents            (PINK REGENCY TEACUP AND SAUCER)<br>consequents           (GREEN REGENCY TEACUP AND SAUCER)<br>antecedent support                             0.029611<br>consequent support                             0.036759<br>support                                        0.024266<br>confidence                                     0.819473<br>lift                                          22.293137<br>leverage                                       0.023177<br>conviction                                     5.335706<br>zhangs_metric                                  0.984289</pre><ul><li><em>antecedents and </em><em>consequents: The items in the antecedent and consequent of the association rule, respectively.</em></li><li><em>antecedent support and </em><em>consequent support: The proportion of transactions that contain the antecedent and consequent items, respectively.</em></li><li><em>support: The proportion of transactions that contain both the antecedent and consequent items.</em></li><li><em>confidence: The proportion of transactions that contain both the antecedent and consequent items, out of all transactions that contain the antecedent.</em></li><li><em>lift: The ratio of the observed support for both the antecedent and consequent items together to what would be expected if the items were independent of each other. A value greater than 1 indicates positive correlation.</em></li><li><em>leverage: The difference between the observed support for both the antecedent and consequent items together and what would be expected if the items were independent of each other. Positive values indicate positive correlation.</em></li><li><em>conviction: A measure of how much the consequent item depends on the antecedent item.</em></li><li><em>zhangs_metric: Another measure of the strength of association between the antecedent and consequent items.[ChatGPT]</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46afe82e9ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>