<?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 Lusine Zilfimian on Medium]]></title>
        <description><![CDATA[Stories by Lusine Zilfimian on Medium]]></description>
        <link>https://medium.com/@lusine.zilfimian?source=rss-7abbb2552abe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*QAzORGaibFKUnWYEzUSULQ.jpeg</url>
            <title>Stories by Lusine Zilfimian on Medium</title>
            <link>https://medium.com/@lusine.zilfimian?source=rss-7abbb2552abe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:51:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lusine.zilfimian/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[Dynamic Time Warping: Algorithmic Foundations and Applications in Time Series Similarity Search]]></title>
            <link>https://medium.com/@lusine.zilfimian/dynamic-time-warping-algorithmic-foundations-and-applications-in-time-series-similarity-search-fe25accc2409?source=rss-7abbb2552abe------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe25accc2409</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Lusine Zilfimian]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 19:14:46 GMT</pubDate>
            <atom:updated>2026-10-11T19:14:46.793Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This report explores Dynamic Time Warping for time series analysis, comparing it with Euclidean Distance and its optimized version using the Sakoe-Chiba band. DTW’s ability to handle temporal distortions is demonstrated through ATM transaction data from Armenia, highlighting its importance in clustering and real-world applications.</em></p><h3>Introduction</h3><p>Time series analysis plays a valuable role in addressing a wide variety of real-world problems across multiple research domains. Examples include economic forecasting, gene expression analysis, medical surveillance, hydrology, electro-cardiogram analysis, biometrics, process monitoring [1, 2]. Time series data mining reveals complex patterns and relationships within the data, but it also presents several challenges. One of the most significant issues is the high dimensionality of time series data, which complicates the task of defining a meaningful similarity measure that aligns with human perception.</p><p>This report focuses on analyzing a similarity measure for time series that captures data patterns — the Dynamic Time Warping (DTW) algorithm, emphasizing its behavior in terms of time and space complexity. Given the growing size of time series datasets, efficient processing methods like DTW are essential. Dynamic time warping is providing both a distance measure that is insensitive to local compression and stretches, and the warping which optimally deforms one of the two input series onto the other [2].</p><p>The key advantage of DTW over Euclidean distance is its ability to handle time lags or temporal distortions between the compared sequences. In many real-world scenarios, time series data may exhibit variations in speed, phase shifts, or temporal misalignments. Euclidean distance, by strictly comparing corresponding points, may fail to capture the underlying similarities between two time series with such variations. DTW, on the other hand, allows for flexible alignment, warping, and stretching of the sequences to find the best matching pattern.</p><p>The report further evaluates the advantages and disadvantages of DTW compared to Euclidean Distance, demonstrating the specific problems DTW can effectively address. Additionally, the practical application of DTW in time series clustering is demonstrated using bank data. The implementation was carried out in the R programming language, using the dtw package, which provides a unification of a variety of algorithms and constraints related to DTW.</p><p>The report considers an exclusive set of hourly data spanning over six months, obtained from an entire ATM network within one of Armenia’s financial institutions. This dataset includes cash withdrawal activities across roughly 130 ATMs, constituting approximately 16% of the total ATMs within Armenia. The data will be analyzed using the DTW algorithm to address a clustering problem and present a solution based on the theory discussed.</p><p>The second section of the report focuses on the functionality of the algorithms. It begins with a description of the Euclidean Distance and DTW algorithms, followed by DTW with the Sakoe-Chiba band, which demonstrates a method for optimizing the complexity of DTW. The third section discusses the practical application of DTW in real-world problem-solving, outlining the problem statements and presenting the results obtained from clustering with these algorithms. The report concludes with a summary of the findings.</p><h3>Algorithmic Overview</h3><p>Initially, it is essential to define the similarity measures for time series. The similarity measure D(Q, S) between time series Q and S is a function taking two time series as inputs and returning the distance d between these series. This distance has to be nonnegative, that is, D(Q, S) ≥ 0. If this measure satisfies the additional symmetry property D(Q, S) = D(S, Q) and subadditivity D(Q, S) ≤ D(Q, U) + D(U, S), also known as the triangle inequality, the distance is said to be a metric. These properties are important when comparing time series using different algorithms.</p><h3>Euclidean Distance</h3><p>The Euclidean distance is a widely used method for measuring the similarity between (a lot of things, including) two time series. Caution (!) one limitation of this algorithm is that it requires the time series to be of equal length. In contrast, as will be discussed later, DTW does not have this constraint. Let |Q| denote the length of the time series Q. The Euclidean distance for time series Q and S is then defined (as in other cases) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/0*fXONvLfjpjNeZVCX" /></figure><p>This algorithm operates by comparing each pair of data points from the two time series that correspond to the same time instance. But, almost every time series mining task requires a nuanced understanding of similarity between series, often based on the <strong>more intuitive</strong> concept of shape. When humans analyze multiple characteristics of a time series simultaneously, they can abstract away from issues such as amplitude variations, scaling, temporal warping, noise, and outliers [1]. The Euclidean distance, while simple and effective for certain applications, <strong>fails</strong> to capture such levels of abstraction. To address these challenges, we turn to DTW, a method designed to overcome the limitations of Euclidean distance by allowing for more flexible comparisons of time series, even when they are <strong>misaligned</strong> or (which is not less important) <strong>vary in length</strong>. Let’s examine the differences in greater detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*bhiRL7BtgN2Eu6qWsXIhgw.png" /><figcaption>Figure 1. Comparison of Euclidean distance (a, b) and DTW alignment (c, d), cost matrices and warping paths. Source: [3]</figcaption></figure><p>Figure 1 (a, b) illustrates the alignment between two time series using the Euclidean distance. This straightforward measure compares corresponding points in the time series without considering time distortions. The alignment is achieved by connecting the points directly, resulting in a rigid alignment that may not accurately capture the underlying similarities between the time series. In contrast, Figure 1 (c, d) demonstrates the alignment between the same two time series using DTW. By allowing for warping and stretching of the sequences, DTW identifies the optimal alignment path that minimizes the total cost. This flexible alignment accounts for potential time distortions and provides a more accurate representation of the similarities between the time series. But it is not clear for now, so let’s make DTW as intuitive as Euclidean distance is.</p><h3>Unconstrained Dynamic Time Warping</h3><p>And so, Dynamic Time Warping is another widely used algorithm in the field of time series similarity search. It was originally developed to measure the similarity between spoken words in speech recognition systems [4]. Originally proposed in the 1970s, DTW was developed to address variations in speaking rates across speakers and utterances. For instance, DTW can effectively identify a low distance score between the sound signals of “now” and “nooow,” demonstrating its insensitivity to differences in the duration of specific sounds.</p><p>DTW refers to a class of algorithms designed to compare series of values by stretching or compressing them locally to make one series resemble the other as closely as possible. After applying this alignment, the distance between the two series is calculated by summing the distances of their corresponding aligned elements.</p><p>In contrast to Euclidean distance which proposes a one-to-one matching, DTW is suggested as a one-to-many metric [5]. One of the key advantages of DTW is its ability to compare time series of different lengths. More importantly, DTW can align time series that are out of phase, even when the phases vary in duration. When applied to time series data, this means that DTW can handle scenarios where the series start at different times or exhibit variations in temporal alignment. DTW enables the identification of similarities between time series by focusing on the overall shape of the data, rather than small fluctuations, allowing for the detection of patterns across various time scales. Generally, dynamic programming is used in order to find the path effectively.</p><p>In brief it can be concluded that DTW has some advantages and disadvantages as follows:</p><p><strong>Advantages:</strong></p><ol><li>DTW can align time series even if they are out of phase, unlike Euclidean distance.</li><li>DTW supports clustering time series of different lengths without missing data, while normalization can ensure accurate comparisons of same-length series.</li><li>DTW has a significantly lower error rate compared to Euclidean distance.</li></ol><p><strong>Disadvantages:</strong></p><ol><li>DTW can distort distances as it requires matching all points, making it sensitive to outliers.</li><li>DTW is computationally expensive, requiring quadratic time. Despite efforts to speed it up through approximations, it remains challenging, particularly for clustering tasks where distances between all pairs must be calculated [5].</li></ol><p>Consider two time series, Q and S, of lengths n and m, respectively, where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*wn5D1TNXivGdbBOf" /></figure><p>A matrix of size n × m can be constructed. This matrix aligns the two sequences Q and S, with each element (i, j) of the matrix containing the squared distance between the two points qi and sj:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*AycacTADG663tvj5" /></figure><p>Using dynamic programming, DTW finds the optimal non-linear alignment of the points of the time series Q and S using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*SdKqpM6E04JDPL6D" /></figure><p>The distance between Q and S is defined as DTW(Q, S) = Dn,m.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*fpXulPjRgUf4dWzDazyHOw.png" /><figcaption>Figure 2. The local distance matrix (left) and the symmetric step pattern (right). Source: [2], [3]</figcaption></figure><p>It is important to note that this local constraint limits movement between corresponding cells to a single step at a time — horizontally, vertically, or diagonally (Figure 2). However, the slope constraint on the warping function can be adjusted and may vary depending on the specific requirements of different applications [6].</p><p>The cost matrix (Figure 2) is a fundamental component in DTW, representing the pairwise distances between individual points in the two time series being compared. Each element in the matrix corresponds to the cost of aligning two specific points. The goal of DTW is to find the optimal path through the matrix with the minimum total cost, indicating the best alignment between the time series.</p><p>The optimal alignment in DTW is defined by the shortest warping path in a distance matrix, which maps indices between two time series. The shape of the warping curve itself provides information about which point matches which, i.e., the pairwise correspondences of time points can be easily inspected (Figure 3). It captures the alignment of corresponding points in the two time series, taking into account possible time distortions or shifts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*1aOYhRNlQnCMBsLIk6EOoA.png" /><figcaption>Figure 3. DTW alignment of the time series (left), distance matrix with warping path (center), warping path constrained by the Sakoe-Chiba band (right). Source: [7]</figcaption></figure><p>Finding the optimal alignment (Figure 3, left) can be quite slow because it requires comparing each element of Q with each element of S. Depending on the length of the sequences, DTW is often hundreds or even thousands of times slower than Euclidean distance. For instance, an experiment using DTW to align gene expression data was reported to take 6 days [8]. To speed up the computation, lower bounding techniques have been introduced. For example, Keogh and Ratanamahatana (R-K band) introduced upper and lower envelopes, reducing the complexity [1]. Furthermore, it can lead to bad alignments where a relatively small part of one time series maps onto a large section of the other one. This can be avoided by narrowing the searching window around the diagonal of the warping matrix using global constraints [9]. Additionally, temporal constraints on the DTW warping window, such as the Sakoe-Chiba Band (S-C band) and Itakura Parallelogram, improve both speed and accuracy by preventing pathological matches from extended warping. The R-K band is a general global constraint model that can represent any global constraints with arbitrary shape and size effectively.<a href="#fn1">1</a> Unlike the single S-C band, these multiple R-K bands can be adjusted as needed according to each class’ warping path [7]. Let us further explore the Sakoe-Chiba Band constraint and then compare its complexity.</p><h3>DTW with Sakoe-Chiba Constraint</h3><p>Global constraints, often referred to as warping windows, restrict the warping curves from entering specific regions of the (i, j) plane [2]. These constraints are designed to incorporate prior knowledge about the time distortion’s limitations, ensuring that the alignment process remains both meaningful and efficient.</p><p>The Sakoe-Chiba band was introduced as an optimized variant of the DTW algorithm to reduce its complexity. This approach introduces a parameter known as the warping window, denoted as w, which acts as a constraint on the dynamic programming algorithm. Instead of considering the entire matrix, the algorithm restricts its computations to a range of ±w along the diagonal of the matrix, provided the constraints remain within the matrix boundaries. Typically, the width of the warping window is set to approximately 10% of the length of the time series [9]. This constraint significantly reduces the computational cost by limiting the alignment search space. The concept is visually represented in Figure 3 (right). Note that Euclidean distance can be considered a special case of DTW, where the constraint is strictly limited to the diagonal of the matrix, effectively using a warping window of w = ±0, and a warping window of 100% width represents an unconstrained similarity measure.</p><h3>Complexity Comparison</h3><p>The Euclidean distance is the most computationally efficient among the algorithms, requiring only linear time, O(n), to compare two time series of the same length n. This is because the algorithm involves a single pass through both time series, computing the squared difference between corresponding points at each position.</p><p>The DTW algorithm begins by allocating a matrix of size m × n. Each cell in this matrix is populated with the distance values between the i-th element of one time series and the j-th element of the other. The time complexity of DTW is O(mn), as the algorithm utilizes a nested loop structure to compute and fill the matrix. For time series of lengths m and n, each pair of elements requires computation, leading to m × n operations overall. This quadratic relationship makes DTW computationally more intensive compared to simpler algorithms like Euclidean Distance.</p><p>The Sakoe-Chiba band introduces a constraint to the DTW algorithm that reduces the number of elements processed in the inner loop of the dynamic programming approach. Instead of iterating through the entire inner loop at each step, the algorithm is restricted to a fraction of the loop, determined by the window parameter w. As a result, the time complexity of DTW with the Sakoe-Chiba band is reduced to O(mw), where w ≪ m. In summary:</p><ul><li><strong>Euclidean distance:</strong> O(n)</li><li><strong>DTW:</strong> O(mn)</li><li><strong>DTW with Sakoe-Chiba band:</strong> O(mw)</li></ul><h3>Practical Application</h3><h3>Problem Statement and Data</h3><p>Now, let’s apply Dynamic Time Warping to real-world data, while defining an interesting implication and problem statements based on the dataset described below.</p><p>The analysis uses hourly time series data obtained from a financial institution in Armenia, spanning February to May 2023, and includes information on 133 ATMs<a href="#fn2">2</a> and four cash denominations. The primary objective is to investigate cash withdrawal dynamics and clustering possibilities within Armenia’s ATM network. For this task we are going to use the R programming language with the dtw package<a href="#fn3">3</a> due to its versatility and robust functionality [2].</p><p>The dataset consists of three primary variables: TERMINAL_ID, a unique identifier assigned to each ATM; NOMINAL, representing the cash denominations under study (1,000, 5,000, 10,000, and 20,000 AMD); and AVAILABLE, the key variable of interest, which records the hourly count of cash availability for each combination of ATM and denomination. To understand the data better, let’s examine, for example, two different ATMs with vastly different cash withdrawal patterns for each denomination: Figure 4 illustrates cash availability dynamics for 2 ATMs. One ATM exhibits a replenishment frequency of less than a week with a steep decline in nominal availability (top), while another shows a replenishment interval of approximately 2.5 months with a gradual decrease (bottom). Such differences highlight the complexity of clustering ATMs based on availability patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*FKkxqGVbX5ZiaHyGNkd04A.png" /><figcaption>Figure 4. Cash availability patterns across two ATMs, illustrating variations in replenishment frequency and dynamics, from steep weekly declines (top) to gradual decreases over months (bottom). Source: R output</figcaption></figure><p>By allowing flexible alignment and warping, DTW enables the identification of similar availability patterns across ATMs, even when the timing of events differs. This capability is particularly valuable in optimizing cash withdrawal management and replenishment strategies. Moreover, DTW accommodates time series data of varying lengths, making it suitable for cases where the length of the time series may differ across ATM or nominal. This is particularly useful when dealing with ATMs that have a relatively short sequence of availability data.</p><p>To show the difference between Euclidean distance and DTW, a simple example was considered. The example consists of three time series representing the dynamics of three ATMs, with one nominal (1,000 AMD). Time series from one ATM (147, red) serving as the reference and the other two (177, 178 — blue, yellow respectively) being compared to find the most similar one (Figure 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*t8MVkK03o9vZHtmbjQy1Sw.png" /><figcaption>Figure 5. Comparison of time series from three ATMs, ATM 147 (red) as the reference and ATMs 177 (blue) and 178 (yellow) analyzed for similarity using Euclidean distance and DTW. Source: R output</figcaption></figure><p>Upon comparing these time series using both DTW and Euclidean distance metrics, interesting (ordinary and aligned with the theory) observations were made. When utilizing DTW, the first time series (147) was found to be closer to the third time series (178) in terms of similarity. However, based on the Euclidean distance, the first time series appeared to be closer to the second time series — 177:</p><ul><li><strong>ATM 147 vs 177:</strong> Euclidean = 33,192; DTW = 11,906</li><li><strong>ATM 147 vs 178:</strong> Euclidean = 45,986; DTW = 10,173</li></ul><p>The calculated distances highlight the contrasting results obtained from DTW and Euclidean distance. The observation that the DTW distance is smaller than the Euclidean distance in this example highlights the effectiveness of DTW in capturing the underlying similarities between time series having time distortion.</p><h3>Results</h3><p>Now let’s go deeper, by clustering the ATMs using a multi-dimensional DTW approach (see [10]). This involves calculating the distance between the time series for pairs of ATMs, considering not only the distance between two time series but also the distances between the corresponding Nominal time series of two ATMs. By performing this comparison for all pairs of ATMs, a 130 × 130 distance matrix was generated, providing a comprehensive measure of similarity between ATMs. Using this distance matrix (a sample is shown in Table 1), k-means clustering was applied to group ATMs into clusters.</p><p>Table 1. Pairwise distance matrix representing the similarity between ATMs, calculated using distances between time series for each ATM pair (sample). Source: R output</p><p>The results, depicted in Figure 6, showcase the 3 clusters<a href="#fn4">4</a>, with each cluster represented separately. Within each cluster, 4 time series are represented as a centroid (prototype) for each denomination, providing a concise summary of the time series patterns for that cluster. The clustering analysis reveals three main groups of ATMs based on replenishment frequency: high-frequency, medium-frequency, and low-frequency clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*aXUrpopkPknPzq7JnqRfuw.png" /><figcaption>Figure 6. Cluster analysis results using multi-dimensional DTW, illustrating three distinct clusters. Each cluster is represented by centroid time series, summarizing the patterns within the group. Source: R output</figcaption></figure><ul><li><strong>High-frequency cluster:</strong> ATMs in this group require replenishment within approximately one week. These ATMs are likely to experience high cash withdrawal demand, necessitating frequent restocking.</li><li><strong>Medium-frequency cluster:</strong> This group consists of ATMs with a replenishment cycle of about two weeks, indicating moderate usage levels.</li><li><strong>Low-frequency cluster:</strong> ATMs in this cluster demonstrate a replenishment cycle exceeding one month. These machines are likely to serve in areas with lower withdrawal activity or reduced customer traffic.</li></ul><p>To further examine the clustering results, Figure 7 focuses specifically on the time series for the 1,000 AMD nominal across each cluster. The black line in each plot represents the cluster prototype or centroid, summarizing the typical behavior of the nominal’s availability within that cluster. This visualization highlights the distinct temporal patterns across clusters, illustrating how the availability dynamics for the 1,000 AMD nominal align with the broader clustering structure. By comparing individual time series to their corresponding cluster prototypes, it becomes evident how well the clustering captures the variability and shared trends within each group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Pqm7vQs-ikUN_oxsXvEArw.png" /><figcaption>Figure 7. Time series of 1,000 AMD nominal across clusters, with black lines representing cluster prototypes. Source: R output</figcaption></figure><h3>Conclusion</h3><p>This report provides a detailed analysis of the Dynamic Time Warping (DTW) algorithm, emphasizing its advantages and disadvantages. The main advantage of DTW over Euclidean distance is its ability to handle temporal distortions in time series, such as speed variations or phase shifts. While Euclidean distance strictly compares corresponding points, DTW flexibly aligns sequences by warping and stretching to reveal underlying similarities. Additionally, a comparative performance evaluation of Euclidean Distance, standard DTW, and DTW constrained by the Sakoe-Chiba band is conducted, focusing on their respective complexities. The Euclidean Distance emerged as the most efficient algorithm with linear time complexity O(n), making it suitable for applications requiring fast and straightforward similarity comparisons. However, its limitation lies in requiring time series to be of equal length and perfect alignment, which restricts its utility in more complex scenarios. In contrast, DTW offers greater flexibility, allowing for the comparison of time series with different lengths and temporal misalignments. This flexibility comes at the cost of higher computational requirements, with a complexity of O(mn), making it more resource-intensive than the Euclidean Distance. The Sakoe-Chiba band enhances the efficiency of DTW by introducing a constraint on the alignment process, reducing the complexity to O(mw), where w represents the warping window size. This optimization makes DTW more computationally feasible for large datasets while retaining its ability to handle misaligned and variable-length time series. The results of this report highlight the trade-offs between computational efficiency and algorithmic flexibility.</p><p>This report demonstrated the practical application of DTW in analyzing time series data from a real-world ATM cash management scenario. By using DTW’s flexibility in handling temporal misalignments, availability patterns of different cash denominations were clustered to identify groups of ATMs with similar replenishment and usage dynamics, even in the presence of temporal misalignments or distortions. By accounting for temporal variations and aligning availability trends, DTW enhances the accuracy of clustering. The methodology provided a robust framework to compare time series with varying speeds and phases, addressing limitations associated with traditional distance measures like Euclidean distance. The clustering process revealed distinct groups of ATMs based on replenishment frequency: high-frequency clusters requiring weekly restocking, mid-frequency clusters with biweekly schedules, and low-frequency clusters operating efficiently with monthly restocking. Identifying ATMs with similar availability patterns enables tailored replenishment schedules, reducing operational costs and improving service reliability.</p><p>This report underscores the significance of advanced time series analysis methods, such as DTW, in addressing complex, real-world challenges in financial and operational contexts. Future work may extend this approach to incorporate additional data, different band types, local constraints or explore hybrid techniques for even greater accuracy and efficiency.</p><h3>References</h3><blockquote>P. Esling and C. Agon, “Time-series data mining,” <em>ACM Computing Surveys</em>, vol. 45, Article 12, Nov. 2012.</blockquote><blockquote>T. Giorgino, “Computing and visualizing dynamic time warping alignments in R: The dtw package,” <em>Journal of Statistical Software</em>, vol. 31, no. 7, 2009.</blockquote><blockquote>Z. Zhang, R. Tavenard, A. Bailly, X. Tang, and P. Tang, “Dynamic time warping under limited warping path length,” <em>Information Sciences</em>, vol. 393, pp. 91–107, 2017.</blockquote><blockquote>J. B. Kruskal and M. Liberman, “The symmetric time-warping problem: from continuous to discrete,” in <em>Time Warps, String Edits, and Macromolecules: The Theory and Practice of Sequence Comparison</em> (D. Sankoff and J. B. Kruskal, eds.), ch. 4, CSLI Publications, 1983.</blockquote><blockquote>S. R. A. S. Yazdi, <em>Clustering of Large Time-Series Datasets Using a Multi-Step Approach</em>. Doctoral dissertation, University of Malaya, 2013.</blockquote><blockquote>H. Sakoe and S. Chiba, “Dynamic programming algorithm optimization for spoken word recognition,” <em>IEEE Transactions on Acoustics, Speech, and Signal Processing</em>, vol. 26, no. 1, pp. 43–49, 1978.</blockquote><blockquote>V. Niennattrakul and C. A. Ratanamahatana, “Learning DTW global constraint for time series classification.”</blockquote><blockquote>C. A. Ratanamahatana and E. Keogh, “Making time-series classification more accurate using learned constraints.”</blockquote><blockquote>Z. Geler, V. Kurbalija, M. Ivanović, M. Radovanović, and W. Dai, “Dynamic time warping: Itakura vs Sakoe-Chiba.”</blockquote><blockquote>M. Shokoohi-Yekta, B. Hu, H. Jin, J. Wang, and E. Keogh, “Generalizing dynamic time warping to the multi-dimensional case requires an adaptive approach,” in <em>Proceedings of the 21st ACM SIGKDD International Conference on Knowledge Discovery and Data Mining</em>, pp. 905–914, 2015.</blockquote><ol><li>For more detailed information on these band types, I recommend referring to the original paper by Sakoe and Chiba or the article titled “Dynamic Time Warping: Itakura vs Sakoe-Chiba” by Geler, Kurbalija, et al. These resources provide comprehensive insights into the different band approaches and their applications in DTW analysis.<a href="#fnref1">↩︎</a></li><li>Constituting approximately 16% of the total ATMs within Armenia.<a href="#fnref2">↩︎</a></li><li>The package enables users to compute time series alignments while allowing flexibility in mixing various features, such as continuity constraints, restriction windows, endpoint handling, and local distance definitions. Furthermore, the dtw package includes visualization tools that help to illustrate alignments and constraints through several classic diagram types, enhancing the understanding of the algorithm’s workings.<a href="#fnref3">↩︎</a></li><li>The number of clusters was determined based on the optimal solution, which in this case was found to be 3 clusters.<a href="#fnref4">↩︎</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe25accc2409" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Galton’s law of filial regression. Understanding the phenomenon of regression towards the mean]]></title>
            <link>https://medium.com/@lusine.zilfimian/galtons-law-of-filial-regression-understanding-the-phenomenon-of-regression-towards-the-mean-104b04724917?source=rss-7abbb2552abe------2</link>
            <guid isPermaLink="false">https://medium.com/p/104b04724917</guid>
            <category><![CDATA[galton]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Lusine Zilfimian]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 18:56:46 GMT</pubDate>
            <atom:updated>2026-10-11T19:07:40.776Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The word regression comes from Latin regressus, which means “a return”. But how and when this phenomenon was born? The article is about the first study about regression toward mediocrity. The idea behind the regression toward the mean is that, following an extreme random event, the next random event is likely to be less extreme. In this article I am going to present the main findings of Galton’s filial regression on the famous Galton data.</em></p><h3>Introduction</h3><p>Today the most basic data mining tool is the linear regression and, it is often used to compare more complex approaches. The word regression comes from Latin regressus, which means “a return”, thus the meaning of the word regression can be interpreted as the act of going back. However, the least of us knows from where the regression comes and how the phenomenon of regression has appeared. We are going to speak about the first study about regression and the main idea of Galton filial regression. For this purpose, the dataset similar to famous Galton data will be used.</p><p><a href="http://www.galton.org/">Sir Francis Galton</a> was interested in the heredity of human characteristics like personality temperament, artistic ability, and disease incidence, etc. Among all these traits Galton collected information about the human statures of different families to understand the concept of human height heredity. In his classic paper “Regression Towards Mediocrity in Hereditary Stature” he measured the relationship between the heights of children and those of their parents. Galton wanted to know could the height of parents somehow explain/predict the height of the child. For that time the concept of regression, notions like explanatory and dependent variables, noise term did not exist and the knowledge about genetics was limited.</p><p>One should think, that the dependence is obvious — tall parents have tall children and vice versa. But, surprisingly, Galton discovered that parents who were taller than average had tall children, but they were not as tall as their parents. And parents with height below the average children were short, but not lower than their parents. So, the height of already adult children deviates to a lesser extent from the average than the height of parents. That is, the children are stronger regress to the average.</p><h3>About Galton findings</h3><p>Do you believe that your talent and beauty must be inherited by your children? I hope you do not think so because the statistics are more conservative on this issue. A statistical principle called “regression to the mean” will help explain this.</p><p>The term regression <a href="https://en.wikipedia.org/wiki/Regression_analysis">was coined</a> by British statistician Francis Galton in the nineteenth century to describe a biological phenomenon. The first studies of Galton referred to the seed size in generations of sweet peas, which he called revision toward the mean. Then, he changed the name of the phenomenon to regression in the mid-1880s after obtaining human data on the heights of parents and their children.</p><p>Galton observed that the characteristics of parents are not fully transmitted to their children. The idea of the phenomenon is that the heights of the adult children tend to regress toward the mediocre point. And simple linear regression is also called reversion to the mean and <em>reversion to mediocrity.</em></p><p>Galton found that children of short parents tended to be shorter than average, while children of tall parents tended to be taller than average, “however, the transmission of height across generations was imperfect.” This means that the difference between a child and its parents for height is proportional to its parents’ deviation from typical people in the population. In order to find to what extent the heights are inherited across generations Galton uses the principle of regression (without knowing about it) and stated in his article “the deviates of the children are to those of the mid-parent as 2 to 3”. So, the child gained only two-thirds of an inch for each inch the parents exceeded the average. Galton concluded that there was <strong>regression towards mediocrity</strong> in height.</p><p>To measure the rate of regression in hereditary stature, Galton divided the height of offspring into 9 subgroups according to the median height of their two parents. Galton used the median as a measure of central tendency and semi-interquartile range as a measure of variability. Although this poor choice of descriptive statistics, Galton found the important pattern by plotting the median offspring height against the mid-parent height, and by eye, fitted a straight line to the nine data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*2tPMO8UlHhx5F7ZGWZVtXA.png" /><figcaption>Figure 1. The histograms of mid-parent’s and child’s height</figcaption></figure><h3>About the data</h3><p>The dataset was used by Galton in 1885 to study the relationship between the heights in inches of parents and those of their children. The data is represented by a child. Originally, <a href="http://www.medicine.mcgill.ca/epidemiology/hanley/galton/notebook/index.html">Galton’s notebook</a> lists 963 children in 205 families ranging from 1–15 adult children. 29 of these observations had non-numeric heights recorded. Families are listed in descending order of father, and within these, mother height. The 205 families are identified by the numbers 1–135, 136A, 136–204.</p><p>There are different sources and variations of Galton’s initial data. We are going to use the dataset <strong>GaltonFamilies</strong> from the R package <strong>HistData</strong> as this data is more comprehensive among others.</p><p>From the graphs (Figure 1), we can see that the distributions of parent’s and child’s height can be approximated by the normal distribution. It is important because Galton findings is true when variables follow a normal distribution.</p><p>Suppose we want to understand do tall fathers have tall kids or do tall mothers have tall kids. The simple visualization (Figure 2) shows that there are positive relationships between the average height of kids in a family and their fathers’ and mothers’ heights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*2pKPbASKUkdzAhin7r_wAQ.png" /><figcaption>Figure 2. The relationship between heights of father/mother and adult children from Galton original dataset</figcaption></figure><p>When regressing the heights of adult children on those of their parents, Galton took into consideration the fact that in general men are taller than women. In order to adjust the height in his analysis Galton multiplied female heights by 1.08. He transmuted the height of females and then defined the term <strong>mid-parent</strong> which is an average of the father’s height and the transmuted mother’s height. Galton applied the process of adjusting the heights of women to the height of each daughter, too.</p><h3>Understanding Galton’s findings</h3><p>To describe the main concept of regression let’s look at the following subcase. Without knowing the mid-parental height the best guess for a child height, probably, would be the simple average height of all children. However, what if the mid-parental height of this child is greater than average? Is still the guess of the mean for the child good one? So, in that case, the conditional expectation will be the better prediction for the height of the child. For any specific value of mid-parental height (for example 67.4) we will have a very little number of data points. The usage of rounding to the nearest inch can help to solve this issue. Then, we can predict the height of a child calculating the average of this subgroup.</p><p>Note that 67-inch midparent is shorter than the average (overall mean is 69.2, mean for 67-inch group is 66.9), and the prediction for child height is lower than average (overall mean 67, average of 67-inch group 65.5), but the deviation from the average for midparent is larger. Galton said that children have <strong>regressed</strong> to average height.</p><p>As Galton suggested, let’s consider the means of the groups and plot it against the divided groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*BSLDs7XHYvbAHUJ-onSOhA.png" /><figcaption>Figure 3. The relationship between heights of father/mother and adult children from Galton original dataset</figcaption></figure><p>The median of boxplots in Figure 3 is similar to the points of Galton’s famous plot. And this is the main idea of his study. Galton simply divided the height of parents, created groups, calculated the mediocre point of children’s height for each group and plot in on the graph. When he noticed some patterns between these points and the height of mid-parents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*imHt31vnw5DsCBd3Tix0JQ.png" /><figcaption>Figure 4. Constructing Galton’s Table 1 (joint distribution of the heights of mid-parents and their adult children) and Plate X, which are first steps for simple linear regression.</figcaption></figure><p>Note that both the total number of mid-parents and their children are approximately normal. Galton showed that if two variables follow a bivariate normal distribution, the prediction computing via conditional expectation and the regression line is reciprocal.</p><p>From the table (Figure 4), corresponding to mid-parents of given height we calculated the mean height of the children (the last column). These mean values are plotted against mid-parental height. Galton fitted a straight line through the points by eye and found that its slope was 2/3. We will check it by considering the linear regression model (see below). He expressed this in a chart showing the rate of regression in hereditary stature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*TXuzWk9j8SwYWlN3KB3_vA.png" /><figcaption>Figure 5. Rate of regression in hereditary stature — modern Regression line.</figcaption></figure><p>The plot (Figure 5) is essential in the formulation of the Galton rule. The points follow a straight line which we now call the regression line. The red line refers to the height of mid-parents in inches from 64 to 73 with a step of 1. The green points show the mean height of the children of each group. The green line gives the smoothed results of the corresponding mean heights of children. Galton showed that the point of convergence is at the level of mediocrity and that “the mean filial regression towards mediocrity was directly proportional to the parental deviation from it.”</p><h3>The regression and correlation</h3><p>Now, when we all know about the concept of regression it is quite simple to predict the values of the dependent variable using the value of the explanatory variable and the fitted line. The simple linear regression line has the following representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hr9EXsgNnzi72qSAoz73cg.png" /></figure><p>Based on the obtained coefficient estimation using OLS the above equation can be rewritten as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcBPP3jt2EyDQtyXIHUejw.png" /></figure><p>If we have imperfect correlation (a.k.a apart from 0 and 1) linear regression is the appropriate model for this data. Even Galton used estimated correlation coefficient, he recognized the important relationship between the paired variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/0*vvOdVKNfbTUNzD8U" /></figure><p>Note that, differences in variability between the two variables influence the slope of the regression line but not the level of association between the variables. From the formula above, if we standardize the variables, the regression line has intercept 0 and slope equal to the correlation ρ. Galton found a slope of 0.66, which indicated to him that extremely large or small mother seeds typically generated less extreme daughter seeds.</p><p>In the Galton studies, the angle formed between the least-squares regression line and the positive direction of the x-axis is approximately 34°. Galton determined their estimate of the regression coefficient by comparing the tangent of this angle to the tangent of 45°. That is tan(34°) : tan(45°) ≈ 2 : 3. According to Galton, the law of regression can be defined in the following way: “The height-deviate of the offspring is, on the average, two-third of the height-deviate of its mid-parentage”. The same result is derived using the linear regression model (Figure 6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*prd0Mjf6ZZreFczxKleveg.png" /><figcaption>Figure 6. The output of linear regression model obtained from R statistical package.</figcaption></figure><p>Although Galton could not analytically derive the coefficient of regression he used geometrical proof — contours of equal bivariate frequencies in the joint distribution which looked like an ellipse. The data ellipse is a useful data visualization technique in analyzing bivariate data which adds a visual summary to a scatterplot. It shows the means, standard deviations, correlation and slope of the regression line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*TFBQD5wAhVnA5r8DgPHDeA.png" /><figcaption>Figure 7. Visualization of the relationship between heights of mid-parents and adult children using data ellipses.</figcaption></figure><p>The overlayed data ellipses have the mean vector (x̄, ȳ) as their center. Projections of ellipsis on coordinate axes give the standard deviations of the variables (x̄ ± k·sₓ and ȳ ± k·sy, with k = 1, 1.5, 2.45), having bivariate coverage 40%, 68% and 95% and univariate coverage 68%, 87% and 98.6%, respectively. As Galton noted, the regression line can be visually estimated as the locus of the points of vertical tangents with the family of concentric ellipses.</p><h3>Conclusion</h3><p>Overall, if the data is approximately bivariate, then the conditional expectation can be obtained using the regression line. The idea behind the regression toward the mean is that, following an extreme random event, the next random event is likely to be less extreme. Galton found that children of short parents tended to be shorter than average, while children of tall parents tended to be taller than average, “however, the transmission of height across generations was imperfect.”</p><p>Although Galton uses the mid-parental height and did not pay attention to the gender of children, he wrote that “the height of daughters, takes after the height of the father more than it does after the of the mother”. Han, Ma, and Zhu challenged whether Galton’s classic model and its interpretation are proper. In their study, you can find the consideration of gender-specific models with different regression fits and drawbacks in Galton’s study. Also, you can find the <a href="http://www.biostat.mcgill.ca/hanley/galton/GaltonsHeightForecaster.zip">shiny app</a> which shows how to predict the child height having mid-parental height.</p><p>There are the different paper with criticism of Galton findings which refers to incorrectness of biological explanation for the regression phenomenon, the inappropriateness of Galton’s calculation of mid-parental height, the abstraction from the gender of the child, a fixed correlation of characteristics across generations. However, these mistaken assumptions gave us the notion and idea of regression and the conceptual difference between the correlation and regression.</p><h3>Source Code</h3><p>Source code for this article is available at <a href="https://zilfimian.github.io/Repository/PhD-Spring-2020-English-Lusine-Zilfimian.html">this GitHub page</a>.</p><h3>References</h3><blockquote>Friendly, Michael, Georges Monette, and John Fox. 2013. “Elliptical Insights: Understanding Statistical Methods Through Elliptical Geometry.” <em>Statistical Science</em> 28 (1): 1–39.</blockquote><blockquote>Galton, Francis. 1886. “Regression Towards Mediocrity in Hereditary Stature.” <em>The Journal of the Anthropological Institute of Great Britain and Ireland</em> 15: 245–63.</blockquote><blockquote>Han, Hao, Yeming Ma, and Wei Zhu. 2015. <em>Galton’s Family Heights Data Revisited</em>.</blockquote><blockquote>Hanley, James A. 2004. “’Transmuting’ Women into Men: Galton’s Family Data on Human Stature.” <em>The American Statistician</em> 58 (3): 237–43.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=104b04724917" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Outlier detection in Air Pollution data]]></title>
            <link>https://medium.com/datamotus/outlier-detection-in-air-pollution-data-d82ef71cc015?source=rss-7abbb2552abe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d82ef71cc015</guid>
            <category><![CDATA[outlier-detection]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[pollution]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Lusine Zilfimian]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 16:06:25 GMT</pubDate>
            <atom:updated>2023-05-30T14:54:32.064Z</atom:updated>
            <content:encoded><![CDATA[<h3>Outlier Detection in Air Pollution data</h3><p>The article was originally published on <a href="https://datamotus.com/2019/11/15/Outlier-Detection.html">https://datamotus.com/2019/11/15/Outlier-Detection.html</a></p><h4>Introduction and Data Description</h4><p>On a daily basis, economical, technological and political changes cause air pollution, which is currently one of the most pressing environmental issues around the globe. It is particularly acute in large cities with a rising level of industrialization and growing urbanization. The polluted air we breathe results in serious health disorders and decreases the quality of life. Before steps are taken to decrease the harmful effect of daily produced pollutants, certain measurements are required.</p><p>Government agencies use the <strong>air quality index</strong> to communicate with the public. An example of such communication is recommendations to reduce or avoid outdoor physical exertion when the air quality index (AQI) is too high. Different countries have their own air quality indices and they use their own method of calculation and health risk categories. Typically, outdoor air pollution can be defined as the emission of harmful substances into the atmosphere. This broad definition encapsulates a number of pollutants, including:</p><ul><li>sulphur dioxide (SO₂)</li><li>nitrogen oxides (NOₓ)</li><li>ozone (O₃)</li><li>particulate matter</li><li>carbon monoxide (CO)</li><li>carbon dioxide (CO₂)</li><li>volatile organic compounds (VOCₛ)</li></ul><p>We took the historical data of annual emissions of carbon dioxide per person, based on territorial emissions derived by <a href="https://ourworldindata.org/co2-and-other-greenhouse-gas-emissions">Our World in Data</a>. Per capita emissions (production-based) were calculated dividing the total national CO₂ emissions per year by population estimates. The summary of the dataset is presented below. The number of observations in the initial data is 42,844 and the range of variable time span is 1751–2017. For further analysis, the observations before 1970 that have a value of zero are omitted. The dataset used in this analysis can be found <a href="https://datamotus.com/2019-11-15-Outlier-Detection_files/co-emissions-per-capita.csv">here</a>.</p><pre># load the required libraries used in the article<br>if (!require(&quot;pacman&quot;)) install.packages(&quot;pacman&quot;)<br>pacman::p_load(ggplot2, dplyr, kableExtra, tsoutliers, forecast, TSA)<br>co &lt;- read.csv(&quot;co-emissions-per-capita.csv&quot;)<br>cond &lt;- which(co$Year &lt; 1970 &amp; co$Co2 == 0)<br>co &lt;- co[-cond,]</pre><p>We can look at the summary of the data.</p><pre>options(knitr.kable.NA = &#39;&#39;)<br>knitr::kable(summary(co), digits=2) %&gt;%<br>kable_styling(bootstrap_options = &quot;striped&quot;, full_width = F)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*vnr_RNvCjDJWCOGSRftW9A.png" /></figure><p>The variables <em>Entity</em> and <em>Code</em> show the country and/or area and its code, where the level of carbon dioxide was measured. The variables <em>Year</em> and Co₂ show the time span of variable Co₂ and the carbon dioxide measured in tones (CO₂ data has been converted from tones of carbon to tones of carbon dioxide (CO₂) using a conversion factor of 3.664).</p><p>We will now explore the pattern of CO₂ by looking at the data of 3 particular countries: Venezuela, the United Arab Emirates, and the Bahamas.</p><pre>co %&gt;% filter(Entity %in% c(“Venezuela”, “United Arab Emirates”, “Bahamas”)) %&gt;%<br>ggplot() + geom_line(aes(x = Year, y = Co2, color = Entity)) +<br> theme(legend.position=”None”) + facet_grid(.~Entity, scales = “fixed”) +<br> ggtitle(“The emissions of CO2 per capita”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*q4YKTTnu1ITOqJIS3AVBhg.png" /></figure><p>These countries were not selected randomly. If you look at the time series of these countries separately, the different types of outliers: <strong>additive</strong>, <strong>innovational</strong>, and <strong>level shift outliers</strong> can be found in the time series of CO₂ in Venezuela, the United Arab Emirates and the Bahamas correspondingly.<br>Outliers are usually the unexpected spikes or dips of observations at given points in time.</p><h3>Outliers and detection</h3><p>Time-series observations reveal frequent shifts in the data. The shifts in a time series that cannot be explained are referred to as <strong>outliers</strong>. One important reason to detect outliers is that they can represent an error. At the same time, these observations are inconsistent with the rest of the series and can dramatically influence the analysis, thus affecting the forecasting capacity of the time series model. So, to increase the prediction accuracy they must be removed before the analysis. Here are the most common types of outliers:</p><ul><li>Additive Outliers</li><li>Level Shifts</li><li>Transient Change</li><li>Innovation Outliers</li><li>Seasonal Level Shifts</li></ul><p>Three of the aforementioned outliers are to be considered below. There are different tools and methods to detect and deal with outliers (time series decomposition, generalized extreme student deviation, ARIMA, etc.). In order to detect the presence of outliers in the time series, we will use the <br>R function <strong><em>tso()</em></strong> , an interface to the automatic detection procedure provided in the package “<a href="https://cran.r-project.org/web/packages/tsoutliers/tsoutliers.pdf"><strong><em>tsoutliers</em></strong></a><strong><em>”</em></strong>. The R package “<strong><em>tsoutliers”</em></strong> implements the <strong>Chen and Liu</strong> procedure for the detection of outliers in time series. Different types of outliers (by default: <strong>AO</strong> additive outliers; <strong>LS</strong> level shifts, <strong>IO</strong> innovative outliers, etc.) can be selected in the function. The proposed procedure may be applied both to general seasonal and nonseasonal ARMA processes.</p><h4>Additive Outliers</h4><p>An <strong>additive outlier</strong> (AO) corresponds to an exogenous change of a <strong>single observation</strong> of the time series. Subsequent observations are unaffected by an additive outlier. Due to external causes, this type of outlier is usually associated with <strong>isolated</strong> incidents like measurement errors or impulse effects.</p><p>The graph indicates that the time series of the following countries can have an additive outlier/outliers:</p><ul><li>Brunei</li><li>Mauritania</li><li>Togo</li><li>The United Kingdom</li><li>Venezuela</li><li>Yemen</li></ul><pre>AO &lt;- co[co$Entity %in% c(&quot;Brunei&quot;, &quot;Mauritania&quot;, &quot;Togo&quot;, &quot;United Kingdom&quot;, &quot;Venezuela&quot;, &quot;Yemen&quot;), ]<br>ggplot(data = AO) + geom_line(aes(x = Year, y = Co2, color = Entity)) +<br>  theme(legend.position=&quot;None&quot;) + facet_wrap(~Entity, scales = &quot;free&quot;) +<br>  ggtitle(&quot;The emissions of CO2 per capita&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*6MCvBTMsLjSVI0lhGiKI-g.png" /></figure><p>We will now consider the time series of Venezuela and the United Kingdom. The plot above shows that the value of the year 1946 (17 tonnes of carbon dioxide) in Venezuela is not typical for the data. To check this assumption the <strong><em>tso</em></strong> function can be used.</p><pre>tsoutliers::tso(ts(AO[AO$Entity == “Venezuela”, “Co2”], <br> start = AO[AO$Entity == “Venezuela”, “Year”][1]), types = “AO”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*g-vQpHYwz_bCPeiFz2kpTg.png" /></figure><p>We will now study the value of CO₂ in Venezuela tested as an outlier (with the index of 34).</p><pre>AO[AO$Entity == “Venezuela”,][34,]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*hH_KQkCdx9clWjkzxfwpcg.png" /></figure><p>The procedure first detects outliers upon a chosen ARIMA model (which is an iterative process), then it chooses the ARIMA model including the outliers detected in the previous step and removes the outliers that are not significant in the new fit. The procedure is repeated until no outliers are detected or until a maximum number of iterations (by default, 4) is reached (Chen and Liu, 2013). <br>There is yet another <strong><em>TSA</em></strong> function that can be used to check the existence of additive outliers.</p><pre>detectAO(arima(ts(AO[AO$Entity == “Venezuela”, “Co2”]), <br> order = c(0, 0, 0)), alpha = 0.05, robust = TRUE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*NREKU150xERPXpPvq1wVhg.png" /></figure><p>The time series of Brunei also detects an outlier between the years of 1947 and 1949. These, however, are not the only types of outliers data can have. For example, the value of 1970 can be considered a level shift outlier. Different types of outliers can be simultaneously checked using the vector of possible types in the <strong><em>tso()</em></strong> function. Although, Chung and Liu (2013) state that, from a computational standpoint, the strategy of detecting outliers one by one may be the only feasible approach to dealing with multiple outliers, it seems more appropriate to estimate the outlier effects jointly rather than sequentially. Besides, a procedure based solely on iteratively adjusted residuals may often result in biased estimates for adjacent outliers.</p><pre>tsoutliers::tso(ts(AO[AO$Entity == “United Kingdom”, “Co2”], <br> start = AO[AO$Entity == “United Kingdom”, “Year”][1]), types = c(“AO”,”LS”, “IO”)) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*LuvDAJU7tKUXjtDJO2NW0g.png" /></figure><pre>AO[AO$Entity == &quot;United Kingdom&quot;, ][c(94,122,127),]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*tUp8YBOF0mNbm710f7pQeQ.png" /></figure><p>As assumed, the levels of CO₂ in the year of 1893 and 1926 are treated as outliers. In addition, the algorithm found an innovational outlier (see details about this type of outlier below) in the year 1921.</p><p>In forecasting models, removing outliers may be highly dangerous. If the forecasting models are sensitive to outliers, we need to replace them, because outliers will skew the coefficients. To deal with additive outliers, the <em>tsoutliers()</em> function from the package “<strong><em>forecast”</em></strong>, designed to identify and to suggest potential replacement values, can be used. In our data of the United Kingdom there are three outliers and, correspondingly, three replacements:</p><pre>tsoutliers(ts(AO[AO$Entity == “United Kingdom”, “Co2”],<br> start = AO[AO$Entity == “United Kingdom”, “Year”][1]))<br>replUnKing &lt;- ts(AO[AO$Entity == “United Kingdom”, “Co2”], <br> start = AO[AO$Entity == “United Kingdom”, “Year”][1])<br>replUnKing[c(94, 122, 127)] &lt;- c(10.12905, 10.18127, 10.10963)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*dpAm_zZBkM9okvJvvkw_EA.png" /></figure><p>An alternative useful function identifying and replacing outliers is <em>tsclean()</em> from the same package. In this case, linear interpolation is used to estimate missing values and to replace outliers.</p><pre>replUnKing &lt;- tsclean(ts(AO[AO$Entity == “United Kingdom”, “Co2”], <br> start = AO[AO$Entity == “United Kingdom”, “Year”][1]))<br>out &lt;- data.frame(<br>  UK = ts(AO[AO$Entity == &quot;United Kingdom&quot;, &quot;Co2&quot;], <br>    start = AO[AO$Entity == &quot;United Kingdom&quot;, &quot;Year&quot;][1]),<br>  replUnKing, Year = AO[AO$Entity == &quot;United Kingdom&quot;, &quot;Year&quot;])</pre><pre>ggplot(data = out) + <br>  geom_line(aes(x = Year, y = UK, color=&quot;#FC4E07&quot;), size =1.1, alpha = 0.5) +<br>  geom_line(aes(x = Year, y = replUnKing, color=&quot;#E7B800&quot;)) +<br>  scale_color_discrete(name = &quot; &quot;, labels = c(&quot;Replaced&quot;, &quot;UK CO2&quot;))+ <br>  labs(y = &quot;CO2&quot;, title = &quot;Replacing the outliers&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*5-TitJoPWM3I8hlE8xz8SA.png" /></figure><h4>Innovational Outliers</h4><p><strong>Innovational outlier</strong> or Intervention Outlier (IO) corresponds to an endogenous change of a single innovation of the time series and is usually associated with isolated incidents such as an impulse. The influence of the outliers may increase over time. It represents a shock. <br> <br>The following countries are selected to visually study the case of having innovational outlier/outliers:</p><ul><li>Cape Verde</li><li>Iran</li><li>Germany</li><li>Armenia</li><li>The United Arab Emirates</li><li>Mauritania</li></ul><pre>IO &lt;- co[co$Entity %in% c(“Cape Verde”, “Iran”, “Germany”, “Armenia”, <br> “United Arab Emirates”, “Mauritania”), ]</pre><pre>ggplot(data = IO) + <br> geom_line(aes(x = Year, y = Co2, color = Entity)) +<br> theme(legend.position=”None”) +<br> facet_wrap(~Entity,scales = “free”) +<br> ggtitle(“The emissions of CO2 per capita”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*mYr9aOK_M0olilZcYycH2w.png" /></figure><p>The time series for the United Arab Emirates shows innovational outliers in 1969 and 1998, which are to be tested:</p><pre>tsoutliers::tso(ts(IO[IO$Entity == “United Arab Emirates”,”Co2&quot;], <br> start = IO[IO$Entity == “United Arab Emirates”, “Year”][1]),types = c(“LS”,”IO”))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*LbQmb_RpLNr6LzbYpmvhGQ.png" /></figure><pre>IO[IO$Entity == &quot;United Arab Emirates&quot;,][c(11,40),]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*QxUEyvwQ3OpRDdYk8M7IVA.png" /></figure><p>The algorithm detected a level shift outlier in the year 1984 (see details below).</p><p>Armenia’s level of CO₂ has an innovational outlier in 1993. It can also be seen through the function <em>detectIO()</em> and can be visually studied in the graph above.</p><pre>tsoutliers::tso(ts(IO[IO$Entity == “Armenia”, “Co2”],<br> start = IO[IO$Entity == “Armenia”, “Year”][1]),types = c(“IO”, “AO”))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*O9IhzpuRsSgxivGNHkCgiQ.png" /></figure><p>The number 35 is tagged as an innovative outlier.</p><pre>IO[IO$Entity == “Armenia”,][35,]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*1FiqgQ0P--j5IHGE1PsgfQ.png" /></figure><p>Detect innovative outlier with <em>detectIO()</em>.</p><pre>detectIO(arima(ts(IO[IO$Entity == “Armenia”, “Co2”]), <br> order = c(0, 1, 0)), alpha = 0.05, robust = TRUE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*OmRD5qN6omCW1UTQys3LLQ.png" /></figure><h4>Level Shift Outliers</h4><p><strong>Level Shift outlier </strong>(LS) represents an abrupt change in the mean level and may or may not be seasonal (Seasonal Level Shift). LS is a change in the mean level of the time series starting at some point and continuing until the end of the observed period. In contrast to additive outliers, a level shift outlier affects <strong>many observations</strong> and has a <strong>permanent</strong> effect. It can be modeled in terms of a step function with the magnitude equal to the omega parameter.</p><p>The countries below are selected to visually study the case of having level shift outlier/outliers:</p><ul><li>Iceland</li><li>North Korea</li><li>Yemen</li><li>Bahamas</li><li>Lithuania</li></ul><pre>LS &lt;- co[co$Entity %in% c(“Iceland”, “North Korea”, “Yemen”, “Bahamas”, “Lithuania”), ]</pre><pre>ggplot(data = LS) + geom_line(aes(x = Year, y = Co2, color = Entity)) +<br> theme(legend.position=”None”) + facet_wrap(~Entity,scales = “free”) +<br> ggtitle(“The emissions of CO2 per capita”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*7CjqVyTQDo2YtwOfIk8v1g.png" /></figure><p>A similar analysis for the level shift outlier was conducted for the time series of Iceland and Bahamas. The results are presented below:</p><pre>tsoutliers::tso(ts(LS[LS$Entity == “Iceland”, “Co2”], <br> start = LS[LS$Entity == “Iceland”, “Year”][1]), types = c(“LS”, “AO”))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*cWUfvDl0LUeDCSNd0S6zLw.png" /></figure><p>As can be seen from the output above, case number 12 is tagged as an outlier.</p><pre>LS[LS$Entity == “Iceland”,][12,]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*u8YLLbeNlaG_i2mLPSo29w.png" /></figure><p>And for the Bahamas:</p><pre>tsoutliers::tso(ts(LS[LS$Entity == “Bahamas”, “Co2”], <br> start = LS[LS$Entity == “Bahamas”, “Year”][1]),types = “LS”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*GOeI7SgHip_6qiLP5LU5Fg.png" /></figure><pre>LS[LS$Entity == &quot;Bahamas&quot;,][c(22,32),]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*Zu7rNCeJuOEmDhLTEKYM3Q.png" /></figure><p>A dummy variable can be used to account for level shift outliers and innovative outliers in the data. Rather than omitting the outlier, a dummy variable removes its effect. In the case of one outlier, the dummy variable takes value 1 for the observations before the outliers occur and 0 for other observations. For two and more outliers coding with several dummy variables can be implemented.</p><h3>Conclusions</h3><p>In the article, we considered three types of outliers (AO, IO, and LS) in time series modeling. Here is the summary of these types of outliers:</p><ul><li>An Additive Outlier (AO) represents an isolated spike.</li><li>A Level Shift outlier (LS) represents an abrupt change in the mean level.</li><li>An Innovational Outlier (IO) represents a shock.</li></ul><p>To illustrate, we described the time series of annual emissions of carbon dioxide per person to detect these outliers. The iterative procedure of finding an outlier from the package “<strong><em>tsoutliers</em></strong>” was used. The next step in outlier analysis should be their adjustment.</p><h3>Reference list</h3><blockquote>Chen, C. and Liu, L. (2013) ‘Joint Estimation of Model Parameters and Outlier Effects in Time Series’, 88(421), pp. 284–297.</blockquote><blockquote>Ahmar, A. et al. (2018) ‘Modeling Data Containing Outliers using ARIMA Additive Outlier (ARIMA-AO)’, Journal of Physics Conference Series, 954. doi: 10.1088/1742–6596/954/1/012010.</blockquote><blockquote>Ruey S. Tsay (1988) ‘Outliers, level shifts, and variance changes in time series’, Journal of Forecasting, 7, pp. 1–20.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d82ef71cc015" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamotus/outlier-detection-in-air-pollution-data-d82ef71cc015">Outlier detection in Air Pollution data</a> was originally published in <a href="https://medium.com/datamotus">Datamotus</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the problem of heteroscedasticity through weighted regression]]></title>
            <link>https://medium.com/datamotus/solving-the-problem-of-heteroscedasticity-through-weighted-regression-e4a22f1afa6b?source=rss-7abbb2552abe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a22f1afa6b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Lusine Zilfimian]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 16:05:26 GMT</pubDate>
            <atom:updated>2020-02-16T16:05:26.991Z</atom:updated>
            <content:encoded><![CDATA[<p>The article was originally published on <a href="https://datamotus.com/2019/10/30/Weighted-Least-Squares.html">https://datamotus.com/2019/11/15/Outlier-Detection.html</a></p><h3>Introduction</h3><p>Nowadays, having a business implies awning a website. The primary aim of a website is to provide information, which is crucial in the modern business world. Suppose a website owner aims at increasing the number of visitors in order to have more views, sales or popularity. To achieve this goal, one first needs to understand the factors affecting web traffic. The vast majority of small businesses try to increase website hits or visits via advertisements.</p><p>We took a look at small business website statistics and saw how important advertising is. Let us review the artificially generated <a href="https://datamotus.com/2019-10-30-Weighted-Least-Squares_files/website.csv">data</a>. The summary of the dataset is presented below.</p><pre>web &lt;- as.data.frame(read.csv(“website.csv”))<br>options(knitr.kable.NA = ‘’)<br>kable(summary(web), digits=2)%&gt;%<br> kable_styling(bootstrap_options = “striped”, <br> full_width = F)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*dDTgLYmGt8AyQd5Djd2U-g.png" /></figure><p>The data consists of 4 variables and 1000 observations without any missing values. The variable Company shows the unique number of the company whose website is being examined, the variable Visits is the number of website visits per week. The variables AdType and Budget show the <strong>main type</strong> of advertising done by the company and the average monthly amount spent on this advertisement, respectively. There are 5 types of advertisements in the data: Radio and Podcasts, Direct Mail, Video Ads, Social Media Ads, and Outdoor Ads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IECCG-7TQqwnI3_-4U4SQ.png" /></figure><p>The left graph indicates that there is a positive correlation between the money spent on advertisements and the number of website visits. The coloring of the plot has been done based on the variable AdType.The result shows that there is no interaction effect of two explanatory variables on the popularity of the website. In general, website owners spend an approximately equal amount of money on different types of advertisements. Roughly there is no multicollinearity between explanatory variables. Based on the second graph, as the medians and spread of data are approximately the same, we can claim that the way one chooses to increase the visibility of a website plays no significant role.</p><p>To understand the effect of advertising let us consider the following multiple linear regression model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*_TmImXSUQKpF2xZkvWZ10A.png" /></figure><p>The result of fitted linear regression is presented in the output below:</p><pre>model &lt;- lm(Visits ~ Budget + AdType, data = web)<br>stargazer::stargazer(model,<br> title = “Results”,<br> dep.var.labels = c(“Visits”),<br> out=”models.htm”, type = “text”, header=FALSE, <br> covariate.labels = c(“Budget”, “Outdoor Ads”,<br> “Radio and Podcasts”,”Social Media Ads”, “Video Ads”))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*4jHZHrqpTVGw8wHOg0h60Q.png" /></figure><p>It is not surprising that the coefficients for the unique levels of the variable AdType are not significant, because there is no effect on the response variable Visits. However, the coefficient for the variable Budget is statistically significant and positive (see the graph). So, the multiple regression analysis shows that with the increase in the amount of money spent on advertising by $100 the number of visitors will increase by, on average, 102. Thus, the number of visitors can be predicted based on the ad budget. <br> <br> And yet, this is not a reliable result, since an important factor has been omitted. We will now discuss briefly the concepts of heteroscedasticity, the causes and effects of nonconstant variance and the ways of solving this problem.</p><h3>The problem</h3><h4>Nonconstant variance</h4><p>One of the Gauss–Markov conditions states that the variance of the disturbance term in each observation should be constant. This assumption, however, is clearly violated in most of the models resulting in heteroscedasticity. Mathematically, homoscedasticity and heteroscedasticity may be defined as:</p><ul><li><strong>Homoscedasticity: </strong>the variance of the error term is the same for all observations</li><li><strong>Heteroscedasticity: </strong>the variance of the error term is not the same for all observations.</li></ul><p>See the visual demonstration of homoscedasticity and heteroscedasticity below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Y3lKA4Bqak0fpHUcHQv0A.png" /><figcaption><a href="https://towardsdatascience.com/the-concept-of-heteroscedasticity-c5652b746223">https://towardsdatascience.com/the-concept-of-heteroscedasticity-c5652b746223</a></figcaption></figure><p>The left picture illustrates homoscedasticity. Let us start with the first observation, where X has a value of X₁. If there was no disturbance term in the model, the observation would be represented by the circle lied on the regression line. The effect of the disturbance term is to shift the observation upwards or downwards vertically (downwards in case of X₁). The potential distribution of the disturbance term, before the observation was generated, is shown by the normal distribution.</p><p>Although homoscedasticity is often taken for granted in regression analysis, it is common to suppose that the distribution of the disturbance term is different for different observations in the sample. Suppose the variance of the distribution of the disturbance term rises as X increases (right picture). This does not mean that the disturbance term will necessarily have a particularly large (positive or negative) value in an observation where X is large, but it does mean that the a priori probability of having an erratic value will be relatively high.</p><p>The first graph of the relationship between the budget and visitors illustrates a typical scatter diagram of heteroscedastic data — there is a tendency for their dispersion to rise as X increases. It means that even though there is a positive relationship between the variables, starting at a particular point a large amount of money fails to imply a large number of visitors. In other words, one can spend huge sums without the guarantee of large traffic.</p><blockquote>Reasons and consequences</blockquote><p>Heteroscedasticity is more likely to occur, for example, when</p><ul><li>The values of the variables in the sample vary substantially in different observations.</li><li>The explanatory variable increases, the response tends to diverge. For example, families with low incomes will spend relatively little on luxury goods, and the variations in expenditures across such families will be small. But for families with large incomes, the amount of discretionary income will be higher.</li><li>The model is misspecified (using response instead of the log of response or instead of X² using X etc). Important variables may be omitted from the model.</li></ul><p>Why does heteroscedasticity matter? As a matter of fact, the evidence for the absence of bias in the OLS regression coefficients did not use this condition. So we can be sure that the coefficients are still unbiased.</p><p>Nevertheless, two concerns are raised:</p><p>1) <em>The variances of the regression coefficients</em>: if there is no heteroscedasticity, the OLS regression coefficients have the lowest variances of all the unbiased estimators that are linear functions of the observations of Y. If heteroscedasticity is present, the OLS estimators are inefficient because it is possible to find other estimators that have smaller variances and are still unbiased.</p><p>2) <em>The estimators of the standard errors of the regression coefficients</em> will be wrong and, as a consequence, the t-tests, as well as the usual F tests, will be invalid. It is quite likely that the standard errors will be underestimated, so the t statistics will be overestimated and you will have a misleading impression of the precision of your regression coefficients. You may be led to believe that a coefficient is significantly different from 0, at a given significance level, when, in fact, it is not.</p><h4>How to detect?</h4><p>There are a lot of statistical tests called to test whether heteroscedasticity is present. The list includes but is not limited to the following:</p><ul><li>The Spearman Rank Correlation Test</li><li>The Goldfeld–Quandt Test</li><li>The Glejser Test</li><li>The Breusch-Pagan test</li><li>The White test</li></ul><p>Despite a large number of the available tests, we will opt for a simple technique to detect heteroscedasticity, which is looking at the residual plot of our model. We can diagnose the heteroscedasticity by plotting the residual against the predicted response variable.</p><pre>library(ggResidpanel)<br>resid_auxpanel(residuals = resid(model), <br> predicted = fitted(model), <br> plots = c(“resid”, “index”))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*N4X93ppGLQ2PPx9Ru6RDqg.png" /></figure><p>In our case, we can conclude that as budget increases, the website visits tend to diverge.</p><h3>The solution</h3><p>The two most common strategies for dealing with the possibility of<br>heteroskedasticity is heteroskedasticity-consistent standard errors (or <a href="http://afhayes.com/public/BRM2007.pdf">robust errors</a>) developed by White and <strong>Weighted Least Squares</strong>.</p><h4>WOLS</h4><p>OLS does not discriminate between the quality of the observations, giving equal weight to each, irrespective of whether they are good or poor guides to the location of the line. Thus, it may be concluded that if we can find a way of assigning more weight to high-quality observations and less to the unreliable ones, we are likely to obtain a better fit. In other words, our estimators for coefficients will be more efficient. WOLS works by incorporating extra nonnegative constants (weights) associated with each data point into the fitting criterion. We shall see how to do this below. Suppose the true relationship is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*eq8gc0J8Eg-t48VY58D1BA.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*w2cmKCMmQnjUre5u6vgBJQ.png" /></figure><p>So we have a heteroscedastic model. We could eliminate the heteroscedasticity by dividing each observation by its variance of the error term. The model becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*3Z5IU9cmLqfNxA629Eq6dQ.png" /></figure><p>The disturbance term will be homoscedastic because</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*GBQFbpYQRryuNfwxcm88pA.png" /></figure><p>Therefore, every observation will have a disturbance term drawn from a distribution with population variance 1, and the model will be homoscedastic. By rewriting the model, we will have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*ImP45Giy5MNTOwI4jkUfGw.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*fcyN6lddj4za7_MnmMcT2g.png" /></figure><p><strong>Note</strong> that there should not be a constant term in the equation. By regressing Y’ on h and X’, we will obtain efficient estimates of coefficients with unbiased standard errors. The general solution to this is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*8QWxLlXgFnhugQg692ECgQ.png" /></figure><p>where W is the diagonal matrix with diagonal entries equal to weights and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*ZWk3R5JZ5dbD4su7nZkFQg.png" /></figure><p>In some cases, the values of the weights may be based on theory or prior research. In our model, the standard deviations tend to increase as the value of Budget increases, so the weights tend to decrease as the value of Budget increases, thus the weights are known. Where the weights are unknown, we can try different models and choose the best one based on, for instance, the distribution of the error term. There are the following common types of situations and weights:</p><ul><li>When the variance is proportional to some predictor xᵢ, then</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*1XLbUH1-sm6AE4eRnIfpVg.png" /></figure><p>thus we setwᵢ=1/xᵢ</p><ul><li>When the iᵗʰ value of y is an average of nᵢ observations</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*QNN1WvJmDiyrwwYqlR1_Pg.png" /></figure><p>thus we set wᵢ=nᵢ (this situation often occurs in cluster surveys)</p><ul><li>When the iᵗʰ value of y is a total ofnᵢ observations</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*bQxEFDlU3ZGQO3kxHpDcmQ.png" /></figure><p>thus we set wᵢ=1/nᵢ.</p><p>If the structure of weights is unknown, we have to perform a two-stage estimation procedure. We need to estimate an ordinary least squares regression to obtain the estimate of the variance of error for iᵗʰ squared residual and the absolute value of standard deviation (in case of outliers). Thus, we can have different weights depending on the variance of error. Often the weights are determined by fitted values rather than the independent variable. Let us show these different models via statistical package R. Fortunately, the R function lm(), which is used to perform the ordinary least squares, provides the argument weights to perform WOLS. By default the value of weights in lm() is NULL, weighted least squares are used with weights weights, minimizing the sum of we².</p><p>Suppose we do not know the pattern of weights, and we want to fit the models with the following weights</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*vxzcIw89D_mHnzKw38Mzxg.png" /></figure><pre>wols1 &lt;- lm(Visits ~ Budget + AdType, data = web, weights = 1/Budget)<br>wols2 &lt;- lm(Visits ~ Budget + AdType, data = web, weights = 1/Budget²)<br>wols3 &lt;- lm(Visits ~ Budget + AdType, data = web, weights = 1/fitted(model))<br>wols4 &lt;- lm(Visits ~ Budget + AdType, data = web, weights = 1/fitted(model)²)<br>wols5 &lt;- lm(Visits ~ Budget + AdType, data = web, weights = 1/resid(model)²)<br>wols6 &lt;- lm(Visits ~ Budget + AdType, data = web, weights = 1/abs(resid(model)))</pre><p>The result of the fitted models will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*te8mFMtbPc-j8GGGqjBKWA.png" /></figure><p>Weighted least squares estimates of the coefficients will usually be nearly the same as the “ordinary” unweighted estimates. In the models with explanatory variables such as weight weights = 1/Budget² produces the smallest standard errors. The summary of models shows that the fitted equations are highly similar yet again. Overall, the smallest standard errors are presented by the model with weights = 1/resid(model)².</p><blockquote>The inverse of x and residuals with weights</blockquote><p>However, as we know the pattern of weight allows to examine the residual plots for the first two weighted OLS models.</p><pre>resid_compare(models = list(wols1, wols2),<br> plots = c(“resid”, “index”),<br> title.opt = FALSE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TVuBwxZO1JiH0w49J61h2g.png" /></figure><p>Apparently, the nonconstant variance of the residuals still results in heteroscedasticity. The issue is that the plots above use unweighted residuals; whereas, with weighted least squares, we need to use weighted residuals to evaluate the suitability of the model since these take into account the weights which change variance. The usual residuals fail to do this and will maintain the same non-constant variance pattern irrelevant to the weights used in the analysis.</p><pre># Weighted residuals by corresponding weight<br>resid_auxpanel(residuals = sqrt(1/web$Budget)*resid(wols1), <br> predicted = fitted(wols1), <br> plots = c(“resid”, “index”))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7f0uu1HFsgvfGK2uXI8aTA.png" /></figure><pre>resid_auxpanel(residuals = sqrt(1/web$Budget²)*resid(wols2), <br> predicted = fitted(wols2), <br> plots = c(“resid”, “index”))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0d90KrBXs_rwtas76jOF9A.png" /></figure><p>The second WOLS model is chosen because the variability of residuals is the same for all predicted values. We can now be more confident in results and state that with every $100 increase in the amount of money spent on advertising the number of website visitors will rise by, on average, 102. The absence of heteroscedasticity and the fact that the standard deviation of the coefficient is less than in the original model allow making predictions with a higher level of certainty.</p><h3>Conclusion</h3><p>Overall, the weighted ordinary least squares is a popular method of solving the problem of heteroscedasticity in regression models, which is the application of the more general concept of <strong>generalized least squares</strong>. WOLS implementation in R is quite simple because it has a distinct argument for weights. As we saw, weights can be estimated directly from sample variances of the response variable at each combination of predictor variables. WOLS can sometimes be used where different observations have been measured by various instruments, importance or accuracy, and where weights are used to take these circumstances into account.</p><p>The disadvantage of weighted least squares is that the theory behind this method is based on the assumption that exact weight sizes are known. However, when it comes to practice, it can be quite difficult to determine weights or estimates of error variances. Note that WOLS is neither the only nor the best method of addressing the issue of heteroscedasticity. The alternative methods include estimating heteroskedasticity-consistent standard errors, and other types of WOLS (e.g. iteratively reweighted least squares).</p><h3>Reference List</h3><blockquote>Oscar L. Olvera, Bruno D. Zumb, Heteroskedasticity in Multiple Regression Analysis: What it is, How to Detect it and How to Solve it with Applications in R and SPSS.</blockquote><blockquote>R. Williams, “<a href="https://www3.nd.edu/~rwilliam/stats2/l25.pdf">Heteroskedasticity</a>”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a22f1afa6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamotus/solving-the-problem-of-heteroscedasticity-through-weighted-regression-e4a22f1afa6b">Solving the problem of heteroscedasticity through weighted regression</a> was originally published in <a href="https://medium.com/datamotus">Datamotus</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pseudorandomization: Propensity score matching]]></title>
            <link>https://medium.com/datamotus/pseudorandomization-propensity-score-matching-c6119ad79bbc?source=rss-7abbb2552abe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6119ad79bbc</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Lusine Zilfimian]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 11:01:31 GMT</pubDate>
            <atom:updated>2019-12-12T11:01:31.902Z</atom:updated>
            <content:encoded><![CDATA[<p>The article was originally published on <a href="https://datamotus.com/2019/10/15/Propensity-Score-Matching.html">https://datamotus.com/2019/10/15/Propensity-Score-Matching.html</a></p><h3>Introduction</h3><p>The research question is whether playing chess is correlated with the improvement in logical thinking. Previous research, conducted in a number of countries, indicates that playing a game of chess increases concentration, logical and critical thinking, as well as the ability to plan and analyse.</p><p>Should one aim at increasing the level of logical thinking among university students and schoolchildren by playing chess, the following steps are to be taken. Once the population, sampling method, sample size and other crucial elements of research are defined, the sample should be taught how to play a game of chess. This may be reached by including a relevant curriculum in the syllabus. The second step to take would be to conduct pre- and post-tests to measure the performance before and after a six-month course. Finally, the analyses of the data would indicate whether the experiment had a significant effect and whether the project is worth replicating.</p><p>Assuming all the mentioned steps were adhered to and the evaluation of the effectiveness of the program for university and school students has been launched, let us review the artificially generated <a href="https://datamotus.com/2019-10-15-Propensity-Score-Matching_files/Chess.csv">data</a>. The summary of the dataset is presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*W0DOipdkFjcxyPBLMFD17Q.png" /></figure><p>We have 7 variables and 921 observations without any missing values. The variable ‘<em>Treatment.Type’ </em>shows the group (Control or Treatment) to which students were randomly assigned. The variables <em>‘Pre’</em> and <em>‘Post’</em> show the number of correct answers out of 40 logical questions. The last 4 variables are the characteristics of the students: the gender, age, math grade of a student for the last semester, and overall grade by the end of the semester.</p><p>The group, used for baseline measures, is called the Control group, and the group that receives an experimental procedure is <a href="https://www.statisticshowto.datasciencecentral.com/experimental-group/">Treatment</a>. To estimate the effect of teaching how to play chess (<em>”treatment effect”</em>) we can use the linear regression that compares the change in averages of students’ logical scores (outcome variable) between Pre and Post surveys across the control and treatment groups (dummy independent variables). This regression is known as the difference in difference <a href="https://en.wikipedia.org/wiki/Difference_in_differences">(DiD)</a> analysis. Before the treatment of DiD regression is addressed let us observe the visual display of the treatment effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*jOznv1sNLuRtySjwubXzig.png" /></figure><p>It is clear that unlike the pre-test results <em>after</em> the teaching program students from the treatment group tend to answer most of the questions correctly. In the absence of the treatment, the true effect of time shows that there is no noticeable difference between the number of correct answers at Pre- and Post-test.</p><h4>DiD</h4><p>The result of linear regression is in the output below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*XTUQF-ceBr3NSZNSmSvpWA.png" /></figure><p>The coefficient of <em>‘Group * Time (Treatment * Post)’</em> itself is the difference in differences estimator which tells us whether the expected mean changes in the outcome from pre to post are different in the two groups. At post-test, the students in the treatment group had on average 12.6 correct answers more than those from the control group. Regression analysis shows that the effect of treatment is high and significant.</p><p>Is this a reliable result or are there any other factors that have not been considered? Provided that this is an introduction to a lengthy article (see the scrollbar), the more probable answer is “yes, we have omitted something”. Let us discuss briefly the concepts of <a href="https://en.wikipedia.org/wiki/Confounding">confounding</a> variable or confounding factor and the ways in which it can be eliminated.</p><h3>The problem</h3><h4>Confounding bias and Randomization test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*SmNoQhB-s0p0dmChnjXZAA.png" /></figure><p>The association treated by the regression analysis above can be spurious because there may be other factors affecting both the independent variable (treatment) and the dependent variable (correct answers). Let us consider the illustration above: <em>‘Z’</em> is a confounding factor, we have not accounted for, which influences both dependent (<em>‘Y’</em>) and independent variables (<em>‘X’</em>), creating the correlation between the last two variables. In this case, any baseline personal characteristic, unevenly distributed to the groups, can be the cause of bias.</p><p><strong>Local conclusion:</strong> As we are interested in estimating the effectiveness of the teaching program for students and pupils, we need to be sure that groups are assigned randomly to avoid bias. Before starting the analysis, we should measure the level of imbalance between the treatment and control groups and, should the personal differences be statistically significant, control for them. <br> <br>In order to check the existence of confounding effect, the balance diagnostics should be performed on all possible confounding variables. We can use the Chi-squared test of independence for categorical variables (gender and overall grade), and ANOVA for numeric variable <em>‘Math.grade’</em> and <em>‘age’</em>.</p><h4>Chi-squared test result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*jexvZXlcSgf-0RI6JTL1VQ.png" /></figure><h4>ANOVA results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*VNFQBrVa3jQm6gihzY8aaA.png" /></figure><p>For variables with p &gt; .05 , we do not reject the null hypothesis of independence of variables. We can conclude that the groups are independent from the gender at .05 significance level. However, the statistics for the remaining variables show that students in different groups (treatment and control) have different personal characteristics. To avoid being overly technical, we can describe the problem of randomization through the graphs below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*RX9dR5QkI0RSPup3Fozkfg.png" /></figure><p>The graphs illustrate that the distribution of students by gender in both groups is similar, however, the median value of math grade of students in the treatment group is noticeably higher and they had obtained higher math grades the previous semester.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*Lp_z5-3wA4Wa6Rbjn-V8vQ.png" /></figure><p>The students/pupils in the control group are older and their overall grades are lower in comparison with the students in the treatment group. The problem is in the sectional bias, so we need to adjust it. In the observational studies, treatment selection is often influenced by subject characteristics. Suppose, we did the regression above and inferred that the treatment effect of teaching how to play the game of chess is valid. However, there is a possibility that the effect is significant and positive not as a result of efficient seminars, but because apriori the treatment group “contains” students with “better” characteristics: the ability to learn “faster”, or which are quite favoured to know/learn more. Thus, this is not the pure effect of seminars, because baseline characteristics of students differ systematically from those of untreated students. What should be done? The answer is to <em>randomize</em> the existing data.</p><h3>The solution</h3><h4>Propensity scores</h4><p>There are different ways of performing randomization. In this case, we will discuss the method called Propensity Score Matching (PSM), normally used in pharmacoepidemiologic researches containing large healthcare databases. <br>We need to calculate some scores (propensity score) and classify students according to these scores. In a <em>randomized study,</em> the propensity score is known: if the treatment was assigned randomly, then the propensity score for each subject is 0.5. However, in <em>observational (or nonrandomized) studies</em>, we need to estimate the fitted values for scores. The question is why do we need to estimate the probability that a subject receives a certain treatment since we already have these groups? The answer is that to have the pure effect of treatment we want to do randomization artificially, and the propensity score is not known. After obtaining this score we will find two subjects: one in the treated group and one in the control, with the <em>same or similar</em> propensity scores. Then we can imagine that these two subjects were “randomly” assigned to each group in the sense of being equally likely to be treated or to be in the control group.</p><p>The propensity score is the estimated conditional probability (propensity) of receiving treatment based on the covariates included in the propensity score model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*uiTMsiiIycc0zN0zeVO6kQ.png" /></figure><p>where <em>‘PS’</em> is propensity score, X is the binary variable with 0 value, if the student is in the control group and, <em>X = 1</em>, then a student is in the treatment group, and <em>‘Z’</em> is covariates (student characteristics).</p><p>The propensity score is most often estimated using a logistic regression model, where treatment status is regressed on a common set of explanatory variables (gender, age, math grade, the overall grade of a student), such as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*0-cYdiP0SrHEior9cv2Bkg.png" /></figure><p>The propensity score plays an important role in balancing the study groups to make the treated and untreated groups comparable. The authors of this method, <a href="https://www.stat.cmu.edu/~ryantibs/journalclub/rosenbaum_1983.pdf">Rosenbaum and Rubin</a>, showed that treated and untreated subjects with the same propensity scores have identical distributions for all background covariates, which is quite intuitive. Exact adjustments using the propensity score will, on average, remove the bias in the baseline variables. We can divide the sample into subgroups, for example, quintiles, based on the propensity scores. As Rosenbaum states, in matching we find a subset of untreated individuals whose propensity scores are similar to those of the treated persons, or vice-versa. The <em>goal</em> of matching is to create a dataset that looks closer to the one that would result from a possibly randomized experiment. Note that in matching we use the propensity scores rather than all covariates individually, so we have a chance to control for many confounding factors simultaneously by matching on a single scalar variable.</p><h4>Matching</h4><p>The propensity score can be used to reduce confounding via <strong>matching</strong>, stratification, regression adjustment, or any combination of these strategies. Let us now consider the matching. Matching is a common technique used to select students for the control group who are matched with the students from the treated group on background covariates. So, after the estimating score individuals with similar estimated propensity scores will be chosen and they will have, on average, similar chances of receiving the treatment. Note that even if the propensity score is similar, they may have different patterns of covariates at an individual level. To that end, we need the <strong>distribution of covariates</strong> to be <strong>similar</strong> within the matched treated and control groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*hnTOyQ4MOhTc7Vvd9dlX-g.png" /><figcaption>For more details see Schneeweiss S. A basic study design for expedited safety signal evaluation based on electronic healthcare data. <a href="https://www.ncbi.nlm.nih.gov/pubmed/20681003">https://www.ncbi.nlm.nih.gov/pubmed/20681003</a></figcaption></figure><p>On the left extreme end of the distributions are the students and pupils from the control group with a low probability of being included in the treatment group. On the right extreme one we can notice the students from the treatment group with a very high probability of being treated. Conversely, the overlapping area will identify students/pupils who have comparable propensity scores among treated and control students and are therefore better candidates for inclusion in a comparative analysis. After the matching, the distribution of observed baseline covariates that were considered in the propensity score model must be similar.</p><p>The most common implementation of propensity score matching is <em>one-to-one</em> or pair matching, in which pairs of treated and untreated subjects are formed in a way that matched subjects have similar values of the propensity score. Although one-to-one matching appears to be the most common approach to propensity score matching, other approaches can also be used. The next common method for matching is the <em>nearest neighbor</em> matching. Nearest neighbor matching selects for matching to a given treated subject that untreated subject whose propensity score is closest to that of the treated subject. If multiple untreated subjects have propensity scores that are equally close to that of the treated subject, one of these untreated subjects is selected randomly (Patorno, Grotta et al.). Rassen et al. have shown that a variation of the nearest-neighbor matching algorithm, the pairwise nearest-neighbor matching algorithm, is computationally fast and provides better balance among the treatment groups. That is why we use this method in our calculations. Let us now return to our case study. Before taking any randomization steps we have the following proportion of groups:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*63oJfEJtYhs2b0oHmRoSyQ.png" /></figure><p>To show the result of propensity score matching, we will use the R programming language. In R, Ho et al. developed the package MatchIt (<a href="http://cran.r-project.org/package=MatchIt">available from the Comprehensive R Archive Network</a>), which implements different types of matching algorithms and provides various tools to assess the balance of data. <a href="https://imai.fas.harvard.edu/research/files/matchit.pdf">From the R journal</a>: MatchIt is designed for causal inference with a dichotomous treatment variable and a set of pretreatment control variables. Any number or type of dependent variables can be used. MatchIt is usually used for observational studies where the treatment variable is not randomly assigned by the investigator, or the random assignment goes wrong. The main command<em> matchit()</em> implements the matching procedures. Here is the simple case for balancing the data.</p><pre>ChessWide &lt;- read.csv(&quot;chess.csv&quot;)<br># Use install.packages(&quot;MatchIt&quot;) to install the package, call it by the function library().<br>library(MatchIt)<br># Changing the labels of target variable for matchit() function.<br>ChessWide$Treatment.Type = ifelse(ChessWide$Treatment.Type == &quot;Control&quot;, 0, 1)<br># Data will be matched without one variable (Gender).<br># Different matched data can be obtained, for reproducible result the set.seed is used.<br>set.seed(2708)<br># The dependent variable is dichotomous treatment variable.<br># The covariates are pre-treatment characteristics of students.<br># This command creates the MatchIt object called match.<br>match &lt;- matchit(Treatment.Type ~ Age + Math.Grade + Overall.Grade, <br>  data = ChessWide, method = &quot;nearest&quot;)<br># The function match.data() is used to create the matched data from the MatchIt.<br># output object by excluding unmatched units from the original data.<br>matcheddata &lt;- match.data(match)<br># Creating function for comparison (results of Chi-squared and ANOVA tests).<br>comparetable &lt;- function(data){<br>  <br>  pacman::p_load(tableone)<br>  tab &lt;- CreateTableOne( vars =  c(&quot;Gender&quot;, &quot;Age&quot;, &quot;Math.Grade&quot;, &quot;Overall.Grade&quot;), <br>                         data = data, <br>                         factorVars =  c(&quot;Gender&quot;, &quot;Overall.Grade&quot;), <br>                         strata = &#39;Treatment.Type&#39;)<br>  tab &lt;- print(tab, printToggle = FALSE, noSpaces = TRUE)<br>  tab[,-4]<br>}<br># Relabel the data and see the result.<br>matcheddata$Treatment.Type = ifelse(matcheddata$Treatment.Type == 0,&quot;Control&quot;, &quot;Treatment&quot;)<br>knitr::kable(comparetable(matcheddata)) %&gt;%<br>  kableExtra::kable_styling(bootstrap_options = &quot;striped&quot;, full_width = F)</pre><p><em>‘Treatment.Type’</em> is the dichotomous treatment variable, <em>‘Gender, Age, Math.grade, Overall.Grade’</em> pre-treatment covariates, all of which are contained in the data frame ChessWide (The long format of data is for regression analysis, and wide format for matching and visualization). The dependent variable may be included in ChessWide for convenience but is never used by MatchIt or included in the formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*PHouVPIeNPscs-buDqDs2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*Cb_cyGyQ04UXYFou0vsq7A.png" /></figure><p>The distribution of variables across treatment and control groups is relatively similar, the test result also indicates that there is no significant difference between groups on the personal characteristics of students. The effect of the treatment can now be estimated as the difference between the average outcome for treated students and the mean outcome for untreated students in the matched sample. Although there is no noticeable difference between results, the second parametric analysis is more reliable because it is based on matched data.</p><pre># For regression analysis we use the data in the long format<br>MLong &lt;- tidyr::gather(matcheddata, PrePost, Answers, c(Pre,Post), factor_key=TRUE)<br>matchedmodel &lt;- lm(Answers ~ Treatment.Type + PrePost + Treatment.Type * PrePost, data = MLong)<br>stargazer::stargazer(matchedmodel,<br>  title = &quot;DID Results&quot;,<br>  dep.var.labels = c(&quot;Answers&quot;),<br>  out=&quot;models.htm&quot;,<br>  type = &quot;text&quot;,<br>  header=FALSE, <br>  covariate.labels = c(<br>    &quot;Group (Treatment)&quot;,<br>    &quot;Time (Post)&quot;,<br>    &quot;Group * Time (Treatment * Post)&quot;<br>  ))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*f4tLpBejyNNsdDxW-LZPkg.png" /></figure><h3>Conclusion</h3><p>All in all, randomization is a popular method to block or minimize potential imbalance between the treatment and control groups in order to control the confounding. We used popular method Propensity score matching for providing the random or pseudorandom data for analysis. The basic steps for PSM implementation are:</p><p>1. Fit the logit (or other) model, where the dependent variable is treatment groups and the independent variables are confounding variables.</p><p>2. Split the sample into user-defined k intervals of the propensity scores.</p><p>3. Within each interval, run a test to assure that the average propensity score of control and treated units do not differ.</p><p>4. If the test fails in one interval, split the interval in half and test again.</p><p>5. Continue until the distribution is equal in both groups.</p><p>6. Test the difference (using average value or proportion) for characteristics to determine the difference between groups.</p><p>7. Conduct the parametric (or other) analysis using the matched balanced data</p><p>It seems that PSM is an ideal method for balancing data. However, the authors state some drawbacks in PSM. One of them is that the results of using the propensity scores are conditional <strong>only</strong> on the observed covariates. Thus, unmeasured confounding bias cannot be excluded. Other illustrations of PSM drawbacks may be found <a href="https://gking.harvard.edu/files/gking/files/psnot.pdf">here</a>.</p><h4>Reference List</h4><blockquote>* P. Rosenbaum, D. Rubin, “The Central Role of the Propensity Score in Observational Studies for Causal Effects.”<br>* E. Patorno, Al. Grotta, et al, “Propensity score methodology for confounding control in health care utilization databases.”<br>* S. Schneeweiss, “A basic study design for expedited safety signal evaluation based on electronic healthcare data.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6119ad79bbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamotus/pseudorandomization-propensity-score-matching-c6119ad79bbc">Pseudorandomization: Propensity score matching</a> was originally published in <a href="https://medium.com/datamotus">Datamotus</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>