<?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 Paulo R S Oliveira on Medium]]></title>
        <description><![CDATA[Stories by Paulo R S Oliveira on Medium]]></description>
        <link>https://medium.com/@proberto3122?source=rss-7afebe988e30------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_L8fo100CFPw29cHWuCo5g.png</url>
            <title>Stories by Paulo R S Oliveira on Medium</title>
            <link>https://medium.com/@proberto3122?source=rss-7afebe988e30------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:50:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@proberto3122/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[Heart Disease Multivariate Analysis with R — Part 3 of 3]]></title>
            <link>https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-3-of-3-8210a695f64f?source=rss-7afebe988e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/8210a695f64f</guid>
            <category><![CDATA[linear-discriminant]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[discriminant-analysis]]></category>
            <category><![CDATA[goodness-of-fit]]></category>
            <category><![CDATA[quadratic-discriminant]]></category>
            <dc:creator><![CDATA[Paulo R S Oliveira]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 21:06:01 GMT</pubDate>
            <atom:updated>2026-10-08T21:06:01.605Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Heart Disease Multivariate Analysis with R — Part 3 of 3</strong></h3><p><strong>Linear Regression, Discriminant Analysis (LDA and QDA) and Logistic Regression</strong></p><h3>I. Introduction</h3><p>This final part asks a practical question:</p><p><strong><em>Can the clinical records of 299 heart failure patients predict who dies during follow-up?</em></strong></p><p>We answer it with linear regression, principal components regression, LDA, QDA and binomial logistic regression, all evaluated on a held-out test sample.</p><p>In [Part 1](<a href="https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-1-of-3-bce77a7cb31c">https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-1-of-3-bce77a7cb31c</a>) we introduced the theory, chose `ejection_fraction` as our quantitative variable (`VQ`) and `DEATH_EVENT` as our qualitative variable (`VN`), and explored the data. We found no missing values, weak correlations, no multivariate normality and unequal variance-covariance matrices between the two classes.</p><p>In <a href="https://medium.com/p/102defac2281/edit">Part 2</a> we tried Factor Analysis and Cluster Analysis. The KMO index (0.55) showed the variables share little common structure, and the clusters we found agreed poorly with the death event categories.</p><p><em>Part 3 covers</em>:</p><ul><li><em>Splitting the data into training (80%) and test (20%) samples.</em></li><li><em>A linear regression model to estimate `VQ`, and a principal components version of it.</em></li><li><em>Discriminant analysis (LDA and QDA) and logistic regression to classify `VN`, using a balanced training sample.</em></li><li><em>Evaluation with confusion matrices and ROC curves.</em></li></ul><h3>II. Splitting the data</h3><h4>Training and test samples</h4><p>We split the 299 patients into 239 for training (80%) and 60 for testing (20%). Models learn only from the training sample; the test sample tells us how they behave on patients they have never seen.</p><p>Setting a seed makes the split reproducible, so readers who run the code get the same samples.</p><pre><br>set.seed(1234)<br>n &lt;- nrow(hrtfail)<br>n_treino &lt;- round(0.8 * n)<br>s &lt;- sample(1:n)<br>hrt5_treino &lt;- hrtfail[s[1:n_treino], ]<br>hrt5_teste &lt;- hrtfail[s[(n_treino + 1):n], ]<br>dim(hrt5_treino)<br>dim(hrt5_teste)<br></pre><pre>dim(hrt5_treino)<br>[1] 239  13<br><br>dim(hrt5_teste)<br>[1] 60 13</pre><h3>III. Linear regression</h3><p>The best linear model explains only about 3% of the variance in ejection fraction (adjusted R² = 0.033). The other clinical variables carry very little information about how well the heart pumps.</p><p><strong><em>Finding a parsimonious model</em></strong></p><p>We start with a full model that estimates `VQ` from the quantitative variables in the training sample.</p><pre><br>mod1 &lt;- lm(VQ ~ age + anaemia + creatinine_phosphokinase + time +<br> high_blood_pressure + platelets + serum_sodium,<br> data = hrt5_treino)<br>summary(mod1)<br></pre><pre><br>summary(mod1)<br><br>Call:<br>lm(formula = VQ ~ age + anaemia + creatinine_phosphokinase + <br>    time + high_blood_pressure + platelets + serum_sodium, data = hrt5_treino)<br><br>Residuals:<br>    Min      1Q  Median      3Q     Max <br>-23.228  -7.650  -1.320   6.005  44.045 <br><br>Coefficients:<br>                           Estimate Std. Error t value Pr(&gt;|t|)   <br>(Intercept)              -4.466e+01  2.595e+01  -1.721  0.08656 . <br>age                       6.937e-02  6.741e-02   1.029  0.30451   <br>anaemia                   1.548e-01  1.587e+00   0.098  0.92239   <br>creatinine_phosphokinase -6.896e-04  9.333e-04  -0.739  0.46076   <br>time                      7.345e-03  1.054e-02   0.697  0.48666   <br>high_blood_pressure       1.749e+00  1.608e+00   1.087  0.27799   <br>platelets                -1.428e-06  9.653e-06  -0.148  0.88252   <br>serum_sodium              5.679e-01  1.896e-01   2.996  0.00304 **<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Residual standard error: 11.83 on 231 degrees of freedom<br>Multiple R-squared:  0.05165, Adjusted R-squared:  0.02291 <br>F-statistic: 1.797 on 7 and 231 DF,  p-value: 0.0887</pre><p>A parsimonious model explains the response with as few predictors as possible without losing explanatory power. We remove variables with the highest p-values one step at a time: first ‘anaemia’ (mod2), then ‘platelets’ and ‘creatinine_phosphokinase’ (mod3).</p><pre><br>mod2 &lt;- lm(VQ ~ age + creatinine_phosphokinase + time +<br> high_blood_pressure + platelets + serum_sodium,<br> data = hrt5_treino)<br><br>mod3 &lt;- lm(VQ ~ age + time + high_blood_pressure + serum_sodium,<br> data = hrt5_treino)<br><br>summary(mod2)<br><br>summary(mod3)<br></pre><pre>summary(mod2)<br><br>Call:<br>lm(formula = VQ ~ age + creatinine_phosphokinase + time + high_blood_pressure + <br>    platelets + serum_sodium, data = hrt5_treino)<br><br>Residuals:<br>    Min      1Q  Median      3Q     Max <br>-23.169  -7.650  -1.408   5.926  43.968 <br><br>Coefficients:<br>                           Estimate Std. Error t value Pr(&gt;|t|)   <br>(Intercept)              -4.480e+01  2.585e+01  -1.733  0.08436 . <br>age                       6.934e-02  6.726e-02   1.031  0.30369   <br>creatinine_phosphokinase -7.064e-04  9.153e-04  -0.772  0.44103   <br>time                      7.217e-03  1.044e-02   0.691  0.48997   <br>high_blood_pressure       1.748e+00  1.605e+00   1.089  0.27711   <br>platelets                -1.483e-06  9.615e-06  -0.154  0.87754   <br>serum_sodium              5.698e-01  1.882e-01   3.027  0.00274 **<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Residual standard error: 11.8 on 232 degrees of freedom<br>Multiple R-squared:  0.05161, Adjusted R-squared:  0.02708 <br>F-statistic: 2.104 on 6 and 232 DF,  p-value: 0.05365<br><br><br>summary(mod3)<br><br>Call:<br>lm(formula = VQ ~ age + time + high_blood_pressure + serum_sodium, <br>    data = hrt5_treino)<br><br>Residuals:<br>    Min      1Q  Median      3Q     Max <br>-22.821  -7.482  -1.354   6.113  44.005 <br><br>Coefficients:<br>                      Estimate Std. Error t value Pr(&gt;|t|)   <br>(Intercept)         -44.002971  25.751915  -1.709  0.08883 . <br>age                   0.073669   0.066779   1.103  0.27108   <br>time                  0.007256   0.010403   0.698  0.48616   <br>high_blood_pressure   1.756767   1.596989   1.100  0.27244   <br>serum_sodium          0.556395   0.186481   2.984  0.00315 **<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Residual standard error: 11.77 on 234 degrees of freedom<br>Multiple R-squared:  0.049, Adjusted R-squared:  0.03274 <br>F-statistic: 3.014 on 4 and 234 DF,  p-value: 0.01886</pre><pre><br>Model Predictors Adjusted R²<br> - - - - - - - - - - - - - -<br>mod1 7 0.02291<br>mod2 6 0.02708<br>mod3 4 0.03274<br></pre><p>Removing variables slightly increased the adjusted R², because that measure penalises predictors that add noise rather than information.</p><h4>a. Comparing the models</h4><p>The ANOVA test checks whether the extra variables in the larger models improve the fit.</p><p>- H0: the models have the same explanatory power.<br>- H1: the models have different explanatory power.<br>- Significance level: 5%.</p><pre><br>anova(mod1, mod2, mod3)<br>AIC(mod1, mod2, mod3)<br>BIC(mod1, mod2, mod3)<br></pre><pre>Analysis of Variance Table<br><br>Model 1: VQ ~ age + anaemia + creatinine_phosphokinase + time + high_blood_pressure + <br>    platelets + serum_sodium<br>Model 2: VQ ~ age + creatinine_phosphokinase + time + high_blood_pressure + <br>    platelets + serum_sodium<br>Model 3: VQ ~ age + time + high_blood_pressure + serum_sodium<br>    Res.Df  RSS Df   Sum of  Sq    F Pr(&gt;F)<br>1    231 32327                           <br>2    232 32329 -1    -1.331 0.0095 0.9224<br>3    234 32418 -2   -89.054 0.3182 0.7278<br><br><br><br>AIC(mod1, mod2, mod3)<br>     df      AIC<br>mod1  9 1869.075<br>mod2  8 1867.085<br>mod3  6 1863.742<br><br>BIC(mod1, mod2, mod3)<br>     df      BIC<br>mod1  9 1900.363<br>mod2  8 1894.896<br>mod3  6 1884.601</pre><p>The p-value is above 0.05, so we cannot reject H0: dropping three variables costs no explanatory power. mod3 also has the lowest AIC, so we keep it as our parsimonious model.</p><h4>b. Checking multicollinearity</h4><p>Multicollinearity happens when predictors are strongly correlated with each other, which inflates the uncertainty of the coefficients. The Variance Inflation Factor (VIF) measures it: values near 1 are ideal and values above 5 to 10 signal a problem.</p><pre><br>library(car)<br>round(vif(mod3), 3)<br></pre><pre>    age                time    high_blood_pressure        serum_sodium <br>   1.040               1.087               1.033               1.020 </pre><p>All VIF values are below 3, so multicollinearity is not a concern in this model.</p><h4>c. Principal components regression</h4><p>Replacing mod3’s four predictors with their principal components changes nothing in explanatory power, and the full-component model predicted the test sample best (RMSE = 11.48).</p><p>Principal Component Analysis (PCA) turns correlated variables into uncorrelated components. We apply it to the four predictors of mod3: ‘age’, ‘time’, ‘high_blood_pressure’ and ‘serum_sodium’. Setting ‘cor = TRUE’ uses the correlation matrix, so variables on different scales weigh equally.</p><pre><br>pca5b &lt;- princomp(hrt5_treino[, c(&quot;age&quot;, &quot;time&quot;,<br> &quot;high_blood_pressure&quot;,<br> &quot;serum_sodium&quot;)], cor = TRUE)<br>summary(pca5b)<br><br>library(factoextra)<br>fviz_eig(pca5b, addlabels = TRUE, main = &quot;Scree plot pca5b&quot;)<br></pre><pre>summary(pca5b)<br>Importance of components:<br>                         Comp.1    Comp.2    Comp.3    Comp.4<br>Standard deviation     1.155093 0.9984877 0.9630664 0.8609794<br>Proportion of Variance 0.333560 0.2492444 0.2318742 0.1853214<br>Cumulative Proportion  0.333560 0.5828044 0.8146786 1.0000000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*P8FibCjDkDGte1r1M_8mxg.png" /></figure><p>The next two plots show how well each patient is represented by the first two components, and how much each variable contributes to them.</p><pre><br>fviz_pca_ind(pca5b, col.ind = &quot;cos2&quot;,<br> gradient.cols = c(&quot;lightblue&quot;, &quot;lightgreen&quot;, &quot;red&quot;),<br> repel = TRUE, legend.title = &quot;Representation quality&quot;)<br><br>fviz_pca_var(pca5b, col.var = &quot;contrib&quot;,<br> gradient.cols = c(&quot;darkblue&quot;, &quot;darkgreen&quot;, &quot;red&quot;),<br> repel = TRUE, legend.title = &quot;Contribution&quot;)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*C4V1u1KvmfInLUsc-o3wig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*GfWsXg-Y1DYbY-bG9Q55ww.png" /></figure><p>Patients near the centre of the first plot are usually poorly represented; here the quality is mixed across the plane.</p><p>In the variables plot, each arrow is a variable. Its direction shows how it relates to the two dimensions, its length shows how well the plane represents it, and its colour shows its contribution.</p><pre>Variable              Dim1    Dim2    Contribution   Contribution<br>                      corr.   corr.   to Dim1 (%)    to Dim2 (%)<br>-------------------   -----   -----   ------------   ------------<br>time                  -0.76    0.04       43.5            0.2<br>age                    0.58    0.17       25.1            2.9<br>high_blood_pressure    0.52    0.49       20.5           24.4<br>serum_sodium          -0.38    0.85       10.8           72.5</pre><p><strong>Dim1 (33.4% of the variance)</strong> opposes time to age and high_blood_pressure. Patients on the right of the plot tend to be older, hypertensive and to have shorter follow-up, which is the profile of higher risk we saw in <a href="https://medium.com/p/102defac2281/edit">Part 2</a>. Patients on the left are younger, without hypertension, with longer follow-up.</p><p><strong>Dim2 (24.9% of the variance)</strong> is essentially serum_sodium, which alone accounts for 72.5% of it, with some help from high_blood_pressure.</p><p>Two details stand out. First, the variance is spread almost evenly across the four components (33%, 25%, 23% and 19%), so PCA compresses very little here: with variables this weakly correlated, there is little redundancy to remove. Second, the plot explains the regression results that follow. serum_sodium is the predictor most correlated with VQ (0.20), and it drives Dim2. Accordingly, Comp.2 is the only component noticeably correlated with ejection fraction (0.21), while Comp.1 barely is (−0.03). That is why, below, a model without Comp.1 keeps almost all of the explanatory power.</p><p>Now we use the component scores as predictors of `VQ`.</p><pre>hrt5b_Comb &lt;- data.frame(cbind(hrt5_treino, pca5b$scores))<br><br>mod5b  &lt;- lm(VQ ~ Comp.1 + Comp.2 + Comp.3 + Comp.4, data = hrt5b_Comb)<br>mod5b2 &lt;- lm(VQ ~ Comp.1 + Comp.2 + Comp.3,          data = hrt5b_Comb)<br>mod5b3 &lt;- lm(VQ ~ Comp.2 + Comp.3,                   data = hrt5b_Comb)<br><br>summary(mod5b)<br>anova(mod5b, mod5b2, mod5b3)<br>AIC(mod5b, mod5b2, mod5b3)</pre><pre>summary(mod5b)<br><br>Call:<br>lm(formula = VQ ~ Comp.1 + Comp.2 + Comp.3 + Comp.4, data = hrt5b_Comb)<br><br>Residuals:<br>    Min      1Q  Median      3Q     Max <br>-22.821  -7.482  -1.354   6.113  44.005 <br><br>Coefficients:<br>            Estimate Std. Error t value Pr(&gt;|t|)    <br>(Intercept)  38.1841     0.7614  50.153  &lt; 2e-16 ***<br>Comp.1       -0.3062     0.6591  -0.465 0.642669    <br>Comp.2        2.5429     0.7625   3.335 0.000992 ***<br>Comp.3        0.6103     0.7905   0.772 0.440924    <br>Comp.4        0.3092     0.8843   0.350 0.726914    <br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Residual standard error: 11.77 on 234 degrees of freedom<br>Multiple R-squared:  0.049, Adjusted R-squared:  0.03274 <br>F-statistic: 3.014 on 4 and 234 DF,  p-value: 0.01886</pre><pre>anova(mod5b, mod5b2, mod5b3)<br>Analysis of Variance Table<br><br>Model 1: VQ ~ Comp.1 + Comp.2 + Comp.3 + Comp.4<br>Model 2: VQ ~ Comp.1 + Comp.2 + Comp.3<br>Model 3: VQ ~ Comp.2 + Comp.3<br>    Res.Df RSS  Df    Sum of Sq    F Pr(&gt;F)<br>1    234 32418                           <br>2    235 32435 -1   -16.937 0.1223 0.7269<br>3    236 32465 -1   -29.900 0.2158 0.6427</pre><pre>AIC(mod5b, mod5b2, mod5b3)<br>        df    AIC<br>mod5b   6  1863.742<br>mod5b2  5  1861.867<br>mod5b3  4  1860.087</pre><p>With all four components, mod5b has exactly the same adjusted R² as mod3 (0.03274). That is expected: the components are only a rotation of the same four variables, so they carry the same information.</p><p>The ANOVA shows no significant difference between the three component models (F = 0.169, p = 0.8446, when comparing mod5b with mod5b3). mod5b3, with only Comp.2 and Comp.3, has the lowest AIC and is the most parsimonious.</p><h4>d. Performance on the test sample</h4><p>We project the test patients onto the components learned from the training sample, then compare predicted and observed `VQ` with three measures:</p><ul><li>RMSE (root mean squared error): typical prediction error, in ejection fraction points; penalises large errors.</li><li>MAE (mean absolute error): average size of the error, less sensitive to outliers.</li><li>R²: share of the variance in the test sample explained by the predictions.</li></ul><pre><br>library(caret)<br>pca_newdata &lt;- predict(pca5b, data.frame(hrt5_teste))<br><br>pred_mod5b  &lt;- predict(mod5b,  data.frame(pca_newdata))<br>pred_mod5b3 &lt;- predict(mod5b3, data.frame(pca_newdata))<br><br>postResample(pred_mod5b,  hrt5_teste$VQ)<br>postResample(pred_mod5b3, hrt5_teste$VQ)<br></pre><pre><br>Model                   RMSE     MAE     R²<br>---------------------   ------   -----   ------<br>mod5b (4 components)    11.476   8.875   0.0068<br>mod5b3 (2 components)   11.507   8.892   0.0059<br></pre><p>mod5b had the lower RMSE. With an error of about 11.5 points on a variable that ranges from 14 to 80, neither model is useful for estimating ejection fraction in practice. That matches <a href="https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-1-of-3-bce77a7cb31c">Part 1</a>, where `VQ` showed very weak correlations with every other variable.</p><h3>III. Discriminant analysis</h3><p>Discriminant analysis builds a rule that assigns each patient to a class of ‘VN’ (death event: ‘no’ or ‘yes’) from their clinical variables. We train it on a balanced training sample and evaluate it on the test sample in section d.</p><h4>a. Preparing the data</h4><p>We reload the data so this section runs on its own, apply the same renaming as in <a href="https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-1-of-3-bce77a7cb31c">Part 1</a>, and use the same seed so the split matches section 4.</p><pre><br>library(readr)<br>library(dplyr)<br><br>hrtfail_Q6 &lt;- read_csv(&quot;Heart_failure.csv&quot;)<br>hrtfail_Q6 &lt;- rename(hrtfail_Q6, VN = DEATH_EVENT, VQ = ejection_fraction)<br>hrtfail_Q6$VN &lt;- factor(hrtfail_Q6$VN, labels = c(&quot;no&quot;, &quot;yes&quot;))<br>hrtfail_Q6 &lt;- hrtfail_Q6 %&gt;% mutate(...1 = NULL)<br>hrtfail_Q6 &lt;- relocate(hrtfail_Q6, VN, sex, diabetes, smoking, VQ, age,<br>                       anaemia, creatinine_phosphokinase,<br>                       high_blood_pressure, platelets, serum_sodium, time)<br>hrtfail_Q6 &lt;- as.data.frame(hrtfail_Q6)<br><br>set.seed(1234)<br>n6        &lt;- nrow(hrtfail_Q6)<br>n6_treino &lt;- round(0.8 * n6)<br>s6        &lt;- sample(1:n6)<br><br>hrt6_treino &lt;- hrtfail_Q6[s6[1:n6_treino], ]<br>hrt6_teste  &lt;- hrtfail_Q6[s6[(n6_treino + 1):n6], ]<br><br>table(hrt6_treino$VN)<br>table(hrt6_teste$VN)<br></pre><p>The training sample has 160 survivors and 79 deaths; the test sample has 43 survivors and 17 deaths.</p><h4>b. Balancing the training sample with oversampling</h4><p>Only about 32% of patients died (96 of 299), so a classifier could score well just by predicting ‘no’ for everyone. Oversampling fixes this by randomly replicating patients from the smaller class until both classes have the same size. No original information is discarded.</p><p>We balance only the training sample. The test sample keeps its real class proportions, so the evaluation reflects the real world.</p><pre><br>library(UBL)<br>set.seed(1223)<br><br>hrt6_treino_bo &lt;- RandOverClassif(VN ~ ., hrt6_treino, &quot;balance&quot;)<br>table(hrt6_treino_bo$VN)<br></pre><p>After oversampling, the training sample has 160 patients in each class (320 in total).</p><h4>c. Linear Discriminant Analysis (LDA)</h4><p>LDA finds the linear combination of variables that best separates the two classes. The output gives the prior probabilities (50/50 after balancing), the class means of each variable and the coefficients of the discriminant function.</p><pre>library(MASS)<br>lda6 &lt;- lda(VN ~ ., data = hrt6_treino_bo)<br>lda6<br></pre><p>The raw output prints the coefficients in scientific notation (for example, -2.079604e-06 for platelets). The table below shows the same results in plain numbers. Prior probabilities are 0.5 for each class.</p><pre>                              Group means               LD1 coefficient<br>Variable                   no          yes          raw          standardized<br>------------------------   ---------   ---------    ----------   ------------<br>time                          155.48       75.98    -0.011582       -0.759<br>VQ                             40.69       33.51    -0.046544       -0.551<br>serum_creatinine                1.16        1.94     0.355364        0.407<br>age                            59.12       64.80     0.020817        0.245<br>creatinine_phosphokinase      483.59      658.88     0.000207        0.209<br>serum_sodium                  137.54      135.43    -0.046319       -0.195<br>platelets                 263,285.30  245,805.00    -0.000002       -0.167<br>sex                             0.64        0.64    -0.317499       -0.153<br>high_blood_pressure             0.36        0.41    -0.193580       -0.094<br>anaemia                         0.44        0.45    -0.137035       -0.068<br>smoking                         0.33        0.30    -0.097169       -0.045<br>diabetes                        0.40        0.39     0.031078        0.015</pre><p>The raw coefficients depend on each variable’s units, so a tiny number like the one for platelets does not mean the variable is unimportant: platelets are counted in the hundreds of thousands. To compare variables, we multiply each coefficient by the variable’s within-group standard deviation, which gives the standardized coefficients in the last column.</p><pre>W &lt;- Reduce(`+`, lapply(split(hrt6_treino_bo[, -1], hrt6_treino_bo$VN),<br>                        function(g) cov(g) * (nrow(g) - 1))) /<br>     (nrow(hrt6_treino_bo) - 2)<br>round(lda6$scaling[, 1] * sqrt(diag(W)), 3)</pre><p>Higher LD1 scores push a patient towards yes (death). Follow-up time and ejection fraction (VQ) carry the most weight, both pulling towards survival, followed by serum_creatinine and age, which pull towards death. The group means tell the same story: patients who died had half the follow-up time (76 vs 155 days), lower ejection fraction (33.5 vs 40.7) and higher serum creatinine (1.94 vs 1.16). Sex, smoking, anaemia and diabetes barely differ between the groups and have little weight.</p><p>LDA assumes multivariate normal predictors and equal variance-covariance matrices in both classes. We test both on the balanced training sample, at a 5% significance level.</p><pre>library(mvnormtest)<br>library(heplots)<br><br>mshapiro.test(t(hrt6_treino_bo[, 5:13]))<br>boxM(hrt6_treino_bo[, 5:13], hrt6_treino_bo$VN)</pre><pre> mshapiro.test(t(hrt6_treino_bo[,5:13]))<br><br> Shapiro-Wilk normality test<br><br>data:  Z<br>W = 0.70462, p-value &lt; 2.2e-16<br><br><br>boxM(hrt6_treino_bo[,5:13], hrt6_treino_bo$VN)<br><br> Box&#39;s M-test for Homogeneity of Covariance Matrices<br><br>data:  hrt6_treino_bo[, 5:13]<br>Chi-Sq (approx.) = 238.41, df = 45, p-value &lt; 2.2e-16</pre><p>Both p-values are below 2.2e-16, so both assumptions fail, as they did on the full data in Part 1. LDA can still classify reasonably well when assumptions are violated, but its results deserve caution. The failed Box’s M test is the reason we also try QDA.</p><p>The histograms of the discriminant scores show how far apart the two classes sit along the LDA axis.</p><pre>lda6_treino_bo &lt;- predict(lda6, hrt6_treino_bo)<br><br>ldahist(data = lda6_treino_bo$x, g = hrt6_treino_bo$VN, type = &quot;b&quot;)<br><br>library(caret)<br>confusionMatrix(lda6_treino_bo$class, hrt6_treino_bo$VN, positive = &quot;yes&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*jPxrF2GxzOSaN3F5qTbjBg.png" /></figure><p>The histograms show the LD1 score of every patient in the balanced training sample, one panel per class. The patients who survived are centred at −0.9 and those who died at +0.9, both with a standard deviation of about 1. LDA classifies a patient as yes when their score is above 0, the midpoint between the two centres.</p><p>The two distributions overlap clearly. About 21% of the survivors have positive scores, and about 22% of those who died have negative scores. These patients fall on the wrong side of the boundary, and they are exactly the errors we see in the confusion matrix.</p><pre><br>Confusion Matrix and Statistics<br><br>          Reference<br>Prediction  no yes<br>       no  126  35<br>       yes  34 125<br>                                          <br>               Accuracy : 0.7844          <br>                 95% CI : (0.7352, 0.8282)<br>    No Information Rate : 0.5             <br>    P-Value [Acc &gt; NIR] : &lt;2e-16          <br>                                          <br>                  Kappa : 0.5688          <br>                                          <br> Mcnemar&#39;s Test P-Value : 1               <br>                                          <br>            Sensitivity : 0.7875          <br>            Specificity : 0.7812          <br>         Pos Pred Value : 0.7826          <br>         Neg Pred Value : 0.7862          <br>             Prevalence : 0.5000          <br>         Detection Rate : 0.3937          <br>   Detection Prevalence : 0.5031          <br>      Balanced Accuracy : 0.7844          <br>                                          <br>       &#39;Positive&#39; Class : no </pre><p>The model classifies 78.4% of the training patients correctly. Errors are balanced between the two classes: 35 deaths were classified as survivors, and 34 survivors as deaths. That balance is a direct effect of oversampling, since with equal priors the model has no reason to favour either class. A Kappa of 0.569 means moderate agreement beyond chance.</p><p>One caution about these numbers: 81 of the 160 yes patients are copies created by oversampling, so the training sample overstates how much distinct information the model has seen. The test sample in section II-d is the fair check.</p><h4>d. Quadratic Discriminant Analysis (QDA)</h4><p>QDA drops the equal-covariance assumption: each class gets its own variance-covariance matrix, and the boundary between classes becomes a curve instead of a straight line. It fits our data better in theory, at the cost of more parameters to estimate.</p><pre>qda6 &lt;- qda(VN ~ ., data = hrt6_treino_bo)<br>qda6<br><br>qda6_treino &lt;- predict(qda6, hrt6_treino_bo)<br>confusionMatrix(qda6_treino$class, hrt6_treino_bo$VN, positive = &quot;yes&quot;)</pre><pre>Confusion Matrix and Statistics<br><br>          Reference<br>Prediction  no yes<br>       no  148  49<br>       yes  12 111<br>                                         <br>               Accuracy : 0.8094         <br>                 95% CI : (0.762, 0.8509)<br>    No Information Rate : 0.5            <br>    P-Value [Acc &gt; NIR] : &lt; 2.2e-16      <br>                                         <br>                  Kappa : 0.6187         <br>                                         <br> Mcnemar&#39;s Test P-Value : 4.04e-06       <br>                                         <br>            Sensitivity : 0.9250         <br>            Specificity : 0.6937         <br>         Pos Pred Value : 0.7513         <br>         Neg Pred Value : 0.9024         <br>             Prevalence : 0.5000         <br>         Detection Rate : 0.4625         <br>   Detection Prevalence : 0.6156         <br>      Balanced Accuracy : 0.8094         <br>                                         <br>       &#39;Positive&#39; Class : no</pre><p>Accuracy on the training sample is optimistic, because the model has already seen these patients, and oversampling repeats some of them. The test sample in II-d is the real check.</p><h4>e. Binomial logistic regression</h4><p>Logistic regression estimates the probability that a patient dies, and makes no assumption about normality or equal covariances. That makes it a natural alternative when, as here, the LDA assumptions fail.</p><p>R models the probability of the second level of the factor. Since ‘levels(VN)’ is ‘ ”no” “yes” ’, the model returns P(death = yes).</p><pre><br>levels(hrt6_treino_bo$VN)<br>RegLogQ6 &lt;- glm(VN ~ sex + smoking + VQ + age + anaemia +<br> creatinine_phosphokinase + high_blood_pressure +<br> platelets + serum_sodium + time,<br> family = binomial, data = hrt6_treino_bo)<br>summary(RegLogQ6)<br></pre><pre>summary(RegLogQ6)<br><br>Call:<br>glm(formula = VN ~ sex + smoking + VQ + age + anaemia + creatinine_phosphokinase + <br>    high_blood_pressure + platelets + serum_sodium + time, family = binomial, <br>    data = hrt6_treino_bo)<br><br>Deviance Residuals: <br>     Min        1Q    Median        3Q       Max  <br>-2.47972  -0.70246  -0.01393   0.66219   2.80474  <br><br>Coefficients:<br>                           Estimate Std. Error z value Pr(&gt;|z|)    <br>(Intercept)               2.071e+01  5.650e+00   3.666 0.000246 ***<br>sex                      -6.147e-01  3.705e-01  -1.659 0.097098 .  <br>smoking                  -1.852e-01  3.763e-01  -0.492 0.622612    <br>VQ                       -7.428e-02  1.418e-02  -5.237 1.63e-07 ***<br>age                       4.207e-02  1.463e-02   2.876 0.004027 ** <br>anaemia                  -1.706e-01  3.111e-01  -0.548 0.583407    <br>creatinine_phosphokinase  5.734e-04  2.283e-04   2.511 0.012025 *  <br>high_blood_pressure      -3.939e-01  3.203e-01  -1.230 0.218789    <br>platelets                -4.498e-06  1.997e-06  -2.252 0.024321 *  <br>serum_sodium             -1.237e-01  4.032e-02  -3.067 0.002159 ** <br>time                     -1.917e-02  2.501e-03  -7.662 1.83e-14 ***<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>(Dispersion parameter for binomial family taken to be 1)<br><br>    Null deviance: 443.61  on 319  degrees of freedom<br>Residual deviance: 280.55  on 309  degrees of freedom<br>AIC: 302.55<br><br>Number of Fisher Scoring iterations: 5</pre><p>A negative coefficient lowers the probability of death as the variable increases; a positive one raises it. At the 5% level, six variables are significant. Higher ejection fraction (`VQ`), serum sodium, platelet count and longer follow-up time lower the probability of death; older age and higher creatinine phosphokinase raise it. Sex, smoking, anaemia and high blood pressure are not significant.</p><h4>f. Goodness of fit: Hosmer-Lemeshow test</h4><p>The Hosmer-Lemeshow test groups patients into 10 bins by predicted probability and compares predicted and observed deaths in each bin.</p><p>- H0: the model fits the data well.<br>- H1: the model does not fit the data well.<br>- Significance level: 5%.</p><p>The test expects the outcome coded as 0/1, so we create a numeric version of ‘VN’ first. Passing the factor directly makes R code it as 1/2, which inflates the statistic and gives a misleading p-value.</p><pre><br>library(ResourceSelection)<br>hrt6_treino_bo$VNyes &lt;- ifelse(hrt6_treino_bo$VN == &quot;yes&quot;, 1, 0)<br>hoslem.test(hrt6_treino_bo$VNyes, fitted(RegLogQ6), g = 10)<br></pre><p>The test gives X² = 13.01 with 8 degrees of freedom and p = 0.11. Since p is above 0.05, we cannot reject H0: there is no evidence that the model fits poorly.</p><h4>g. Multicollinearity and pseudo R²</h4><pre><br>round(car::vif(RegLogQ6), 3)<br><br>library(DescTools)<br>PseudoR2(RegLogQ6, c(&quot;CoxSnell&quot;, &quot;Nagelkerke&quot;, &quot;McFadden&quot;))<br></pre><pre>round(VIF(RegLogQ6),3)<br>                     sex                  smoking                       VQ <br>                   1.484                    1.337                    1.294 <br>                     age                  anaemia creatinine_phosphokinase <br>                   1.132                    1.083                    1.232 <br>     high_blood_pressure                platelets             serum_sodium <br>                   1.067                    1.090                    1.188 <br>                    time <br>                   1.320 </pre><p>All VIF values are below 1.5 (the highest is 1.48, for sex), so the predictors are not redundant.</p><p>Pseudo R² measures imitate the R² of linear regression but are not directly comparable to it, or to each other. McFadden values between 0.2 and 0.4 are usually read as a good fit; Nagelkerke rescales Cox-Snell so its maximum is 1.</p><pre><br>Pseudo R²    Value<br>----------   -----<br>Cox-Snell    0.399<br>Nagelkerke   0.532<br>McFadden     0.368<br></pre><p>McFadden’s 0.368 sits inside the 0.2 to 0.4 range, which points to a good fit, consistent with the Hosmer-Lemeshow test.</p><h4>h. Evaluation on the test sample</h4><p>The test sample has 60 patients the models never saw, with the real proportion of deaths. We treat yes (death) as the positive class, because missing a patient at risk is the costlier error.</p><p>The confusion matrix crosses predicted and observed classes. From it we read:</p><ul><li><strong>Accuracy</strong>: share of patients classified correctly.</li><li><strong>Sensitivity</strong>: share of deaths the model detected.</li><li><strong>Specificity</strong>: share of survivors the model classified correctly.</li><li><strong>Kappa</strong>: agreement beyond what chance alone would give (0 = chance, 1 = perfect).</li></ul><p>The ROC curve plots sensitivity against 1 − specificity for every possible cut-off. The area under it (AUC) summarises it: 0.5 is a coin toss, above 0.8 is good, 1 is perfect.</p><h4>i. Logistic regression</h4><p>The predicted probability is P(death = yes), so a probability of 0.5 or more must map to `yes`, exactly as on the training sample.</p><pre>library(caret)<br>library(pROC)<br><br>ProbQ6_teste    &lt;- predict(RegLogQ6, hrt6_teste, type = &quot;response&quot;)<br>ClassesQ6_teste &lt;- factor(ifelse(ProbQ6_teste &gt;= 0.5, &quot;yes&quot;, &quot;no&quot;),<br>                          levels = c(&quot;no&quot;, &quot;yes&quot;))<br><br>confusionMatrix(ClassesQ6_teste, hrt6_teste$VN, positive = &quot;yes&quot;)<br><br>roc_rl &lt;- roc(hrt6_teste$VN, ProbQ6_teste, levels = c(&quot;no&quot;, &quot;yes&quot;))<br>plot(roc_rl, print.auc = TRUE, col = 2,<br>     main = &quot;ROC curve: binomial logistic regression&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*NBn9PFo_XgLT5r2aEPJqCw.png" /></figure><h4>j. LDA</h4><p>For the ROC curve we use the posterior probability of ‘yes’, selected by name to avoid mixing up the columns.</p><pre>lda6_teste &lt;- predict(lda6, hrt6_teste)<br>confusionMatrix(lda6_teste$class, hrt6_teste$VN, positive = &quot;yes&quot;)<br><br>roc_lda &lt;- roc(hrt6_teste$VN, lda6_teste$posterior[, &quot;yes&quot;],<br>               levels = c(&quot;no&quot;, &quot;yes&quot;))<br>plot(roc_lda, print.auc = TRUE, col = 3, main = &quot;ROC curve: LDA&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*jlq4QvPyBH9-5Qjpcig5Yg.png" /></figure><h4>k. QDA</h4><pre>qda6_teste &lt;- predict(qda6, hrt6_teste)<br>confusionMatrix(qda6_teste$class, hrt6_teste$VN, positive = &quot;yes&quot;)<br><br>roc_qda &lt;- roc(hrt6_teste$VN, qda6_teste$posterior[, &quot;yes&quot;],<br>               levels = c(&quot;no&quot;, &quot;yes&quot;))<br>plot(roc_qda, print.auc = TRUE, col = 4, main = &quot;ROC curve: QDA&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*e1wjEjk4y2RKXs7fieJzsg.png" /></figure><h4>l. Comparing the three classifiers</h4><p>Plotting the three curves together makes the comparison easier to see.</p><pre>library(pROC)<br><br># One ROC object per model, all using P(death = yes)<br>roc_rl  &lt;- roc(hrt6_teste$VN, ProbQ6_teste,<br>               levels = c(&quot;no&quot;, &quot;yes&quot;), direction = &quot;&lt;&quot;)<br>roc_lda &lt;- roc(hrt6_teste$VN, lda6_teste$posterior[, &quot;yes&quot;],<br>               levels = c(&quot;no&quot;, &quot;yes&quot;), direction = &quot;&lt;&quot;)<br>roc_qda &lt;- roc(hrt6_teste$VN, qda6_teste$posterior[, &quot;yes&quot;],<br>               levels = c(&quot;no&quot;, &quot;yes&quot;), direction = &quot;&lt;&quot;)<br><br>plot(roc_rl, col = 2, lwd = 2, asp = NA,<br>     main = &quot;ROC curves on the test sample&quot;)<br>plot(roc_lda, col = 3, lwd = 2, add = TRUE)<br>plot(roc_qda, col = 4, lwd = 2, add = TRUE)<br>legend(&quot;bottomright&quot;,<br>       legend = c(paste(&quot;Logistic, AUC =&quot;, round(auc(roc_rl), 3)),<br>                  paste(&quot;LDA, AUC =&quot;,      round(auc(roc_lda), 3)),<br>                  paste(&quot;QDA, AUC =&quot;,      round(auc(roc_qda), 3))),<br>       col = c(2, 3, 4), lwd = 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*-8cVXdY_Z6PYmMsrvr6fUw.png" /></figure><p>The logistic and LDA curves almost overlap and rise steeply on the left side of the plot. That is the region that matters most in practice, where few survivors are wrongly flagged: keeping specificity around 0.85, both models detect roughly 75% to 80% of the deaths. The QDA curve stays below them over most of the range. At that same specificity, it detects only about half of the deaths.</p><p>All three curves reach full sensitivity only when specificity drops to about 0.5. In other words, catching every death would mean flagging half of the survivors as well, a reminder that no model here separates the two groups perfectly.</p><pre>Model                 Accuracy   Sensitivity   Specificity   Kappa   AUC<br>-------------------   --------   -----------   -----------   -----   -----<br>LDA                   0.817      0.824         0.814         0.585   0.885<br>Logistic regression   0.733      0.824         0.698         0.443   0.871<br>QDA                   0.700      0.529         0.767         0.287   0.751</pre><p>LDA performed best on every measure: it identified 14 of the 17 deaths and 35 of the 43 survivors. Logistic regression detected the same 14 deaths but raised more false alarms (13 survivors classified as deaths). QDA was clearly weaker, missing 8 of the 17 deaths.</p><p>This is a useful twist. Box’s M test rejected equal covariances, which favours QDA in theory. But QDA must estimate a separate covariance matrix for each class, with 12 variables and only 79 distinct deaths behind the oversampled class. The simpler LDA generalised better to new patients despite its violated assumptions.</p><p>A word of caution about time. It records the length of follow-up, and patients who died naturally have shorter follow-up periods. The variable therefore partly reflects the outcome itself and is not known when a patient is first assessed. It boosts the scores here, but a model meant for real clinical use should be tested without it.</p><h3>III. Conclusions</h3><p>Across the three parts, this dataset resisted most multivariate techniques, and that turned out to be the most instructive result. Classification worked much better than the earlier techniques: LDA reached 81.7% accuracy and an AUC of 0.885 on the test sample.</p><ul><li><strong>Exploratory analysis</strong> (<a href="https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-1-of-3-bce77a7cb31c">Part 1</a>): the variables were weakly correlated, not multivariate normal, and had different covariance structures in each class.</li><li><strong>Factor analysis</strong> (<a href="https://medium.com/p/102defac2281/edit">Part 2</a>): the KMO index of 0.55 showed there was little common structure to summarise into factors.</li><li><strong>Cluster analysis</strong> (<a href="https://medium.com/p/102defac2281/edit">Part 2</a>): the clusters found by the data did not match survival and death.</li><li>Linear regression (<a href="https://medium.com/p/8210a695f64f/edit">Part 3</a>): the other variables explain only about 3% of the variance in ejection fraction, with a test RMSE of 11.5 points.</li><li><strong>Classificatio</strong>n (<a href="https://medium.com/p/8210a695f64f/edit">Part 3</a>): LDA was the best classifier (accuracy 81.7%, AUC 0.885), followed by logistic regression (73.3%, AUC 0.871) and QDA (70.0%, AUC 0.751).</li></ul><p>Three lessons stand out. First, no single criterion decides whether a model is good: KMO, RMSEA, AIC, accuracy and AUC each tell part of the story. Second, assumptions matter: when Box’s M rejected equal covariances, QDA and logistic regression became the more defensible choices. Third, always check what a variable really measures, as the follow-up ‘time’ showed.</p><p>At first I thought I had picked the wrong dataset. In the end, a dataset that does not fit the textbook taught me far more than a tidy one would have.</p><p>Thanks for reading! If you have questions or suggestions, feel free to connect with me on <a href="https://www.linkedin.com/in/paulorsoliveira">LinkedIn</a>.</p><p><strong>References:</strong></p><p>1. Hair, J. F., Black, W. C., et al. *Multivariate Data Analysis*, 6th ed. Bookman, 2009.<br>2. Zelterman, D. *Applied Multivariate Statistics with R*. Statistics for Biology and Health. Springer, 2015.<br>3. Venables, W. N., Ripley, B. D. *Modern Applied Statistics with S*, 4th ed. Springer, 2002. [MASS package](<a href="http://www.stats.ox.ac.uk/pub/MASS4/">http://www.stats.ox.ac.uk/pub/MASS4/</a>)<br>4. Chicco, D., Jurman, G. Machine learning can predict survival of patients with heart failure from serum creatinine and ejection fraction alone. *BMC Medical Informatics and Decision Making*, 2020. [Article](<a href="https://bmcmedinformdecismak.biomedcentral.com/articles/10.1186/s12911-020-1023-5">https://bmcmedinformdecismak.biomedcentral.com/articles/10.1186/s12911-020-1023-5</a>)<br>5. Ahmad, T., et al. Survival analysis of heart failure patients: a case study. *PLOS ONE*, 2017. [Article](<a href="https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0181001">https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0181001</a>)<br>6. Heart failure clinical records dataset. [UCI Machine Learning Repository](<a href="https://archive.ics.uci.edu/ml/datasets/Heart+failure+clinical+records">https://archive.ics.uci.edu/ml/datasets/Heart+failure+clinical+records</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8210a695f64f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Short-Term Electricity Consumption on University Campuses (3)]]></title>
            <link>https://medium.com/@proberto3122/forecasting-short-term-electricity-consumption-on-university-campuses-3-8eeec2082bc1?source=rss-7afebe988e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eeec2082bc1</guid>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[energy-forecasting]]></category>
            <category><![CDATA[computational-learning]]></category>
            <dc:creator><![CDATA[Paulo R S Oliveira]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 19:26:01 GMT</pubDate>
            <atom:updated>2026-10-08T19:26:01.454Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Part 3 of 3: machine learning, neural networks, and the final verdict</em></strong></p><p>In <a href="https://medium.com/p/59e0b96b7c76/edit">Part 2</a>, the best statistical model, a SARIMAX with cross-validation, reached a MAPE of 8.38% when forecasting next-day electricity consumption at a university campus in Southern Europe. In this final Part, I test KNN, XGBoost, and three types of neural networks (MLP, LSTM, and GRU), explain why I evaluated each network over 600 independent training runs, and compare all the models to see what really makes a difference.*</p><p><strong>Preparing the data for models that don’t understand time</strong></p><p>Algorithms like KNN and XGBoost were not designed for time series: they have no notion of order or memory. To use them, the series has to be reshaped into a table in which each row contains everything the model needs to see at once.</p><p>Each sample became the consumption over the last 7 or 14 days (the window called <strong><em>days back</em></strong>), optionally along with the exogenous variables for those days, with the next day’s consumption as the target. I did this transformation with the “lagmat()” function from “statsmodels”.</p><p>For these models I split the data into three blocks: the first 1,792 days for training, the following 404 days for validation and, as in <a href="https://medium.com/p/59e0b96b7c76/edit">Part 2</a>, the last 365 days for testing. Min-max normalization was computed on the training data only, to avoid leaking information from the future into the model, and the metrics were always calculated after denormalizing the forecasts.</p><p><strong>KNN: simple and surprisingly honest</strong></p><p>KNN (<em>k-Nearest Neighbors</em>) predicts tomorrow’s consumption by searching the history for the windows most similar to the current one and averaging what happened next. It makes no assumptions about the distribution of the data, which helps with a series that, as we saw, is far from normal [2].</p><p>I tested 72 combinations: 7- and 14-day windows, k ∈ {7, 14, 21, 28} neighbors, and several combinations of exogenous variables. The best model used a 7-day window, 7 neighbors, and the Sunday variable, with a MAPE of 10.96% and an RMSE of 804 kWh. Without Sunday, the MAPE rose to 11.52%.</p><p>Two patterns became clear: the smaller the window and the number of neighbors, the better the result, showing that the recent past is the most informative; and Sunday appeared in all the best models, regardless of the configuration.</p><p><strong>XGBoost: the unexpected effect of normalization</strong></p><p>XGBoost builds decision trees in sequence, each one correcting the errors of the previous ones. It has many hyperparameters, so I used Optuna [1] to tune them automatically.</p><p>I tested the models with and without normalization, and the result was curious. Using consumption alone, normalization made things worse: the best model, with data on the original scale and a 14-day window, reached a MAPE of 10.08%. With the exogenous variables, the opposite happened: the best model used normalized data, a 7-day window, and all three exogenous variables, with a MAPE of 9.48% and an RMSE of 775 kWh.</p><p>Since tree-based models are, in theory, insensitive to the scale of the variables, the difference is probably due to the interaction between normalization and the hyperparameter search, rather than to any intrinsic need of the algorithm. The practical recommendation: it is worth testing both versions.</p><p><strong>Neural networks: MLP, LSTM, and GRU</strong></p><p>I tested three architectures:</p><p>- <strong>MLP</strong> (<em>Multilayer Perceptron</em>): a classic dense network with two hidden layers. It receives the window of days as a vector and has no notion of sequence whatsoever.<br>- <strong>LSTM</strong> (<em>Long Short-Term Memory</em>): a recurrent network with memory mechanisms designed precisely for sequences.<br>- <strong>GRU</strong> (<em>Gated Recurrent Unit</em>): a lighter variant of the LSTM, with fewer parameters.</p><p>All networks used ReLU activation in the hidden layers, a linear output with a single neuron, MSE loss, the RMSprop optimizer, up to 200 epochs, and early stopping with a patience of 20 epochs. Optuna chose the number of neurons, the batch size and, for the LSTM and GRU networks, the dropout rates. In total there were 40 configurations, combining architecture, window, variables, and the use or not of dropout.</p><p><strong>Why a single training run isn’t enough</strong></p><p>Neural networks have a random component: the weights are initialized differently in each run, and two runs with exactly the same hyperparameters can give quite different results. Comparing models based on a single run is therefore risky: you may simply be comparing luck.</p><p>For each of the 40 tuned configurations, I repeated training 600 times and analyzed the distribution of MAPE and how its standard deviation evolved (Figure 1). The standard deviation fluctuates considerably over the first 20 runs and stabilizes at around 200, which gives confidence that 600 runs are enough to characterize each model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86h1uOgXtJdp4-su5vAj7g.png" /><figcaption>Figure 1: Evolution of the standard deviation of MAPE across runs, for three models.</figcaption></figure><p>Figure 2 shows why this matters. Some models, such as the GRU with a 7-day window, have an enormous spread: they can land below 8% or above 14%. Others, such as the MLP, are consistent from one run to the next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJu3x2zl-MFpATsCReXGaA.png" /><figcaption>Figure 2: MAPE over 600 runs per model, using consumption only (dp = dropout; 7d and 14d = 7- and 14-day window).</figcaption></figure><p><strong>Results with consumption only</strong></p><p>Using only the consumption history, the MLPs came out on top, with a MAPE of 7.70% (7-day window) and 7.74% (14-day window). Even at this stage, without any exogenous variable, the neural networks already beat the best statistical model. Another pattern: for both LSTM and GRU, the versions without dropout always did better than the versions with dropout.</p><p><strong>Results with exogenous variables</strong></p><p>With the exogenous variables, the MLP stood out again (Table 1). The best model in the entire study uses a 7-day window, the Sunday variable, 154 neurons in the first layer, just 1 in the second, and a batch size of 13. Its MAPE was 6.86% and its RMSE 644 kWh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*6wPsd41ZhNAnEEMb0zcR4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRC8fTfZ0jFCU6LB5Vz0qg.png" /><figcaption>Figure 3: MAPE distribution of the MLP models with exogenous variables.</figcaption></figure><p>The distribution over 600 runs (Figure 3) confirms that this advantage is not down to chance: the MLP with Sunday and a 7-day window is clearly ahead of the rest.</p><p>The best LSTM, with a 14-day window and the Sunday variable, reached a MAPE of 7.41% and an RMSE of 697 kWh. The best GRU, with the same configuration, came in at 7.73%, but with a lower RMSE of 647 kWh. Visually, the LSTM recovered better from the Christmas-break drop in consumption than the GRU (Figures 4 and 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAa3gZiYQXR2_rvYMHaVVQ.png" /><figcaption>Figure 4: Best LSTM model over the test year.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AkHQjlxsBe1V7vAR7IMFQ.png" /><figcaption>Figure 5: Best GRU model over the test year.</figcaption></figure><h3>The verdict</h3><p>Table 2 brings together the best model of each type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*FJk32KwYputerJeRcJ7fbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYh0hvepIics_MXJyiRnpA.png" /><figcaption>Figure 6: The best model in the study: MLP with a 7-day window and the Sunday variable.</figcaption></figure><p>Only the neural networks got below 8% MAPE, and only the MLP below 7%. Compared with the best SARIMAX, the MLP reduced MAPE by about 18% (in relative terms), but RMSE by only about 2%. In other words, the MLP is more accurate day-to-day, but on the days with large errors, mostly at peaks and troughs and during abrupt regime changes, both approaches stumble in similar ways (Figure 6).</p><p>The most intriguing result is that the simplest network, with no notion of sequence at all, beat the LSTM and GRU networks, which were designed specifically for time series. With daily data and short windows of 7 or 14 values, the long-term memory of recurrent networks seems to add little, and a well-tuned dense network is more than enough.</p><p><strong>What really made the difference</strong></p><p><strong><em>Sunday mattered more than temperature</em></strong>. The Sunday variable appeared in all the best models. It makes sense: on Sundays the buildings are closed and consumption drops sharply, and telling the model so explicitly saves it the work of figuring it out.</p><p>Temperature was the big disappointment. Models that used it as the only exogenous variable did worse than those that did not use it. There are two plausible explanations. First, the rhythms are different: temperature follows a smooth annual cycle, while consumption is driven by the weekly cycle and the academic calendar. Second, heating on this campus relies mainly on natural gas, so temperature affects electricity consumption less than it would in an electrically heated building.</p><p>Holidays helped little, probably because they are rare: 89 days in seven years are too few examples for a model to learn from.</p><p><strong><em>Short windows are enough</em></strong>. The 7-day window appeared in most of the best models, including the winner. That is consistent with the weekly autocorrelation identified in <a href="https://medium.com/p/e19f1af44983/edit">Part 1</a>: one week of history captures the essence of the pattern.</p><p><strong>Limitations</strong></p><p>There are factors none of these models knows about: actual building occupancy, user habits, construction characteristics, installed equipment. The pandemic also showed how a regime change can make the past a poor guide. And every model struggled with academic breaks, which are predictable on the calendar but invisible in the consumption data.</p><p><strong>Next steps</strong></p><p>A few ideas for taking this work further:</p><p>- Include the academic calendar (classes, exams, breaks) as an exogenous variable, which should directly address the models’ main weakness.<br>- Test “similar days” approaches, for example forecasting next Tuesday from the last n Tuesdays, as well as dedicated models for holidays.<br>- Try an 8-day window, which showed promise in exploratory tests with Optuna.<br>- Forecast consumption per building and, ideally, broken down by end use: lighting, HVAC, and equipment.<br>- Extend the approach to gas and water.</p><h4><strong>Conclusion</strong></h4><p>Over this series, we started from seven years of quarter-hourly measurements at a university campus and arrived at a model that forecasts next-day consumption with an average error below 7%. Along the way, a few lessons emerged that go beyond this case: data cleaning deserves attention down to details like daylight saving time; how you evaluate a model matters as much as the model itself; with neural networks, a single training run is not enough to draw conclusions; and the most useful variable was also the simplest one: knowing whether tomorrow is a Sunday.</p><p>Thanks for reading! If you have questions or suggestions, feel free to connect with me on <a href="https://www.linkedin.com/in/paulorsoliveira">LinkedIn</a>.</p><p><strong>References:</strong></p><p>[1] T. Akiba et al., “Optuna: A Next-generation Hyperparameter Optimization Framework,” in *Proceedings of the 25th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining*, 2019.</p><p>[2] J. Korstanje, *Advanced Forecasting with Python*, Apress, 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eeec2082bc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Short-Term Electricity Consumption on University Campuses (2)]]></title>
            <link>https://medium.com/@proberto3122/forecasting-short-term-electricity-consumption-on-university-campuses-2-59e0b96b7c76?source=rss-7afebe988e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/59e0b96b7c76</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[statistical-forecasting]]></category>
            <category><![CDATA[auto-arima]]></category>
            <category><![CDATA[crossvalidation]]></category>
            <dc:creator><![CDATA[Paulo R S Oliveira]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 17:06:01 GMT</pubDate>
            <atom:updated>2026-10-07T17:06:01.946Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Part 2 of 3: SARIMA, SARIMAX, and the power of cross-validation</em></strong></p><p>In <a href="https://medium.com/p/e19f1af44983/edit">Part 1</a>, we saw that daily electricity consumption at a university campus in Southern Europe has a very strong weekly cycle, drops linked to the pandemic and to academic breaks, and a weak relationship with temperature. In this second Part, I build statistical models from the ARIMA family, analyze their residuals, and show how time series cross-validation turned mediocre models into some of the best in the study.</p><p><strong>Training and testing</strong></p><p>The models in this part were trained on the first 2,196 days of the series and evaluated on the last 365 days, from November 2021 to October 2022. A full year of test data ensures the model is evaluated across every season and every period of the academic calendar, including breaks.</p><p><strong>A bit of background on SARIMA</strong></p><p>An ARIMA(p, d, q) model combines three ingredients: an autoregressive component (today’s value depends on the previous p values), differencing of order d (to make the series stationary), and a moving average component (today’s value depends on the previous q errors). SARIMA adds a second layer with the same ingredients for the seasonal pattern, with period m, and is written SARIMA(p, d, q)(P, D, Q)ₘ. SARIMAX goes one step further and accepts exogenous variables, such as temperature or Sunday and holiday indicators [1, 2].</p><p>Since the exploratory analysis showed autocorrelation at every multiple of 7, I always used m = 7.</p><p><strong>Finding the parameters automatically</strong></p><p>Tuning seven parameters by hand is slow and error-prone. I used two automated approaches:</p><p>- the “auto_arima()” function from the “pmdarima” library, which runs a stepwise search guided by the Akaike Information Criterion (AIC) [3];<br>- a grid search with “statsmodels”, “SARIMAX”, testing every combination of p, q, P, and Q within a range defined from the exploratory analysis and ranking them by AIC [4].</p><p>This was the “auto_arima()” configuration:</p><pre><br>import pmdarima as pmd<br>model = pmd.auto_arima(<br> train,<br> start_p=0, start_q=0, d=1,<br> max_p=8, max_q=8, max_d=3,<br> start_P=1, start_Q=1, D=1,<br> max_P=3, max_D=1, max_Q=3, max_order=5,<br> m=7, seasonal=True, test=&#39;adf&#39;,<br> stepwise=True, trace=True,<br> error_action=&#39;ignore&#39;, suppress_warnings=True<br>)</pre><p>The algorithm suggested a SARIMA(0,1,2)(1,1,2)₇, with a MAPE of 9.82% on the test set.</p><p><strong>Residuals tell the story the metrics hide</strong></p><p>A MAPE below 10% looks reasonable, but the residual analysis showed that the model was not capturing the full structure of the data. The residuals had a stable mean, but they were not normally distributed, and the correlogram showed autocorrelation at several lags.</p><p>The Ljung-Box test confirmed this formally: from lag 5 onward, every p-value fell below 0.01, rejecting the hypothesis that the residuals are independent. In practice, this means there was still a pattern left to model. The forecast plot told the same story: the model smoothed out the peaks and troughs in consumption.</p><p><strong>Comparing SARIMA models</strong></p><p>I built five more SARIMA models: two with small variations on the parameters suggested by “auto_arima()”, and three using the best combinations from the grid search (Table 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*emLOh3q3jKGGkTYmwfqDzw.png" /></figure><p>There is a curious detail here. The model with the lowest MAPE has an infinite AIC, meaning “auto_arima()” discarded it during the search, usually because of numerical problems when estimating the likelihood. I included it on purpose to see what would happen, and it ended up being the best in percentage terms. The lesson: <em>AIC is a useful selection criterion, not a final verdict. A model “rejected” by AIC can still forecast well, and the reverse is also true.</em></p><p>Note also that the model with the lowest MAPE is not the one with the lowest RMSE. The two metrics measure different things: MAPE treats every day equally in relative terms, while RMSE penalizes large errors more heavily, and those tend to happen on high-consumption days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oZwlD8MFPjQ6Nz02djqVQ.png" /><figcaption>Figure 1: Actual versus forecast values for the SARIMA(0,1,2)(1,1,2)₇ model suggested by auto_arima(), over the test year.</figcaption></figure><p>Figure 1 shows a pattern that repeated in almost every model in the study: the forecasts miss in the second half of December and the first half of January, when classes stop, and drift off again in April. A model that only looks at the recent past has no way of knowing that an academic break is coming.</p><p><strong>SARIMAX: more information, worse results?</strong></p><p>The logical next step was to add the exogenous variables. I combined temperature, Sunday, and holiday with the six parameter sets in Table 1, for a total of 30 models, and built another 15 with parameters suggested by a new grid search that already included the exogenous variables.</p><p>The result was surprising: no SARIMAX beat the best SARIMA. The best SARIMAX, with the holiday variable, only managed a MAPE of 12.29%, and the worst, with all three exogenous variables, reached a disastrous 64.95% (Table 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*gyBLKprnB3smF5EPRFqXng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wEjhsgWDSI0BLj0mcXMFw.png" /><figcaption>Figure 2: The best SARIMAX without cross-validation: the forecasts get stuck at a plateau and fail to follow the weekly oscillation.</figcaption></figure><p>Figure 2 offers a clue about what went wrong. With a single train-test split, the model is fitted once on data ending in October 2021 and has to forecast an entire year in one go. A plausible explanation is that the coefficients of the exogenous variables, estimated over a period that includes the pandemic, fail to adapt to the return to normal.</p><p><strong>The plot twist: cross-validation for time series</strong></p><p>With time series you cannot shuffle the data as in classical cross-validation: the future cannot be used to predict the past. I tested two techniques that respect the time order:</p><p>- <em>Expanding window (EW)</em>: the training set grows at each step, taking in the most recent observation, and the model always forecasts one step ahead.<br>- <em>Rolling window (RW):</em> the training set has a fixed size and slides forward over time, dropping the oldest observations as new ones come in [1].</p><p>In both cases the model is refitted regularly, which matches real-world use much more closely: in practice, whoever forecasts tomorrow’s consumption always has today’s consumption available.</p><p>I picked four representative models: the best and worst SARIMAX with all three exogenous variables, the best SARIMAX with a single exogenous variable, and the best SARIMA (Table 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*mUurf2PjZUnUs364wMdRrw.png" /></figure><p>The numbers speak for themselves. The SARIMAX that had a MAPE of 64.95% dropped to 8.84% with an expanding window, and its RMSE fell from 3,833 to 679 kWh. The best statistical MAPE in the study, 8.38%, came from the SARIMAX with all three exogenous variables and a rolling window; the best RMSE, 647 kWh, came from the SARIMAX with the holiday variable and an expanding window, with a virtually identical MAPE (8.39%).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdFzITLePn07PIDo0OMIyA.png" /><figcaption>Figure 3: The SARIMAX that had a MAPE of 64.95%, now with an expanding window.</figcaption></figure><p>Interestingly, the SARIMA without exogenous variables got slightly worse with cross-validation. The most plausible interpretation is that exogenous variables only become useful when the model can recalibrate their coefficients with recent data. Without refitting, the extra information turns into noise; with refitting, it helps the model follow the weekly dynamics (Figure 3).</p><p>Even so, the Christmas break remains a weak spot: daily refitting helps the model recover faster, but it does not anticipate the drop.</p><p><strong>Takeaways from this stage</strong></p><p>- Automated selection functions save a lot of time, but AIC should not be the only criterion. A model with an infinite AIC turned out to be the best SARIMA.<br>- Residual analysis is essential: an acceptable MAPE can hide structure that has not been modeled.<br>- Adding exogenous variables does not automatically improve a model. Without cross-validation, it made every SARIMAX tested worse.<br>- How you evaluate matters as much as the model itself. Time series cross-validation took the best statistical model from 9.36% to 8.38% MAPE and cut RMSE by about 15%.</p><p>In <a href="https://medium.com/p/8eeec2082bc1/edit"><strong>Part 3</strong></a>, KNN, XGBoost, and the MLP, LSTM, and GRU neural networks enter the scene. <strong><em>Can they beat 8.38%?</em></strong></p><p>Thanks for reading! If you have questions or suggestions, feel free to connect with me on <a href="https://www.linkedin.com/in/paulorsoliveira">LinkedIn</a>.</p><p><strong>References:</strong></p><p>[1] R. J. Hyndman and G. Athanasopoulos, *Forecasting: Principles and Practice*, 3rd ed., OTexts. <a href="https://otexts.com/fpp3/">https://otexts.com/fpp3/</a></p><p>[2] M. Peixeiro, *Time Series Forecasting in Python*, Manning, 2022.</p><p>[3] pmdarima, `auto_arima` documentation. <a href="https://alkaline-ml.com/pmdarima/">https://alkaline-ml.com/pmdarima/</a></p><p>[4] statsmodels, `SARIMAX` documentation. <a href="https://www.statsmodels.org/">https://www.statsmodels.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59e0b96b7c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heart Disease — Multivariate Analysis with R (Part 2 of 3)]]></title>
            <link>https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-2-of-3-102defac2281?source=rss-7afebe988e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/102defac2281</guid>
            <category><![CDATA[factor-analysis]]></category>
            <category><![CDATA[dendrogram]]></category>
            <category><![CDATA[agglomerative-clustering]]></category>
            <category><![CDATA[cluster-analysis]]></category>
            <category><![CDATA[cophenetic-correlation]]></category>
            <dc:creator><![CDATA[Paulo R S Oliveira]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 21:01:01 GMT</pubDate>
            <atom:updated>2026-10-05T21:01:01.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>Heart Disease — Multivariate Analysis with R (Part 2 of 3)</h3><p>This article is a continuation of Heart Disease — Multivariate Analysis with R.</p><p>In <a href="https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-1-of-3-bce77a7cb31c">Part 1</a>, among other things, we performed exploratory data analysis and visualized plots to comprehend the data&#39;s characteristics better.</p><p>This second article (Part 2 of 3) focuses on Factor Analysis and Clustering Analysis.</p><h3>I-<strong>Factor Analysis</strong>[1,2]</h3><p>The general purpose of factor analysis techniques is to find a way to condense (summarize) the information contained in several original variables into a smaller set of new composite dimensions or statistical variables (factors) with a minimum loss of information — that is, to seek to define the fundamental constructs or dimensions assumed to be inherent to the original variables, being able to achieve their objectives either from an exploratory perspective or from a confirmatory perspective[1].</p><p>The main objective of this work is to apply exploratory factor analysis techniques to identify the factors associated with all quantitative variables in the dataset. The use of factor analysis in a dataset seeks to explain the correlation between the observable variables, simplifying data by reducing the number of variables necessary to describe them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WuouOhtwNwQ9pXSG" /><figcaption>Photo by <a href="https://unsplash.com/@george_tasios?utm_source=medium&amp;utm_medium=referral">George Tasios</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>a. Checking whether the application of exploratory factor analysis is appropriate to the variables.</strong></h4><p>Let’s obtain a table with correlations (rounded up to 3 decimal places) and then plots where we can view the appropriate information.</p><pre>round(cor(hrtfail[,c(5:13)]),3)<br>{r, fig.width=14, fig.height=10, fig.align=&#39;center&#39;, <br>message=FALSE, warning=FALSE}<br>chart.Correlation(hrtfail[,c(5:13)], histogram = T)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*O386xio8YS5Mf5xSqA5jog.png" /></figure><pre><br>ggcorrplot(cor(hrtfail[,c(5:13)]), hc.order = T,<br>           <br>           type=&#39;lower&#39;,<br>           <br>           lab=T, title = &#39;Correlation Matrix&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*tYjhC-swAuBd77o137ui1w.png" /></figure><p>The correlation matrix measures the linear association between the variables through Pearson’s linear correlation coefficient. If the correlations between the variables are small, they are less likely to share common factors.</p><p>Two tests must be carried out to verify the quality and adequacy of the correlations.</p><h4><strong>b. Bartlett’s sphericity test to check suitability</strong></h4><p>Hypothesis Testing:</p><p>H0: variables are not correlated</p><p>H1: at least two variables are correlated</p><p>Significance Level: 5%</p><pre><br>cortest.bartlett(hrtfail[,c(5:13)])<br><br>$chisq<br>[1] 93.61046<br><br>$p.value<br>[1] 5.072008e-07<br><br>$df<br>[1] 36</pre><p>Bartlett’s sphericity test allows evaluation of the presence of<br>correlations between variables. Since the p-value = 5.072008e-07 (less than Alpha of 0.05), we can reject H0 as there is statistical evidence that at least two variables are correlated.</p><h4><strong>c. Kaiser-Meyer-Olkin (KMO) test to check the quality of correlations</strong></h4><p>The KMO test (Kaiser-Meyer-Olkin) allows you to measure the quality<br>of the correlations between the variables and must be interpreted according to the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*uk1hni8gPEmuM857MT4oQw.png" /></figure><pre><br>KMO(hrtfail[,c(5:13)])<br><br>Kaiser-Meyer-Olkin factor adequacy<br>Call: KMO(r = hrtfail[, c(5:13)])<br>Overall MSA =  0.55<br>MSA for each item = <br>                      VQ                      age                  anaemia <br>                    0.50                     0.61                     0.53 <br>creatinine_phosphokinase         serum_creatinine      high_blood_pressure <br>                    0.47                     0.59                     0.54 <br>               platelets             serum_sodium                     time <br>                    0.57                     0.52                     0.56 </pre><p>The Overall MSA of 0.55 indicates that we have poor quality correlations when it comes to factor analysis. Therefore, the variables have little information that provides a good contribution to the division into components.</p><p>We can check whether there is an improvement in KMO by removing the two variables with the lowest MSA index. In the case ‘VQ’-ejection_fraction with 0.50 and ‘creatinine_phosphokinase’ with 0.47.</p><pre>names(hrtfail)<br><br>KMO(hrtfail[,c(6:7, 9:13)])<br><br>Kaiser-Meyer-Olkin factor adequacy<br>Call: KMO(r = hrtfail[, c(6:7, 9:13)])<br>Overall MSA =  0.58<br>MSA for each item = <br>                age             anaemia    serum_creatinine high_blood_pressure <br>               0.63                0.59                0.59                0.55 <br>          platelets        serum_sodium                time <br>               0.56                0.54                0.58 <br></pre><p>With the overall MSA of 0.58, we can still consider the correlations to be of poor quality.</p><p>We can therefore conclude that the indices, tests, correlations, and graphs above inform us that an application of exploratory factor analysis is <strong>not suitable</strong> for this dataset.</p><h4><strong>d. Identifying the number of factors associated with the variables</strong></h4><p>fa.parallel(hrtfail[,c(6:7, 9:13)],fm=c(&#39;ml&#39;), fa=c(&#39;fa&#39;))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*4_V92bkyTtE0cWGn8img4g.png" /></figure><p>Seeking understanding about the scree plot:</p><p>Parallel analysis compares the eigenvalues of our data with those obtained from random data of the same size. A factor is worth keeping only when its eigenvalue lies above the random one. As we can see in the plot above, no factor rises above that line, so fa.parallel suggests zero factors, confirming the poor quality identified in the KMO test.</p><h4><strong>e. Applying the </strong><strong>varimax rotation method and the obtained model diagram</strong></h4><p>Although parallel analysis suggests no factors, we will extract three factors for illustration to see how the method behaves on weakly correlated data.</p><pre>FA2 &lt;- fa(hrtfail[,c(6:7, 9:13)], nfactors= 3,rotate=c(&quot;varimax&quot;), <br>          fm =&quot;ml&quot;)<br><br>FA2$loadings<br><br>&gt;<br>Loadings:<br>                    ML1    ML2    ML3   <br>age                         0.435       <br>anaemia                     0.243       <br>serum_creatinine    -0.170  0.315 -0.147<br>high_blood_pressure         0.200  0.430<br>platelets                          0.157<br>serum_sodium         0.993              <br>time                       -0.526 -0.217<br><br>                 ML1   ML2   ML3<br>SS loadings    1.030 0.673 0.287<br>Proportion Var 0.147 0.096 0.041<br>Cumulative Var 0.147 0.243 0.284<br> </pre><p>Building and viewing the diagram:<br>fa.diagram(FA2)</p><p>The diagram shows each factor as a circle and each variable as a rectangle. Arrows link each variable to the factor on which it loads most strongly, labelled with the loading; loadings below 0.3 are hidden by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*Er6y4mNfG9HOQphT7f8aHQ.png" /></figure><p>Note that in the case of the variables under analysis in this work, the application of the ‘fa’ function together with the ‘varimax’ rotation method generated the factor loadings and ‘distributed’ the variables across the 3 factors, leaving two variables without ‘allocation’ and two factors with only one variable.</p><p>Let’s take a look at the biplot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*HGwbNKknPdZ62qovRAtufA.png" /></figure><p>The biplot graph above combines various information and provides us with a visualization of the distribution of factors across variables as well as the contribution of the variables.</p><h4><strong>f. Using RMSEA and the Tucker-Lewis Index to analyze the model obtained.</strong></h4><p>Model validation is classified according to the Table below:</p><pre>Index    Good       Reasonable       Bad<br>------   --------   --------------   --------<br>RMSEA    &lt; 0.05     0.05 to 0.10     &gt; 0.10<br>TLI      &gt; 0.90 (the higher the better)</pre><pre>print(FA2)<br><br>Factor Analysis using method =  ml<br>Call: fa(r = hrtfail[, c(6:7, 9:13)], nfactors = 3, rotate = c(&quot;varimax&quot;), <br>    fm = &quot;ml&quot;)<br>Standardized loadings (pattern matrix) based upon correlation matrix<br>                      ML1   ML2   ML3    h2    u2 com<br>age                 -0.04  0.44 -0.01 0.191 0.809 1.0<br>anaemia              0.05  0.24  0.00 0.061 0.939 1.1<br>serum_creatinine    -0.17  0.31 -0.15 0.150 0.850 2.0<br>high_blood_pressure  0.00  0.20  0.43 0.225 0.775 1.4<br>platelets            0.05 -0.09  0.16 0.035 0.965 1.8<br>serum_sodium         0.99 -0.02  0.09 0.995 0.005 1.0<br>time                 0.10 -0.53 -0.22 0.334 0.666 1.4<br><br>                       ML1  ML2  ML3<br>SS loadings           1.03 0.67 0.29<br>Proportion Var        0.15 0.10 0.04<br>Cumulative Var        0.15 0.24 0.28<br>Proportion Explained  0.52 0.34 0.14<br>Cumulative Proportion 0.52 0.86 1.00<br><br>Mean item complexity =  1.4<br>Test of the hypothesis that 3 factors are sufficient.<br><br>df null model =  21  with the objective function =  0.22 with Chi Square =  64.08<br>df of  the model are 3  and the objective function was  0 <br><br>The root mean square of the residuals (RMSR) is  0.01 <br>The df corrected root mean square of the residuals is  0.03 <br><br>The harmonic n.obs is  299 with the empirical chi square  1.44  with prob &lt;  0.7 <br>The total n.obs was  299  with Likelihood Chi Square =  0.93  with prob &lt;  0.82 <br><br>Tucker Lewis Index of factoring reliability =  1.34<br>RMSEA index =  0  and the 90 % confidence intervals are  0 0.059<br>BIC =  -16.17<br>Fit based upon off diagonal values = 0.99<br>Measures of factor score adequacy             <br>                                                   ML1   ML2   ML3<br>Correlation of (regression) scores with factors   0.99  0.68  0.51<br>Multiple R square of scores with factors          0.99  0.46  0.26<br>Minimum correlation of possible factor scores     0.98 -0.08 -0.49</pre><p>At first sight, the fit indices look excellent: RMSEA = 0 (90% CI: 0 to 0.059) and TLI = 1.34. However, they must be read with care. A TLI above 1 and a null RMSEA usually appear when there is very little correlation for the model to reproduce: with such weak correlations, almost any model “fits”. The factors confirm this, as together they explain only 28% of the variance, and two of them rest on a single variable each.</p><p>This is a good example of why a model should never be accepted or rejected on a single criterion. Taken together, the KMO index, parallel analysis, explained variance and loadings all point the same way: exploratory factor analysis is not appropriate for this dataset.</p><h4><strong>g. Analyzing internal consistency</strong></h4><p>Evaluated by the Cronbach test — or Cronbach’s Alpha — it allows determining the lower limit of the internal consistency of a group of variables.</p><pre><br>alpha(hrtfail[,5:13], check.keys = TRUE)<br><br>Reliability analysis   <br>Call: alpha(x = hrtfail[, 5:13], check.keys = TRUE)<br><br>  raw_alpha std.alpha G6(smc) average_r    S/N    ase   mean    sd median_r<br>   0.00061    -0.081 -0.0015   -0.0084 -0.075 0.0013 442869 10871    0.017<br><br>    95% confidence boundaries <br>         lower alpha upper<br>Feldt    -0.18     0  0.16<br>Duhachek  0.00     0  0.00<br><br>Reliability if an item is dropped:<br>                          raw_alpha std.alpha G6(smc) average_r     S/N alpha se<br>VQ-                         6.0e-04   -0.2230 -0.1196  -0.02333 -0.1824  0.00132<br>age                         6.0e-04   -0.0924 -0.0206  -0.01069 -0.0846  0.00131<br>anaemia                     6.1e-04   -0.0534  0.0141  -0.00637 -0.0507  0.00131<br>creatinine_phosphokinase-   6.1e-05    0.0074  0.0660   0.00093  0.0075  0.00011<br>serum_creatinine            6.1e-04   -0.0298  0.0334  -0.00363 -0.0290  0.00131<br>high_blood_pressure         6.2e-04   -0.0839 -0.0073  -0.00977 -0.0774  0.00131<br>platelets-                  1.0e-03   -0.1216 -0.0285  -0.01373 -0.1084  0.01126<br>serum_sodium-               6.1e-04   -0.1752 -0.0910  -0.01899 -0.1491  0.00131<br>time-                       6.0e-04    0.0743  0.1077   0.00993  0.0802  0.00131<br>                           var.r    med.r<br>VQ-                       0.0102 -0.00714<br>age                       0.0084  0.01748<br>anaemia                   0.0097  0.00279<br>creatinine_phosphokinase- 0.0104  0.03433<br>serum_creatinine          0.0092  0.02801<br>high_blood_pressure       0.0102  0.00058<br>platelets-                0.0116  0.00976<br>serum_sodium-             0.0089 -0.00714<br>time-                     0.0071  0.02801<br><br>Item statistics <br>                            n  raw.r std.r r.cor r.drop    mean      sd<br>VQ-                       299  0.072  0.47   NaN  0.072 8.5e+05 1.2e+01<br>age                       299  0.053  0.34   NaN  0.053 6.1e+01 1.2e+01<br>anaemia                   299  0.046  0.30   NaN  0.046 4.3e-01 5.0e-01<br>creatinine_phosphokinase- 299  0.034  0.23   NaN  0.024 8.5e+05 9.7e+02<br>serum_creatinine          299  0.042  0.28   NaN  0.041 1.4e+00 1.0e+00<br>high_blood_pressure       299 -0.049  0.34   NaN -0.049 3.5e-01 4.8e-01<br>platelets-                299  1.000  0.37   NaN  0.027 5.9e+05 9.8e+04<br>serum_sodium-             299  0.063  0.42   NaN  0.063 8.5e+05 4.4e+00<br>time-                     299  0.011  0.14   NaN  0.010 8.5e+05 7.8e+01<br><br><br></pre><p>We believe it is worth highlighting that the Cronbach’s Alpha index is a measure of internal consistency ranging from 0 to 1, where a value close to 1 indicates high internal consistency and a value close to 0 indicates low internal consistency. Values ​​greater than 0.7 are considered good, but values ​​greater than 0.8 are considered excellent. Values ​​less than 0.6 are considered low and indicate that the items are not measuring the same thing.</p><p>Furthermore, it is important to keep in mind that the Cronbach’s Alpha index is not a measure of the validity of the questionnaire or test, but rather of internal consistency and that other aspects such as validity, reliability, and precision need to be evaluated separately [1].</p><p>Therefore, when we apply the information above to the variable indices obtained using the ‘alpha’ function, we realize how bad the internal consistency of the data is.</p><p>Two remarks help to read this output. Cronbach’s alpha was designed for items of a scale, such as questionnaire questions meant to measure the same construct; clinical variables like age, platelets and serum sodium are not expected to measure one common thing, so a low alpha is expected. Also, because the variables are on very different scales, the standardized alpha (std.alpha = −0.08) is more meaningful than the raw alpha.</p><h3><strong>II-Clustering Analysis</strong>[1,2]</h3><p>Aims to group the data, individuals and variables, into clusters based on all quantitative variables. A clustering analysis aims to classify individuals (people, animals, companies, plants, etc.) according to similarity (or dissimilarity) criteria, without prejudices or pre-defined criteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BVx76bzuFYy7udu1" /><figcaption>Photo by <a href="https://unsplash.com/@tizianobrignoliphoto?utm_source=medium&amp;utm_medium=referral">Tiziano Brignoli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This technique seeks to group individuals based on their similarities, where each group (cluster) must:<br>a) be homogeneous → the individuals in the group must be similar;<br>b) have characteristics distinct from those of the other clusters → the individuals in a group must present distinct characteristics of individuals from the remaining groups.</p><h3>a. Standardizing the variables</h3><p>Clustering is a nonparametric method that arranges similar observations together, often in a graph that also reveals grouping patterns and outliers. It is called nonparametric because it assumes no underlying distribution or model [2].</p><p>Clustering relies on distances between patients, so the scale of each variable matters. Platelets are counted in the hundreds of thousands while serum creatinine is around 1, so without standardization the clusters would be driven almost entirely by the variables with the largest values.</p><p>We first build a data frame with the nine quantitative variables, then a standardized version in which every variable has mean 0 and standard deviation 1.</p><pre>library(cluster)</pre><pre>Dheartfail &lt;- as.data.frame(hrtfail[, c(5:13)])<br>sapply(Dheartfail, mean)<br>sapply(Dheartfail, sd)</pre><pre>SDhrtfail &lt;- as.data.frame(scale(hrtfail[, c(5:13)]))<br>sapply(SDhrtfail, mean)<br>sapply(SDhrtfail, sd)</pre><pre>                           Original data            Standardized data<br>Variable                   Mean         SD          Mean    SD<br>------------------------   ----------   ---------   -----   --<br>VQ (ejection_fraction)         38.08       11.83     0.00    1<br>age                            60.83       11.89     0.00    1<br>anaemia                         0.43        0.50     0.00    1<br>creatinine_phosphokinase      581.84      970.29     0.00    1<br>serum_creatinine                1.39        1.03     0.00    1<br>high_blood_pressure             0.35        0.48     0.00    1<br>platelets                 263,358.03   97,804.24     0.00    1<br>serum_sodium                  136.63        4.41     0.00    1<br>time                          130.26       77.61     0.00    1</pre><p>After standardization, R prints the means as tiny numbers such as -2.48e-17. These are just rounding errors of the computer: in practice, every mean is 0 and every standard deviation is 1.</p><p>The boxplots below show the effect of standardization.</p><pre>par(mfrow = c(1, 2))<br>boxplot(Dheartfail, main = &quot;Original Dataset&quot;,<br>        ylab = &quot;Range of Values&quot;, col = heat.colors(15))<br>boxplot(SDhrtfail, main = &quot;Standardized Dataset&quot;,<br>        ylab = &quot;Range of Values&quot;, col = heat.colors(15))<br>par(mfrow = c(1, 1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*Hb1FW3ENXGyCh97VuqLrdA.png" /></figure><p>In the original data, platelets dwarf every other variable; after standardization, all variables share the same scale.</p><h3>b. Clustering tendency</h3><p>Before looking for clusters, we check whether the data have any tendency to form groups at all. Any algorithm will return clusters, even on random data, so this step protects us from finding structure that is not there.</p><h4>Hopkins test</h4><p>The Hopkins statistic compares distances between real observations with distances from randomly generated points. Values close to 1 indicate clustered data, values around 0.5 indicate random data, and values close to 0 indicate uniformly spread data.</p><ul><li>H0: the data are uniformly distributed (no meaningful clusters).</li><li>H1: the data are not uniformly distributed (there are meaningful clusters).</li><li>Significance level: 5%.</li></ul><pre>library(hopkins)</pre><pre>set.seed(1234)<br>hopheart &lt;- hopkins(SDhrtfail)<br>hopheart<br>hopkins.pval(hopheart, n = 299)</pre><pre>[1] 0.9974848<br><br>[1] 0</pre><p>The p-value is 0, below 0.05, so we reject H0: the data show a tendency to form clusters.</p><h4>Ordered dissimilarity image</h4><p>The seriation package reorders the observations so that similar patients sit next to each other, then draws the distance matrix as an image (<a href="https://www.jstatsoft.org/article/view/v025i03">Hahsler et al., 2008</a>). Dark squares along the diagonal reveal groups of similar patients.</p><pre>library(seriation)</pre><pre>dishrt &lt;- dist(SDhrtfail)<br>dissplot(dishrt)<br>dissplot(dishrt, labels = as.integer(factor(hrtfail$VN)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Vq7O0DJVDczZ679vkibNSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*POzImidGBZo7M8eGSgu4Sw.png" /></figure><p>The shade of blue is proportional to the distance between two patients: dark when they are close, white when they are far apart. The second image orders the patients by death event, which lets us see whether the two classes form distinct blocks.</p><h3>c. Hierarchical methods</h3><p>Hierarchical methods build a tree of nested groups, drawn as a dendrogram. Agglomerative methods start with each patient alone and merge the closest groups step by step; divisive methods start with everyone together and split them.</p><h4>Agglomerative method: agnes</h4><p>We use agnes with Euclidean distance and Ward&#39;s method, which merges at each step the two groups that least increase the within-group variance. The argument stand = TRUE standardizes the variables internally.</p><pre>hrtaglom &lt;- agnes(Dheartfail, metric = &quot;euclidean&quot;,<br>                  method = &quot;ward&quot;, stand = TRUE)<br>hrtaglom$ac</pre><pre>pltree(hrtaglom, hang = -1, cex = 0.6, ylab = &quot;Height&quot;,<br>       xlab = &quot;Similarity Matrix&quot;,<br>       main = &quot;Dendrogram of the Heart Failure Dataset (agnes)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*9fqL57o1wLTyL51gPe4JuA.png" /></figure><p>The agglomerative coefficient is 0.94. Cutting the tree around height 25 suggests three clusters, so we draw the dendrogram with k = 3 and, for comparison, k = 4.</p><pre>plot(as.dendrogram(hrtaglom), ylab = &quot;Height&quot;,<br>     main = &quot;Heart Failure Dendrogram k = 3&quot;)<br>rect.hclust(hrtaglom, 3, border = &quot;red&quot;)</pre><pre>plot(as.dendrogram(hrtaglom), ylab = &quot;Height&quot;,<br>     main = &quot;Heart Failure Dendrogram k = 4&quot;)<br>rect.hclust(hrtaglom, 4, border = &quot;blue&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*NPrS5hoaH26P8m8uULrEMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Ba46nocOOKpwROK7FZXn8w.png" /></figure><p>To interpret the dendrograms, we cut the tree and compare the clusters’ sizes, averages and mortality.</p><pre>for (k in 3:4) {<br>  cl &lt;- cutree(as.hclust(hrtaglom), k)<br>  print(table(cl))<br>  print(aggregate(cbind(Dheartfail, died = as.numeric(hrtfail$VN) - 1),<br>                  list(cluster = cl), mean))<br>}</pre><pre>k = 3<br>Cluster   Patients   Main feature                             Mortality<br>-------   --------   --------------------------------------   ---------<br>A            252     close to the overall average             25%<br>B             41     serum creatinine 3.1, sodium 132,        76%<br>                     short follow-up (79 days)<br>C              6     creatinine phosphokinase ~5,900          50%<br><br>k = 4: cluster B splits into<br>B1            38     serum creatinine 2.7, sodium 132         74%<br>B2             3     serum creatinine 8.4                     100%</pre><p>The dendrogram does not divide the patients into groups of similar size. With k = 3, one large cluster holds 84% of the patients, while the other two gather patients with extreme values: cluster B those with impaired kidney function (high serum creatinine, low sodium), cluster C six patients with very high creatinine phosphokinase. Moving to k = 4 does not reveal a new profile; it only separates three patients with extreme serum creatinine, all of whom died.</p><p>This behaviour is typical of Ward’s method with Euclidean distance, which is sensitive to extreme values. Even so, the dendrogram tells a clinically coherent story: cluster B, defined by kidney markers, has three times the mortality of the large cluster, echoing the importance of serum creatinine highlighted in Part 1.</p><h4>Divisive method: diana</h4><p>For the divisive method, we use diana with the Manhattan distance, the sum of absolute differences, which is less sensitive to extreme values than the Euclidean distance.</p><pre>hrtdivis &lt;- diana(Dheartfail, metric = &quot;manhattan&quot;, stand = TRUE)<br>hrtdivis$dc</pre><pre>pltree(hrtdivis, cex = 0.6, hang = -1, ylab = &quot;Height&quot;,<br>       xlab = &quot;Similarity Matrix&quot;,<br>       main = &quot;Dendrogram of the Heart Failure Dataset (diana)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Ik4LXKbZ7wa6sCqdQALE7g.png" /></figure><p>The divisive coefficient is 0.88. Both coefficients look high, but they tend to grow with the number of observations, so on their own they say little about quality.</p><p>The biggest jumps in the diana tree happen at heights 42 and 34, after which the merges flatten out, so we again profile the solution with three clusters.</p><pre>cl_diana &lt;- cutree(as.hclust(hrtdivis), 3)<br>table(cl_diana)<br>aggregate(cbind(Dheartfail, died = as.numeric(hrtfail$VN) - 1),<br>          list(cluster = cl_diana), mean)<br><br># Agreement with the agnes solution<br>table(diana = cl_diana, agnes = cutree(as.hclust(hrtaglom), 3))</pre><pre>k = 3 (diana)<br>Cluster   Patients   Main feature                             Mortality<br>-------   --------   --------------------------------------   ---------<br>A            265     close to the overall average             31%<br>B             26     creatinine phosphokinase ~3,000          27%<br>C              8     serum creatinine 6.3, older (66.5),      75%<br>                     short follow-up (80 days)</pre><p>Being a top-down method, diana’s very first split, at height 42, separates just the 8 patients with the most extreme serum creatinine from everyone else. The second split then isolates 26 patients with high creatinine phosphokinase. Cutting at k = 4 adds nothing new: it only isolates a single patient.</p><p>The two hierarchical methods tell a similar story from different angles. Both find one large, average cluster plus two small groups defined by the same variables, kidney function and creatinine phosphokinase. They differ in how wide they draw these groups: agnes puts 41 patients in the kidney group and only 6 in the creatinine phosphokinase group, while diana keeps only the 8 most extreme kidney cases and widens the creatinine phosphokinase group to 26.</p><p>The mortality figures add a useful clinical note. The kidney group has high mortality in both methods (76% in agnes, 75% in diana), while the creatinine phosphokinase group’s mortality (27%) is no different from the large cluster. Extreme values of a variable create a cluster, but only some of those clusters matter for the outcome.</p><h3>d. Cophenetic correlation</h3><p>A dendrogram squeezes multidimensional distances into a two-dimensional tree, which inevitably distorts them. The cophenetic correlation measures that distortion: it correlates the original distances between patients with the distances implied by the tree. Values above 0.75 are considered good.</p><p>Each tree must be compared with the distance it was built on: Euclidean for agnes and Manhattan for diana.</p><pre>cor(daisy(Dheartfail, metric = &quot;euclidean&quot;, stand = TRUE),<br>    cophenetic(hrtaglom))</pre><pre>cor(daisy(Dheartfail, metric = &quot;manhattan&quot;, stand = TRUE),<br>    cophenetic(hrtdivis))</pre><pre>Method         Distance    Cophenetic correlation<br>------------   ---------   ----------------------<br>agnes (Ward)   Euclidean   0.53<br>diana          Manhattan   0.59</pre><p>Both values are well below 0.75, so neither dendrogram represents the original distances faithfully. Ward’s method usually scores lower on this measure, because it favours compact clusters over preserving every distance; even so, the result reinforces how weak the natural grouping in these data is.</p><h3>e. Non-hierarchical methods</h3><p>Non-hierarchical methods split the patients directly into a chosen number k of clusters. We use two: clara (k-medoids) and fanny (fuzzy clustering).</p><h4>k-medoids with clara</h4><p>A medoid is the real patient who best represents a cluster, which makes k-medoids more robust to outliers than k-means. clara applies it to samples of the data, so it scales well to larger datasets.</p><p>We first look for a sensible k with three criteria: the within-cluster sum of squares (wss), the average silhouette and the gap statistic.</p><pre>library(factoextra)</pre><pre>fviz_nbclust(SDhrtfail, clara, method = &quot;wss&quot;)<br>fviz_nbclust(SDhrtfail, clara, method = &quot;silhouette&quot;)<br>fviz_nbclust(SDhrtfail, clara, method = &quot;gap_stat&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*EJM4MEgFdB3MhPZPgzzb9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*cHF2gSP3FpvbzQxdQKxLfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*uE9eng2J_lfNB3loUgffCg.png" /></figure><p>The criteria do not agree. The wss curve has no clear elbow, the silhouette moves between 3 and 5 clusters, and the gap statistic points to 1 to 3. We therefore compare k = 2 and k = 3.</p><pre>hrt_clara2 &lt;- clara(Dheartfail, 2, metric = &quot;manhattan&quot;,<br>                    stand = TRUE, samples = 299)<br>hrt_clara3 &lt;- clara(Dheartfail, 3, metric = &quot;manhattan&quot;,<br>                    stand = TRUE, samples = 299)<br>hrt_clara2$medoids<br>hrt_clara3$medoids</pre><p>Each medoid is a real patient, so we can read it like a clinical record.</p><pre>k = 2 medoids<br>Cluster   VQ   age   anaemia   CPK   serum_creat.   HBP   platelets   sodium   time<br>-------   --   ---   -------   ---   ------------   ---   ---------   ------   ----<br>1         35    62      0      281       1.0         0     221,000      136     108<br>2         40    61      1       84       0.9         1     229,000      141     110<br><br>k = 3 medoids<br>1         35    65      0      198       0.9         1     281,000      137     146<br>2         30    65      0      582       1.3         0     249,000      136     212<br>3         40    63      1       61       1.1         0     221,000      140      86</pre><p>(CPK = creatinine phosphokinase; HBP = high blood pressure.)</p><p>The medoids look strikingly ordinary. Their continuous values are close to the dataset medians (ejection fraction 38, age 60, serum creatinine 1.1, sodium 137), and none of them died. What sets them apart is mainly the two binary variables: with k = 2, the first medoid has neither anaemia nor high blood pressure, while the second has both.</p><p>Crossing the clusters with these two variables confirms it:</p><pre>table(hrt_clara2$clustering,<br>      paste(hrtfail$anaemia, hrtfail$high_blood_pressure))</pre><ul><li><strong>k = 2</strong>: all 48 patients with both anaemia and high blood pressure fall in cluster 2, and all 113 with neither condition fall in cluster 1.</li><li><strong>k = 3</strong>: the clusters are practically “high blood pressure” (82 of 85 patients), “no anaemia, no high blood pressure” (93 of 109) and “anaemia” (88 of 105).</li></ul><p>In other words, clara is mostly sorting patients by two yes/no conditions. Once standardized, a 0/1 variable jumps by about two standard deviations between its only two values, a larger gap than most patients show on any continuous variable, so binary variables end up dominating the Manhattan distance. Since neither anaemia nor high blood pressure turns out to be a significant predictor of death (as the logistic regression in Part 3 will show), this also explains why the clara clusters turn out unrelated to the outcome in section: <em>‘Comparing the clusters with the death event’</em>, below.</p><p>To judge the two solutions we use two internal validation indices. The <strong>silhouette</strong> compares, for each patient, the distance to its own cluster with the distance to the nearest other cluster: close to 1 means well clustered, close to 0 means between two clusters, negative means probably misassigned (<a href="https://doi.org/10.1016/0377-0427(87)90125-7">Rousseeuw, 1987</a>). The <strong>Calinski-Harabasz</strong> index is the ratio of separation between clusters to cohesion within them; higher is better.</p><pre>library(clusterCrit)</pre><pre>fviz_silhouette(silhouette(hrt_clara2$clustering, dist(SDhrtfail)))<br>fviz_silhouette(silhouette(hrt_clara3$clustering, dist(SDhrtfail)))</pre><pre>intCriteria(as.matrix(SDhrtfail), hrt_clara2$clustering, &quot;Calinski_Harabasz&quot;)<br>intCriteria(as.matrix(SDhrtfail), hrt_clara3$clustering, &quot;Calinski_Harabasz&quot;)</pre><pre>fviz_cluster(hrt_clara2, SDhrtfail, ellipse.type = &quot;norm&quot;, labelsize = 8)<br>fviz_cluster(hrt_clara3, SDhrtfail, ellipse.type = &quot;norm&quot;, labelsize = 8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*5xSEs-si7KmSVnTJ2WQvTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*8IQ285vrKk9TeMK4YxD4Tw.png" /></figure><pre>Solution       Cluster sizes    Avg. silhouette   Calinski-Harabasz<br>------------   --------------   ---------------   -----------------<br>clara, k = 2   205, 94          0.09              25.7<br>clara, k = 3   85, 109, 105     0.10              26.8</pre><p>The two solutions are practically tied, and both silhouettes are close to 0, which means the clusters overlap heavily. In the cluster plot for k = 3, one cluster sits almost inside another, so we keep k = 2 as the simpler and more readable solution.</p><h4>Fuzzy clustering with fanny</h4><p>In fuzzy clustering each patient belongs to every cluster with a degree of membership between 0 and 1, instead of to a single cluster. This suits data like ours, where many patients lie between groups. The argument memb.exp = 1.2 controls how fuzzy the solution is; values closer to 1 give crisper memberships.</p><p>Dunn’s partition coefficient measures how crisp the memberships are. Its raw value ranges from 1/k to 1, so it naturally falls as k grows; the normalized version ranges from 0 (completely fuzzy) to 1 (completely crisp) and is the fairer one to compare across k.</p><pre>for (k in 2:5) {<br>  print(c(k, fanny(Dheartfail, k, memb.exp = 1.2, metric = &quot;euclidean&quot;,<br>                   stand = TRUE, maxit = 10000)$coeff))<br>}</pre><pre>k   Dunn&#39;s coefficient   Normalized<br>-   ------------------   ----------<br>2   0.517                0.034<br>3   0.359                0.038<br>4   0.288                0.050<br>5   0.248                0.060</pre><p>The normalized coefficient stays between 0.03 and 0.06 for every k. Memberships are almost evenly split between clusters, which is another sign that the groups are not well separated. We keep k = 2, in line with the other methods.</p><pre>hrt_fanny2 &lt;- fanny(Dheartfail, 2, memb.exp = 1.2,<br>                    metric = &quot;euclidean&quot;, stand = TRUE)<br>head(hrt_fanny2$membership)<br>hrt_fanny2$convergence</pre><pre>fviz_silhouette(silhouette(hrt_fanny2$clustering, dist(SDhrtfail)))<br>fviz_cluster(hrt_fanny2, SDhrtfail, main = &quot;Fuzzy Method Clusters&quot;,<br>             ellipse.type = &quot;norm&quot;, labelsize = 8)</pre><pre>head(hrt_fanny2$membership,5)<br>          [,1]      [,2]<br>[1,] 0.6603021 0.3396979<br>[2,] 0.5027724 0.4972276<br>[3,] 0.5950702 0.4049298<br>[4,] 0.5442447 0.4557553<br>[5,] 0.5696883 0.4303117<br><br><br>hrt_fanny2$convergence<br>iterations  converged      maxit <br>        87          1        500 <br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*Ql4By1gYr4-57VlOG2Zbxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*S9G_BJnftm_Fd4A-U5rX4Q.png" /></figure><p>The algorithm converged after 110 iterations. The two clusters have 147 and 152 patients, with an average silhouette of 0.11 and a Calinski-Harabasz index of 33.9, both slightly better than clara.</p><p>Some patients sit right on the border. Patient 2, for example, has memberships of 0.503 and 0.497, so assigning them to either cluster is almost arbitrary.</p><pre>hrt_fanny2$membership[c(2, 10, 200, 297), ]</pre><pre>Patient   Cluster   Membership 1   Membership 2   Died<br>-------   -------   ------------   ------------   ----<br>2         1         0.503          0.497          yes<br>10        1         0.542          0.458          yes<br>200       1         0.532          0.468          no<br>297       2         0.462          0.538          no</pre><p>The two plots, read together, show that the clusters are not equally solid.</p><p>In the silhouette plot, every patient in cluster 2 has a positive value (average 0.20): it is a compact group. Cluster 1 is the opposite: 65 of its 147 patients have negative silhouettes, meaning they sit closer to cluster 2 than to their own cluster, and its average is only 0.02. The cluster plot shows the same picture, with the red ellipse much wider than the blue one.</p><p>This fits what we found in section f. Cluster 1 is the higher-risk group, holding 78 of the 96 deaths, and sick patients tend to differ from the norm in different ways: one through kidney function, another through sodium, another through age. Cluster 2 gathers patients closer to the average, who naturally resemble each other more.</p><p>The points that escape the ellipses are patients with extreme values:</p><ul><li><strong>Patient 10</strong> (far left): 80 years old, serum creatinine 9.4 and died after only 10 days of follow-up.</li><li><strong>Patient 200</strong> (top): serum sodium of 113, far below the normal range.</li><li><strong>Patient 297</strong> (far right): platelets at 742,000 and creatinine phosphokinase of 2,060.</li><li><strong>Patient 2</strong> (top right) belongs to cluster 1 but appears among the blue patients, which matches its almost even memberships.</li></ul><p>The membership table holds a surprise: even these extreme patients have memberships close to 0.5. With such weak structure in the data, fanny splits almost every patient nearly evenly between the two clusters, echoing the low normalized Dunn’s coefficient. The cluster labels are useful for description, but they hide how fuzzy the boundary really is.</p><h3>f. Choosing the number of clusters</h3><p>Across methods and indices, two clusters was the most consistent choice:</p><ul><li><strong>clara</strong>: k = 2 and k = 3 were practically tied, and k = 3 produced one cluster nested inside another.</li><li><strong>fanny</strong>: k = 2 had the highest raw Dunn’s coefficient, and the normalized coefficient gave no reason to prefer more clusters.</li></ul><p>That said, every index points to weak, overlapping clusters. The choice of k = 2 is a matter of simplicity, not of strong evidence.</p><h3>g. Comparing the clusters with the death event</h3><p>The clusters were found without looking at VN, so a natural question is whether they match the two outcome groups. External validation measures answer it by comparing every pair of patients: do two patients in the same cluster also share the same outcome?</p><ul><li><strong>Rand index</strong>: share of pairs on which clusters and outcome agree (0 to 1).</li><li><strong>Fowlkes-Mallows index</strong>: geometric mean of precision and recall over pairs (0 to 1).</li><li><strong>Adjusted Rand Index (ARI)</strong>: the Rand index corrected for chance; 0 means no better than random grouping, 1 means perfect agreement.</li></ul><pre>library(clusterCrit)<br>library(aricode)</pre><pre>Classes &lt;- hrtfail$VN</pre><pre>for (cl in list(hrt_clara2$clustering, hrt_clara3$clustering,<br>                hrt_fanny2$clustering)) {<br>  print(table(as.integer(Classes), cl))<br>  print(extCriteria(as.integer(Classes), cl,<br>                    c(&quot;Precision&quot;, &quot;Recall&quot;, &quot;Folkes_Mallows&quot;, &quot;Rand&quot;)))<br>  print(ARI(Classes, cl))<br>}</pre><pre>Solution       Rand    Fowlkes-Mallows   ARI<br>------------   -----   ---------------   ------<br>fanny, k = 2   0.586   0.611              0.172<br>clara, k = 2   0.505   0.562             -0.007<br>clara, k = 3   0.482   0.437              0.006</pre><p>The clara clusters have an ARI of practically zero: they are unrelated to the outcome. The fanny clusters do better, and the contingency table shows why.</p><pre>fanny cluster   Survived   Died   Mortality<br>-------------   --------   ----   ---------<br>1                     69     78         53%<br>2                    134     18         12%</pre><p>Cluster 1 holds 78 of the 96 deaths. Comparing the cluster means, its patients are older (67 vs 54 years), have higher serum creatinine (1.75 vs 1.05 mg/dL), more high blood pressure (53% vs 18%) and much shorter follow-up (89 vs 170 days).</p><pre>aggregate(Dheartfail, list(cluster = hrt_fanny2$clustering), mean)</pre><p>This is the most interesting finding of the cluster analysis. Even with weak overall structure, the fuzzy method separated a higher-risk group without ever seeing the outcome. Part of the separation comes from follow-up time, which partly reflects the outcome itself, so it should be read with that in mind.</p><h3>h. Clustering the variables</h3><p>Cluster analysis can also group variables instead of patients. We transpose the standardized data, so each variable becomes a row, and apply hclust with Ward&#39;s method (ward.D2).</p><pre>hrt_dd1  &lt;- dist(t(SDhrtfail))<br>hrtclust &lt;- hclust(hrt_dd1, method = &quot;ward.D2&quot;)</pre><pre>plot(hrtclust, hang = -1, cex = 0.6, xlab = &quot;&quot;, ylab = &quot;&quot;, main = &quot;&quot;)<br>rect.hclust(hrtclust, 2, border = rainbow(2))</pre><pre>cor(hrt_dd1, cophenetic(hrtclust))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*xg-CFiVgOvzqO022-vy_Yw.png" /><figcaption>Dendrogram of the variables</figcaption></figure><p>Cutting the tree into two groups separates age, anaemia and serum_creatinine from the other six variables. The cophenetic correlation is 0.57, again below 0.75, consistent with the weak correlations seen in Part 1.</p><h3>i. Heatmaps</h3><p>A heatmap shows the data matrix as colours instead of numbers, with rows and columns reordered by dendrograms so that similar patients and similar variables sit together (<a href="https://www.datanovia.com/en/lessons/heatmap-in-r-static-and-interactive-visualization/">Datanovia</a>). The coloured side bar marks each patient’s death event.</p><pre>heatmap(as.matrix(Dheartfail), scale = &quot;column&quot;, cexCol = 0.75)</pre><pre>heatmap(as.matrix(Dheartfail),<br>        RowSideColors = rainbow(2)[hrtfail$VN],<br>        scale = &quot;column&quot;, cexCol = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*9NXk7TesUFpXyHKTIoWs7g.png" /></figure><p>Some darker areas in creatinine_phosphokinase seem to align with darker areas in serum_creatinine, but no clear blocks of colour appear, and the side bar shows survivors and deaths mixed throughout. With correlations this weak, the heatmap confirms what the indices already told us.</p><h4>How many clusters does NbClust suggest?</h4><p>Out of curiosity, we also used NbClust, which computes up to 30 indices for each candidate number of clusters and reports the number most indices agree on.</p><pre>library(NbClust)</pre><pre>nbr_Clust &lt;- NbClust(SDhrtfail, distance = &quot;euclidean&quot;,<br>                     min.nc = 2, max.nc = 10,<br>                     method = &quot;average&quot;, index = &quot;all&quot;)</pre><pre>[1] &quot;Frey index : No clustering structure in this data set&quot;<br>*** : The Hubert index is a graphical method of determining the number of clusters.<br>                In the plot of Hubert index, we seek a significant knee that corresponds to a <br>                significant increase of the value of the measure i.e the significant peak in Hubert<br>                index second differences plot. <br> <br>*** : The D index is a graphical method of determining the number of clusters. <br>                In the plot of D index, we seek a significant knee (the significant peak in Dindex<br>                second differences plot) that corresponds to a significant increase of the value of<br>                the measure. <br> <br>******************************************************************* <br>* Among all indices:                                                <br>* 7 proposed 2 as the best number of clusters <br>* 2 proposed 3 as the best number of clusters <br>* 9 proposed 4 as the best number of clusters <br>* 1 proposed 5 as the best number of clusters <br>* 1 proposed 6 as the best number of clusters <br>* 1 proposed 7 as the best number of clusters <br>* 2 proposed 8 as the best number of clusters <br><br>                   ***** Conclusion *****                            <br> <br>* According to the majority rule, the best number of clusters is  4 <br> <br> <br>*******************************************************************</pre><p>With average linkage and Euclidean distance, the majority rule suggests 4 clusters. That differs from our choice of 2 and is a reminder that the answer depends on the method, the distance and the criteria used.</p><h3>III-Conclusions</h3><p>In this Part 2, factor analysis showed that the variables share very little common structure (KMO = 0.55), and parallel analysis suggested no factors at all.</p><p>Cluster analysis told a similar story. The Hopkins test detected some clustering tendency, but silhouettes near 0.1, cophenetic correlations below 0.6 and nearly even fuzzy memberships all point to weak, overlapping groups. The clara clusters were unrelated to the death event (ARI ≈ 0). The fuzzy clusters were the exception: one of them grouped 78 of the 96 deaths, with older patients, higher serum creatinine and shorter follow-up.</p><p>In <a href="https://medium.com/p/8210a695f64f/edit">Part 3</a>, we will split the data into training and test samples, fit linear regression models, and apply discriminant analysis and logistic regression to classify patients by death event.</p><p><a href="https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-1-of-3-bce77a7cb31c">Heart Disease — Multivariate Analysis with R (Part 1 of 3)</a></p><p>Thanks for reading! If you have questions or suggestions, feel free to connect with me on <a href="https://www.linkedin.com/in/paulorsoliveira">LinkedIn</a>.</p><p><strong>References:</strong></p><p>[1] -Multivariate Data Analysis — Joseph F. Hair, William C. Black et. al. — 6th Edition — Bookman — 2009.</p><p>[2] -Applied Multivariate Statistics with R — Statistics for Biology and Health — Daniel Zelterman, ©Springer International Publishing Switzerland 2015.</p><p>[3]-[<a href="https://www.rdocumentation.org/packages/psych/versions/2.2.9/topics/fa.diagram">https://www.rdocumentation.org/packages/psych/versions/2.2.9/topics/fa.diagram</a>].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102defac2281" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Short-Term Electricity Consumption on University Campuses]]></title>
            <link>https://medium.com/@proberto3122/forecasting-short-term-electricity-consumption-on-university-campuses-e19f1af44983?source=rss-7afebe988e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/e19f1af44983</guid>
            <category><![CDATA[statistical-forecasting]]></category>
            <category><![CDATA[exploratory-analysis]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[autocorrelation]]></category>
            <dc:creator><![CDATA[Paulo R S Oliveira]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 16:01:15 GMT</pubDate>
            <atom:updated>2026-10-05T12:59:34.890Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forecasting Short-Term Electricity Consumption on University Campuses (1)</h3><h4>Can we predict a university campus’s total electricity consumption for the next day from its consumption over the previous n days?</h4><p><strong><em>Part 1 of 3: the problem, the data, and what it reveals</em></strong></p><p>How much energy will a university campus use tomorrow? In this three-part series, I show how I tackled that question using seven years of real electricity consumption data, comparing classical statistical models (SARIMA/SARIMAX) with machine learning algorithms (KNN, XGBoost) and neural networks (MLP, LSTM, and GRU). In this first Part, I explain the problem, describe the data and how it was cleaned, and present the exploratory analysis that shaped every modeling decision that followed.</p><p><strong>Why this matters</strong></p><p>Universities are small cities: classrooms, laboratories, administrative services, libraries, and equipment that all run on their own particular schedules. Many higher education institutions have been installing smart meters in their buildings, giving them access to near real-time consumption measurements. That data has considerable strategic value, as long as someone turns it into useful information.</p><p>A good short-term electricity consumption forecast makes it possible, among other things, to:</p><p><strong><em>→</em></strong><em> size self-consumption photovoltaic systems more accurately, matching expected generation to expected demand;<br> </em><strong><em>→</em></strong><em> estimate future energy costs and plan budgets;<br> </em><strong><em>→</em></strong><em> adopt demand management plans, shifting consumption away from the most critical periods or those with the highest tariffs.</em></p><p>A campus’s consumption depends on many factors: occupancy, opening hours, building type and age, installed equipment, and weather conditions [1]. Predicting tomorrow using only today’s value is simple, but the errors add up quickly. The alternative is to look for patterns in historical data, and that is where statistical and machine learning models come in.</p><p><strong>The goal</strong></p><p>This series summarizes the work I carried out for my master’s project in Data Science. The question was a concrete one:</p><p><strong><em>Can we predict a university campus’s total electricity consumption for the next day from its consumption over the previous n days?</em></strong></p><p>I used n = 7 and n = 14, because energy consumption series usually follow a weekly cycle. I also tested whether the forecast improves when exogenous variables are added: the average daily temperature and two binary variables indicating whether the day is a Sunday or a public holiday.</p><p>Model performance was assessed mainly with two complementary metrics:</p><p>MAPE (Mean Absolute Percentage Error) measures the error in percentage terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*eZIwR0Mx4bs8Hxi22lN9sA.png" /></figure><p>RMSE (Root Mean Square Error) measures the error in the same unit as the original variable, in this case kWh:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*XP6S5Gyv7x3CrUX0f9XMPg.png" /></figure><p>In both, Aₜ is the actual value and Fₜ is the forecast. MAPE is intuitive and makes it easy to compare different studies; RMSE penalizes large errors more heavily. As we will see, the best model on one metric is not always the best on the other.</p><p><strong>What the literature says</strong></p><p>Consumption forecasting is usually split into three horizons: long term (up to decades, for planning grids and generation), medium term (weeks to months, for operational planning), and short term (up to a week, for reducing daily operating costs). This work sits in the short term.</p><p>A few studies help calibrate expectations. In a study of university buildings in London, a multiple regression with six explanatory variables achieved a MAPE of 8.58% for administrative buildings and 9.76% for academic buildings [1]. Using hourly data from a large Japanese utility, a SARIMAX model with interaction effects reached a MAPE of 0.7% [2], but the level of aggregation is far larger, which smooths out variability. In another study, using load data from Panama, XGBoost tuned with Optuna achieved an average MAPE of 3.84% [3], and a regional study in Canada using LSTM reported 10.21% [4].</p><p>The main lesson: the smaller and more specific the consumer (a building, a campus), the harder the forecast, because human behavior carries more weight.</p><p><strong>The data</strong></p><p>The dataset covers about seven years of electricity consumption at a university campus in Southern Europe, from late 2015 to late 2022, with measurements every 15 minutes from the grid operator’s meter. The original files recorded active power (kW) and reactive power; for this work only active power mattered, converted into energy consumed (kWh) using a factor of 0.25 (one quarter of an hour).</p><p>To this I added daily weather records from the national meteorological service, collected at a station near the campus: mean, maximum, and minimum temperature, relative humidity, and wind direction and speed. In the end I used only the average daily temperature.</p><p>Figure 1 summarizes the methodology. In practice, the steps were not linear: what I learned during modeling often sent me back to data preparation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blBzvJkSlm5PGCQz17UtIQ.png" /><figcaption>Figure 1: Methodological workflow.</figcaption></figure><p><strong>Cleaning: the small problems that ruin big models</strong></p><p><strong><em>Daylight saving time</em></strong>. The first problem showed up where you would least expect it: the switch to daylight saving time. When the clocks go forward an hour in March, four quarter-hourly records disappear. To restore them, I averaged the values in the same time slot seven days before and seven days after, preserving both the overnight pattern and the weekly cycle.</p><p>In autumn the opposite happens: the clocks go back and the same hour appears twice, producing eight records where there should be four. I replaced them with the average of the eight values, spread across the four correct positions.</p><p><strong><em>Isolated gaps</em></strong>. There were also a few gaps unrelated to the clock change: a block of early-morning records missing on one day in 2016 and, in 2018, a run of four missing values followed by a value of zero. In the first case I used the same seven-days-before and seven-days-after strategy. In the second, I used the median of a wider time window on the same day, which proved more representative than the mean.</p><p><strong><em>Sentinel values in the weather data</em></strong>. The weather data had a different kind of trap: the value −990 used as a “no data” marker. A simple statistical summary gave it away immediately, with negative average temperatures in a temperate climate. Since the gaps were scattered across short intervals over the years, linear interpolation solved the problem without dropping any dates, which was essential for joining the weather data with the consumption series.</p><p>After the correction, the lowest recorded temperature was −5.7 °C. It looked suspicious, but I checked the climate bulletins and confirmed it matched a real cold spell. Not every extreme value is an error.</p><p><strong><em>From quarter-hourly to daily data</em></strong>. Since the goal was to predict daily consumption, I aggregated the roughly 246,000 quarter-hourly records into daily totals, taking care not to leak future information into the training data. The final dataset has 2,561 days, each with total consumption, day of the week, average temperature, and the Sunday and holiday flags.</p><p><strong>What the data reveals</strong></p><p><em>A very strong weekly rhythm</em></p><p>Figure 2 shows the full series. The sharp drop in 2020 and early 2021, caused by the COVID-19 pandemic and remote teaching, stands out immediately. It is a reminder that real-world time series are rarely well behaved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ekTicQrZ0IbM8C2ev7CYA.png" /><figcaption>Figure 2: Daily energy consumption over time (kWh)</figcaption></figure><p>The difference between weekdays and weekends is huge (Figure 3). On Sundays the buildings are closed and consumption stays flat throughout the day; on Saturdays it is only slightly higher. On Fridays and Mondays, by contrast, consumption rises sharply from mid-morning and stays high through the afternoon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zryjqS5pISdaxyDJ4Bpyig.png" /><figcaption>Figure 3: Hourly consumption distribution on Fridays, Saturdays, Sundays, and Mondays.</figcaption></figure><p>The autocorrelation function confirms the pattern: there are significant peaks at every multiple of 7 (Figure 4). This observation is what justified using 7- and 14-day windows and a seasonality of m = 7 in the statistical models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8MK23gpw30OyR5G6FqZCQ.png" /><figcaption>Figure 4: Autocorrelation function of the consumption series.</figcaption></figure><p>A decomposition with multiple seasonal patterns (MSTL [5]) also showed that, in addition to the weekly cycle, there is a pattern tied to the academic calendar, with drops during breaks such as Christmas and Easter. This detail will come back in the next parts: almost every model struggled to anticipate the drop in consumption between mid-December and mid-January.</p><p><em>Outliers: are there any?</em></p><p>The monthly and weekly box plots did not point to any anomalies. As a precaution, I applied an *Isolation Forest* with 5% contamination and checked the candidates against the interquartile range criterion (Q1 − 1.5·IQR and Q3 + 1.5·IQR). No consumption observation was classified as an outlier. In the temperature series only two cases came up, both from the cold spell mentioned above, and I kept them.</p><p><em>Normality and stationarity</em></p><p>The Shapiro-Wilk and Jarque-Bera tests rejected normality for the consumption series (p &lt; 10⁻²⁶ in both), which is consistent with the bimodal histogram created by the gap between weekdays and weekends.</p><p>Stationarity produced a more interesting result (Table 1). The ADF test indicated that the series was stationary, but the KPSS test said the opposite. Given this disagreement, I applied first-order differencing [6], after which both tests agreed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*uSX4Vf1qqSGor0SEAKlD4Q.png" /></figure><p>The temperature series is not normal either, but it is stationary without differencing, with a very clear annual cycle.</p><p><strong><em>Temperature, Sundays, and holidays</em></strong></p><p>You might expect temperature to have a strong influence on consumption, but Figure 5 shows two very different rhythms: temperature follows a smooth annual cycle, while consumption swings week by week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hthFjOW4OphpN50pbg87w.png" /><figcaption>Figure 5: Consumption and temperature, normalized to the [0, 1] interval.</figcaption></figure><p>The correlations confirm the visual impression. Sunday has a point-biserial correlation of −0.45 with consumption, a moderate association. Temperature (Spearman correlation of −0.18) and holidays (−0.19) show weak associations. Even so, holidays cause a visible drop in consumption when they fall on a weekday (Figure 6); the problem is that there are few of them, just 89 days in seven years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfMDIH4KV3wmUNOHR0QJ9g.png" /><figcaption>Figure 6: Effect of public holidays on daily consumption, by day of the week.</figcaption></figure><p><strong>Takeaways from this stage</strong></p><p>Before writing a single line of modeling code, the exploratory analysis had already provided important clues:</p><p><strong><em>→</em></strong><em> The weekly cycle dominates the series, so 7-day windows and a seasonality of m = 7 are natural choices.<br> </em><strong><em>→</em></strong><em> Sunday looks like the most promising exogenous variable; temperature may matter less than expected.<br> </em><strong><em>→</em></strong><em> The pandemic and academic breaks introduce pattern shifts that no model relying only on the recent past can fully anticipate.<br> </em><strong><em>→</em></strong><em> Details such as daylight saving time or sentinel values can go unnoticed and silently contaminate the results.</em></p><p>In <a href="https://medium.com/p/59e0b96b7c76/edit">Part 2</a>, I move on to statistical modeling: SARIMA, SARIMAX, and the surprising effect of cross-validation on time series.</p><p>Thanks for reading! If you have questions or suggestions, feel free to connect with me on <a href="https://www.linkedin.com/in/paulorsoliveira">LinkedIn</a>.</p><p><strong>References:</strong></p><p>[1] K. P. Amber et al., “Energy consumption forecasting for university sector buildings,” *Energies*, vol. 10, no. 10, p. 1579, 2017.</p><p>[2] N. Elamin and M. Fukushige, “Modeling and forecasting hourly electricity demand by SARIMAX with interactions,” *Energy*, vol. 165, pp. 257–268, 2018.</p><p>[3] E. J. Aguilar Madrid, *Short-Term Electricity Demand Forecasting with Machine Learning*, 2021.</p><p>[4] N. Shirzadi et al., “Medium-term regional electricity load forecasting through machine learning and deep learning,” *Designs*, vol. 5, no. 2, p. 27, 2021.</p><p>[5] K. Bandara, R. J. Hyndman, and C. Bergmeir, “MSTL: A Seasonal-Trend Decomposition Algorithm for Time Series with Multiple Seasonal Patterns,” arXiv:2107.13462, 2021.</p><p>[6] R. J. Hyndman and G. Athanasopoulos, *Forecasting: Principles and Practice*, 3rd ed., OTexts. <a href="https://otexts.com/fpp3/">https://otexts.com/fpp3/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19f1af44983" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heart Disease — Multivariate Analysis with R (Part 1 of 3)]]></title>
            <link>https://medium.com/@proberto3122/heart-disease-multivariate-analysis-with-r-part-1-of-3-bce77a7cb31c?source=rss-7afebe988e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/bce77a7cb31c</guid>
            <category><![CDATA[clustering-analysis]]></category>
            <category><![CDATA[heart-disease-prevention]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[discriminant-analysis]]></category>
            <category><![CDATA[multivariate-analysis]]></category>
            <dc:creator><![CDATA[Paulo R S Oliveira]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 16:46:12 GMT</pubDate>
            <atom:updated>2026-10-05T19:57:36.063Z</atom:updated>
            <content:encoded><![CDATA[<h3>Heart Disease — Multivariate Analysis with R (Part 1 of 3)</h3><p>There are situations where it is necessary to conduct a multivariate analysis of the data to evaluate the association/correlation between more than two variables for better decision-making. In this case, effective management and analysis of behavioral factors are aspects of interest in Multivariate Analysis (MAD), an area that uses techniques that are extensions of univariate analysis and bivariate analysis, adding other techniques with multivariate aspects to facilitate understanding of the data, reducing its size and identifying the main characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X26q0-fIufOVCjQq" /><figcaption>Photo by <a href="https://unsplash.com/@echaparro?utm_source=medium&amp;utm_medium=referral">Edgar Chaparro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>I — Introduction</strong></h3><p>In a very brief summary of the theory, we have:</p><ul><li><strong>Factor Analysis</strong>¹ is a set of statistical techniques that seek to explain the correlation between observable variables, simplifying data by reducing the number of variables necessary to describe them, through two methodologies: <strong><em>i</em></strong>) analysis into principal components — summarizes the information of the observed variables in components (unobservable variables that are linear combinations of observed variables, but which are not correlated with each other); and, <strong><em>ii</em></strong>) exploratory factor analysis — assumes the existence of a number smallest of unobservable (latent) variables underlying the data (factors) that express what is common in the original variables;</li><li><strong>Cluster Analysis</strong>¹ is a technique for grouping individuals based on their similarities, where each group (cluster) must: be homogeneous → the individuals in the group must be similar; and have characteristics distinct from those of the other clusters → the individuals in a group must present distinct characteristics of individuals from the remaining groups. Classify individuals (people, animals, companies, plants, countries) according to criteria of similarity (or dissimilarity), without prejudices or pre-defined criteria (classification is not supervised);</li><li><strong>Discriminant Analysis</strong>² tries to identify linear combinations of several variables that can be used to distinguish between the groups. Linear discrimination analysis allows us to identify a linear combination of variables that can be used to identify the group membership of all individuals, aiming to minimize the occurrence of classification errors (classify individuals in one category when they belong to another category).</li></ul><p><strong>a. Objective</strong></p><p>The present work has the purpose of using statistical techniques such as factor analysis and discriminant analysis, aiming to interpret the interrelationship of variables together in their different effects.</p><p>In this way, the main objective will be:<strong>**</strong></p><ul><li>to apply exploratory factor analysis techniques to identify the factors associated with all quantitative variables;</li><li>to group the data, both in terms of individuals and variables, into clusters based on all quantitative variables;</li><li>to do a discriminant analysis, based on quantitative variables, to classify individuals concerning the categories of a qualitative variable using the balanced training sample.</li></ul><p><strong><em>**</em></strong><em> It is not our purpose to carry out a study regarding concepts about statistical variable, measurement scales, significance tests, and confidence levels.</em></p><p><strong>b. Scenario</strong></p><p>Cardiovascular diseases (CVDs) are the number 1 cause of death globally. This represents about 32% of all global deaths. The majority of these deaths are due to heart attacks and strokes.³ In 2021, deaths from cardiovascular diseases reached 20.5 million, up from 12.1 million in 1990, highlighting a significant increase over the past three decades.⁴ CVDs are disorders of the heart and blood vessels, including coronary heart disease (heart attacks), cerebrovascular diseases (strokes), heart failure (HF), and other types of pathologies.⁵</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*61xPzsuLdOQgsloK" /><figcaption>Photo by <a href="https://unsplash.com/@jessedo81?utm_source=medium&amp;utm_medium=referral">jesse orrico</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In particular, heart failure occurs when the heart is unable to pump enough blood to the body and is often caused by diabetes, high blood pressure, or other heart conditions or diseases. Most cardiovascular diseases can be prevented by addressing behavioral risk factors such as tobacco use, unhealthy diet and obesity, physical inactivity, and harmful alcohol use, using population-wide strategies, as people with cardiovascular diseases or those with high cardiovascular risk — due to the presence of one or more risk factors, such as hypertension, diabetes, hyperlipidemia or already established disease — require detection and early management.⁶</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nrr0J1UjWZGrzZXE" /><figcaption>Photo by <a href="https://unsplash.com/@dawson2406?utm_source=medium&amp;utm_medium=referral">Stephen Dawson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Effective management and analysis of behavioral factors are aspects of interest in Multivariate Analysis (AMD), an area that uses techniques that are extensions of univariate analysis and bivariate analysis, adding other techniques with multivariate aspects, such as factor analysis, which identifies the structure inherent to a set of variables, or discriminant analysis, which distinguishes groups based on a set of variables⁷, and that is what this work is about.</p><h3><strong>II — Dataset</strong></h3><p>To carry out this written work, the database <em>heart_failure_clinical_records⁸</em> was chosen — containing data relating to the medical records of 299 patients with heart failure collected at the Faisalabad Institute of Cardiology and the Allied Hospital in Faisalabad (Punjab, Pakistan), during the period April to December 2015.⁹ The patients consisted of 105 women and 194 men, aged between 40 and 95 years. All 299 patients had left ventricular systolic dysfunction and previous heart failure.</p><p>Heart failure is a common event caused by CVDs and this dataset contains 12 features that can be used to predict mortality by heart failure, most cardiovascular diseases can be prevented by addressing behavioral risk factors such as tobacco use, unhealthy diet and obesity, physical inactivity and harmful use of alcohol using population-wide strategies.</p><p>People with cardiovascular disease or who are at high cardiovascular risk (due to the presence of one or more risk factors such as hypertension, diabetes, hyperlipidemia, or already established disease) need early detection and management wherein a machine learning model can be of great help.</p><h3><strong>III — Exploratory Data Analysis/Preprocessing</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yn2ceT0Aevvm3pcs" /><figcaption>Photo by <a href="https://unsplash.com/@swimstaralex?utm_source=medium&amp;utm_medium=referral">Alexander Sinn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When analyzing a database we need to take into account that throughout the analysis we will need to obtain answers to questions such as:</p><blockquote>What type of data is it: real values, categorical values ​​or both?</blockquote><blockquote>Are there correlations between the variables?</blockquote><blockquote>Is there null data?</blockquote><blockquote>Are there unbalanced classes (or categories)?</blockquote><p><em>Variables</em></p><p>Attribute information regarding the 13 clinical characteristics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNzBwZJ-Lc9ORPMEgZEM5Q.png" /></figure><p><em>Features Selection</em></p><p>Among the variables above, we will choose one for use in the multivariate analysis as a quantitative variable (‘VQ’) and the other as a qualitative variable (‘VN’).</p><p><strong>a. Choosing the Ejection Fraction variable as ‘VQ’</strong></p><p>When deciding to use medical records relating to patients with heart failure in this Multivariate Data Analysis work, the choice for the variable ‘<em>ejection_fraction</em>’ occurs because it reflects the proportion of blood pumped out of the heart during a single contraction. In other words: the ‘ejection_fraction’ measures the heart’s ability to pump rich blood in oxygen to the body, and researchers indicate that in a healthy heart, the fraction is a number higher and a low number means the heart has difficulty keeping up with the body’s needs.¹⁰</p><p>Furthermore, researchers using Machine Learning techniques identified ejection_fraction and also serum creatinine, as the two most relevant characteristics, through building survival prediction models through machine learning based only on these two factors, and how the database used in this work deals with issues related to the heart, our choice was due to an important variable in the entire process.¹¹</p><p><strong>b. Choosing the variable ‘Death event’ as ‘VN’</strong></p><p>The choice of qualitative variable ‘Death event’ being the ‘VN’ is because this is the target variable of the database under analysis. The target variable is always the main variable in a data frame, as it is the one that represents the objective of data analysis, being used to predict or classify data. Thus, the target variable also helps in evaluating the effectiveness of the trained model, through metrics such as precision, and accuracy, among others.¹</p><p><strong>c. Changing variable names</strong></p><p>c. 1 — the ‘ejection fraction&#39; variable measures the percentage of blood that leaves the heart with each contraction.</p><p>c.2 — the variable ‘DEATH_EVENT&#39; records whether the patient died during the follow-up period. If yes in (&#39;1&#39;) or no as (&#39;0&#39;).</p><pre>{r}<br>hrtfail = rename(hrtfail, <br>                 c(&#39;ejection_fraction&#39; = &#39;VQ&#39;,<br>                   &#39;DEATH_EVENT&#39; = &#39;VN&#39;))</pre><p>We can then carry out a new query to check the changes made.</p><pre>{r}<br>names(hrtfail)</pre><pre> [1] &quot;X&quot;                        &quot;age&quot;                     <br> [3] &quot;anaemia&quot;                  &quot;creatinine_phosphokinase&quot;<br> [5] &quot;diabetes&quot;                 &quot;VQ&quot;                      <br> [7] &quot;high_blood_pressure&quot;      &quot;platelets&quot;               <br> [9] &quot;serum_creatinine&quot;         &quot;serum_sodium&quot;            <br>[11] &quot;sex&quot;                      &quot;smoking&quot;                 <br>[13] &quot;time&quot;                     &quot;VN&quot; </pre><p>The output above shows that the names of variables ‘VQ’ and ‘VN’ are correct. Checking the percentage and frequency by category of the variable ‘VN’’ (death event), to get information about the patients who died during the follow-up period.</p><pre>{r}<br>round(prop.table(tbVN)*100,)</pre><pre> 0  1 <br>68 32 </pre><p>Frequency table for the variable ‘VN’ (death event).</p><pre>{r}<br>tbVN = table(hrtfail$VN)<br>tbVN</pre><pre>  0   1 <br>203  96 </pre><p><strong>d. Constructing a barplot by category of the variable ‘VN’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjJmx-cGCJAucVGdvdZewQ.png" /></figure><p><strong>e. Characterization of Quantitative Variables</strong></p><p>Preparation of the data frame to carry out statistical processing. Modify/reorder the position of the columns/variables for better effectiveness in using them throughout the analysis. We position the qualitative variables first and then the quantitative variables.</p><pre>{r}<br>hrtfail = relocate(hrtfail, VN, diabetes, sex, smoking, <br>                   VQ, age, anaemia, <br>                   creatinine_phosphokinase,<br>                   serum_creatinine,<br>                   high_blood_pressure, <br>                   platelets, <br>                   serum_sodium, time)</pre><p>Let’s see the data.</p><pre>{r}<br>str(hrtfail)</pre><pre>&#39;data.frame&#39;: 299 obs. of  13 variables:<br> $ VN                      : int  1 1 1 1 1 1 1 1 1 1 ...<br> $ diabetes                : chr  &quot;no&quot; &quot;no&quot; &quot;no&quot; &quot;no&quot; ...<br> $ sex                     : chr  &quot;female&quot; &quot;female&quot; &quot;female&quot; &quot;female&quot; ...<br> $ smoking                 : chr  &quot;no&quot; &quot;no&quot; &quot;yes&quot; &quot;no&quot; ...<br> $ VQ                      : int  20 38 20 20 20 40 15 60 65 35 ...<br> $ age                     : num  75 55 65 50 65 90 75 60 65 80 ...<br> $ anaemia                 : int  0 0 0 1 1 1 1 1 0 1 ...<br> $ creatinine_phosphokinase: int  582 7861 146 111 160 47 246 315 157 123 ...<br> $ serum_creatinine        : num  1.9 1.1 1.3 1.9 2.7 2.1 1.2 1.1 1.5 9.4 ...<br> $ high_blood_pressure     : int  1 0 0 0 0 1 0 0 0 1 ...<br> $ platelets               : num  265000 263358 162000 210000 327000 ...<br> $ serum_sodium            : int  130 136 129 137 116 132 137 131 138 133 ...<br> $ time                    : int  4 6 7 7 8 8 10 10 10 10 ...</pre><p>Let’s take a look at the variable ‘VQ’ (the proportion of blood pumped out of the heart during a single contraction).</p><pre>{r}<br>VQ</pre><pre> [1] 20 38 20 20 20 40 15 60 65 35 38 25 30 38 30 50 38 14 25 55 25 30 35 60 30 38 40<br> [28] 45 38 30 38 45 35 30 50 35 50 50 30 38 20 30 45 50 60 38 25 38 20 30 25 20 62 50<br> [55] 38 30 35 40 20 20 25 40 35 35 80 20 15 25 25 25 40 35 35 50 20 20 60 40 38 45 40<br> [82] 50 25 50 25 50 35 60 40 25 45 45 60 25 38 60 25 60 25 40 25 45 25 30 50 30 45 35<br>[109] 38 35 60 35 25 60 40 40 60 60 60 38 60 38 38 30 40 50 17 60 30 35 60 45 40 60 35<br>[136] 40 60 25 35 30 38 35 30 40 25 30 30 60 30 35 45 60 45 35 35 25 35 25 50 45 40 35<br>[163] 40 35 30 38 60 20 40 35 35 40 60 20 35 60 40 50 60 40 30 25 25 38 25 30 50 25 40<br>[190] 45 35 60 40 30 20 45 38 30 20 35 45 60 60 25 40 45 40 38 40 35 17 62 50 30 35 35<br>[217] 50 70 35 35 20 50 35 25 25 60 25 35 25 25 30 35 35 38 45 50 50 30 40 45 35 30 35<br>[244] 40 38 38 25 25 35 40 30 35 45 35 60 30 38 38 25 50 40 40 25 60 38 35 20 38 38 35<br>[271] 30 40 38 40 30 38 35 38 30 38 40 40 30 38 40 40 35 55 35 38 55 35 38 35 38 38 60<br>[298] 38 45</pre><p>The quantitative variable ‘VQ&#39; (ejection_fraction) has many attributes. So we need to divide/cut/group this variable into classes.</p><pre>{r}<br>range(VQ)<br>seq(10, 85, 10)</pre><pre>{r}<br>VQ_classes = cut(VQ, breaks = c(10,<br>                                20,<br>                                30,<br>                                40,<br>                                50,<br>                                60,<br>                                70,<br>                                80,<br>                                90),<br>                 right = T, dig.lab = 4,<br>                 include.lowest = T)</pre><pre>{r}<br>tabVQ = table(VQ_classes)<br>round(prop.table(tabVQ)*100,3)</pre><pre>VQ_classes<br>[10,20] (20,30] (30,40] (40,50] (50,60] (60,70] (70,80] (80,90] <br>  7.692  23.411  42.140  13.712  11.371   1.338   0.334   0.000</pre><p><strong>f. Visualization searching for unusual observations</strong></p><p>This section provides a graphical representation of the variable ‘VQ’ for visual assistance in data analysis as the graphs allow visualization of many characteristics and unusual observations.</p><pre>{r, fig.width=14, fig.height=7, fig.align=&#39;center&#39;}<br>hist(VQ, main=&#39;Histogram VQ&#39;, ylab=&#39;Frequency&#39;,col=&#39;lightgreen&#39;,freq = F,<br>     xlab=&#39;Ejection Fraction (%)&#39;)<br><br>lines(density.default(VQ), lwd=2, col=&#39;red&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*LvEa6V7dZWaKf9UYk7ALog.png" /></figure><p>The visualization of the histogram reveals that the variable VQ is concentrated in the range of 20 to 40, and by inserting a density line next to the histogram we seek to understand whether the distribution follows a Gaussian curve and whether extreme values ​​are common.</p><p>We should check, through a boxplot, the variable ejection_fraction &#39;VQ&#39;, which records the percentage of blood with each contraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4a3kJhaesUCMCB14t9yEEw.png" /></figure><p>The boxplot above, on the percentage of Ejection Fraction (VQ), reveals the existence of atypical observations that <strong><em>may be</em></strong> outliers, let’s try to identify them through qqPlot, since this type of graph, in addition to being useful for detecting deviations in a distributing data relative to an expected distribution, comparing the distribution of different samples evaluating the normality of data, also could be used to detect possible outliers.</p><pre>{r, fig.width=14, fig.height=7, fig.align=&#39;center&#39;}<br>qqPlot(VQ)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5P2A6qVeRwXxkROH-_BRA.png" /></figure><p>In fact, in qqPlot we noticed that some atypical observations could be outliers. In particular, two individuals are labeled (218 and 65) that seem to run away at the extreme of the plot. However, because multivariate analysis involves more than two variables, univariate or bivariate methods may not be suitable for this purpose. Furthermore, the presence of a possible outlier may not interfere with the Discriminant Analysis, and an observation may not be a univariate outlier, and still turn out to be a multivariate outlier[1].</p><p>Let’s make use of the boxplot.stats function to get more details.</p><pre>{r}<br>boxplot.stats(VQ)</pre><pre>$stats<br>[1] 14 30 38 45 65<br><br>$n<br>[1] 299<br><br>$conf<br>[1] 36.62939 39.37061<br><br>$out<br>[1] 80 70</pre><p>The statistical information obtained from the boxplot.stats function confirms the existence of values ​​80 and 70 that are above the limits in the database (confirming the information from the boxplot and histogram above). Besides them, the qqPlot points out the observations 65 and 218. However, we have no demonstrable proof that these observations are not representative of the sample, since the range of the variable VQ is between 14 and 80, we chose to keep these atypical observations in the database to ensure generality[1].</p><p><strong>g. Checking other statistics for the variable’</strong><strong>VQ&#39;(ejection_fraction)</strong></p><pre>{r, fig.width=14, fig.height=7, fig.align=&#39;center&#39;}<br>round(describe(VQ),3)<br>quantile(VQ, 0.95)</pre><pre>&gt; round(describe(VQ),3)<br>   vars   n  mean    sd median trimmed   mad min max range skew kurtosis   se<br>X1    1 299 38.08 11.84     38   37.43 11.86  14  80    66 0.55        0 0.68<br>&gt; quantile(VQ, 0.95)<br>95% <br> 60 <br>&gt; </pre><p>We can say that 95% of patients have, at most, an Ejection Fraction percentage equal to 60 and that the remaining patients have at least 60.</p><p><strong>h. Analysing the existence of missing observations</strong></p><pre>{r}<br> sum(is.na(hrtfail))<br>[1] 0</pre><p>The practical impact of missing observations is the reduction of the sample for analysis, running the risk of biased and erroneous results. Fortunately, the database used in this work does not contain missing data, as we verify using the function is.na.</p><p><strong>i. Analysing the correlation between quantitative variables</strong></p><pre>{r}<br>&gt; names(hrtfail)<br> [1] &quot;VN&quot;                       &quot;diabetes&quot;                <br> [3] &quot;sex&quot;                      &quot;smoking&quot;                 <br> [5] &quot;VQ&quot;                       &quot;age&quot;                     <br> [7] &quot;anaemia&quot;                  &quot;creatinine_phosphokinase&quot;<br> [9] &quot;serum_creatinine&quot;         &quot;high_blood_pressure&quot;     <br>[11] &quot;platelets&quot;                &quot;serum_sodium&quot;            <br>[13] &quot;time&quot;</pre><p>Constructing an object that contains only quantitative variables.</p><pre>{r}<br>VQuant = c(5:13)<br>pquant = hrtfail[, VQuant]</pre><p>Correlations using: ‘pearson&#39;, &#39;kendall&#39; e &#39;spearman&#39;, methods.</p><pre>{r}<br>round(cor(pquant, method = &#39;pearson&#39;),3)<br>round(cor(pquant, method = &#39;kendall&#39;),3)<br>round(cor(pquant, method = &#39;spearman&#39;),3)</pre><pre>                             VQ    age anaemia creatinine_phosphokinase serum_creatinine high_blood_pressure platelets<br>VQ                        1.000  0.074   0.020                   -0.068           -0.178               0.018     0.054<br>age                       0.074  1.000   0.072                   -0.093            0.271               0.106    -0.052<br>anaemia                   0.020  0.072   1.000                   -0.216           -0.016               0.038    -0.036<br>creatinine_phosphokinase -0.068 -0.093  -0.216                    1.000           -0.050              -0.081     0.060<br>serum_creatinine         -0.178  0.271  -0.016                   -0.050            1.000              -0.090    -0.051<br>high_blood_pressure       0.018  0.106   0.038                   -0.081           -0.090               1.000     0.069<br>platelets                 0.054 -0.052  -0.036                    0.060           -0.051               0.069     1.000<br>serum_sodium              0.162 -0.102   0.061                    0.017           -0.300               0.019     0.049<br>time                      0.071 -0.198  -0.135                    0.126           -0.161              -0.195    -0.007<br>                         serum_sodium   time<br>VQ                              0.162  0.071<br>age                            -0.102 -0.198<br>anaemia                         0.061 -0.135<br>creatinine_phosphokinase        0.017  0.126<br>serum_creatinine               -0.300 -0.161<br>high_blood_pressure             0.019 -0.195<br>platelets                       0.049 -0.007<br>serum_sodium                    1.000  0.086<br>time                            0.086  1.000</pre><p>The resulting tables in the correlation output have many low and negative values. However, a graphical representation can help us visualize the correlations. The most readable version of the correlation graph uses the lower method, without including the main diagonal, keeping only the distinct values ​​and not including the correlation of a variable with itself.</p><p>Visualization of the graph shows the correlations between the variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHKm46UD1g4r0ZiR5p6sfw.png" /></figure><p>Focusing on the correlations between VQ and the other variables we see that the correlation is very small and in some cases even negative.</p><p>Finally, let’s use the ggpairs function to try to understand better.</p><p>In the graph obtained with the ggpairs function, the variable names are displayed on the outer edges of the matrix as x, y, and z. The boxes along the diagonals display the density plot for each variable, while the boxes in the lower left corner display the scatter plot between each pair of variables. The boxes in the upper right corner display the Pearson correlation coefficient between each variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-8KOkHvnNJZ2987ZvuXzQ.png" /></figure><p>Pearson correlation gives us a measure of the linear relationship between two variables. It has a value between -1 to 1, where a value of -1 means a total negative linear correlation, 0 means no correlation and +1 means a total positive correlation which helps us understand the relationship between these variables.</p><p>Note: We emphasize that the graphical representations above are not substitutes for the other statistical measures throughout this work. They simply provide us with a way to think about the data. In this way, the various previous plots can help us with any particular diagnosis throughout the analysis, particularly when it comes to checking correlation, association, variance, and covariance, which if not well identified can generate unexpected results throughout the discriminant analysis—and causing rework that could have been avoided.</p><p><strong>j. Checking for multivariate outliers</strong></p><p>In multivariate analysis, identifying observations allows us to find anomalous observations before applying any multivariate method, aiming to preserve the results of negative influences produced by these observations.</p><pre>{r}<br>&gt; outHD &lt;-HDoutliers(hrtfail)<br>&gt; outHD<br>NULL</pre><pre>{r, fig.width=14, fig.height=7, fig.align=&#39;center&#39;}<br>plotHDoutliers(hrtfail, outHD, <br>main=&#39;Search for possible multivariate outliers&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWHgdH1Il2ixRqRXBgh7oQ.png" /></figure><p>To interpret this graph is extremely difficult due to issues of visualizing the multidimensional space. However, atypical observations are generally represented as distant points in the data set, that is, with high distance values. These observations would be considered outliers and should be investigated further to understand their origin. It may be that these observations have wrong values, are samples out of context, or even represent some specific phenomenon.</p><p>Furthermore, we tried to observe the distribution of observations in the plot, whether they are concentrated in a specific region or distributed homogeneously, this could give us an idea about the type of outlier present in the data set.</p><p>On the other hand, it is important to remember that the presence of outliers is not necessarily an error, they can represent real and important phenomena. Therefore, it is important to investigate them carefully before deciding whether or not to remove them from the dataset [1].</p><p>Considering the comments, we highlight that in the case of the plot above, we did not check the concentration of data in a specific region, on the contrary, the data is ‘<em>scattered</em>’.</p><p><strong>k. Checking if the quantitative variables follow a multivariate normal distribution in each category of the VN variable</strong></p><p>This test is done using the Shapiro-Wilk normality test.</p><p>Hypothesis Testing:</p><p><em>H0: quantitative variables follow a multivariate normal distribution.</em></p><p><em>H1: quantitative variables do not follow a multivariate normal distribution</em></p><p>Significance Level = 5%</p><pre>{r, message=F, warning=FALSE}<br>mshapiro.test(t(hrtfail[,5:13]))<br><br> Shapiro-Wilk normality test<br><br>data:  Z<br>W = 0.66978, p-value &lt; 2.2e-16</pre><p>Since the p-value is &lt; 2.2e-16, therefore less than an alpha of 5%, we can reject H0 because there is statistical evidence that the quantitative variables do not follow a multivariate normal distribution.</p><p>To continue our analysis, we will modify the label of the categories of the VN variable.</p><pre>{r}<br>hrtfail$VN = factor(hrtfail$VN, labels = c(&#39;no&#39;, &#39;yes&#39;))<br>glimpse(hrtfail$VN)<br>&gt; Factor w/ 2 levels &quot;no&quot;,&quot;yes&quot;: 2 2 2 2 2 2 2 2 2 2 ...</pre><p>k.1 — Let’s check whether the quantitative variables follow a multivariate normal distribution in the <strong>‘yes’ category</strong> of the variable VN (death event).</p><p>Hypothesis Testing:</p><p><em>H0: quantitative variables follow a multivariate normal distribution in the ‘yes’ category of the qualitative variable </em><em>VN (death event).</em></p><p><em>H1: quantitative variables do not follow a multivariate normal distribution in the ‘yes’ category of the qualitative variable </em><em>VN (death event).</em></p><p>Significance Level: 5%</p><pre>{r, warning=F, message=F}<br>mshapiro.test(t(hrtfail[hrtfail$VN == &#39;yes&#39;, 5:13]))<br><br> Shapiro-Wilk normality test<br><br>data:  Z<br>W = 0.76408, p-value = 4.097e-11</pre><p>The p-value &lt; 4.097e-11 reported in the output is less than 5% (alpha), so we can reject H0 because there is statistical evidence that the quantitative variables do not follow a multivariate normal distribution in the ‘yes’ category of the qualitative variable VN.</p><p>k.2 — Checking whether the quantitative variables follow a multivariate normal distribution in the <strong>‘no’ category</strong> of the variable VN (death event).</p><p>Hypothesis Testing:</p><p><em>H0: quantitative variables follow a multivariate normal distribution in the ‘no’ category of the qualitative variable </em><em>VN (death event)</em></p><p><em>H1: quantitative variables DO NOT follow a multivariate normal distribution in the ‘no’ category of the qualitative variable </em><em>VN (death event)</em></p><p>Significance Level: 5%</p><pre>{r, warning=F, message=F}<br>mshapiro.test(t(hrtfail[hrtfail$VN == &#39;no&#39;, 5:13]))<br><br> Shapiro-Wilk normality test<br><br>data:  Z<br>W = 0.65146, p-value &lt; 2.2e-16</pre><p>With p-value &lt; 2.2e-16, therefore lower than alpha of 5%, we can reject H0 because there is statistical evidence that the quantitative variables do not follow a multivariate normal distribution in the ‘no’ category of the qualitative variable VN.</p><p><strong>l. Checking whether the variance-covariance matrix of the quantitative variables is the same in all categories of the VN variable</strong></p><p>Given the importance we attribute to this subitem, it seemed convenient to note that the variance-covariance matrix of quantitative variables is a tool used in multivariate statistics to measure linear relationships between variables.</p><ul><li>it is a square matrix that contains the variations of the variables on the main diagonal and the covariances between the variables in the other positions. The main diagonal of the matrix contains the variance values ​​of each variable, that is, the measure of data dispersion around the mean.</li><li>the variation of a quantitative variable is given by the sum of the squares of the differences between each observation and the mean. The other positions of the matrix contain the covariances between the variables, that is, the measure of the linear relationship between them.</li></ul><p>The covariance between two variables is given by the sum of the products of the differences between each pair of observations, divided by the number of observations [1].</p><p>Hypothesis Testing:</p><p><em>H0: The variance-covariance matrix of the quantitative variables is the same in the two categories (‘yes’, ‘no’) of the variable VN (death event).</em></p><p><em>H1: The variance-covariance matrix of the quantitative variables is not the same in the two categories (‘yes’, ‘no’) of the variable VN (death event).</em></p><p>Significance Level: 5%</p><pre>{r}<br>boxM(hrtfail[,5:13], hrtfail$VN)<br><br> Box&#39;s M-test for Homogeneity of Covariance Matrices<br><br>data:  hrtfail[, 5:13]<br>Chi-Sq (approx.) = 176.54, df = 45, p-value &lt; 2.2e-16</pre><p>Since the p-value &lt; 2.2e-16, therefore less than Alpha of 0.05, we can reject H0, as there is statistical evidence that the variance-covariance matrix of the quantitative variables is not equal in both categories (‘yes’, ‘no ‘) of the variable VN (death event).</p><p><strong>m. Analyzing the discriminating capacity of quantitative variables in relation to the </strong><strong>VN variable</strong></p><p>The discriminant capacity of a quantitative variable is its ability to differentiate between different groups or categories. In other words, it is a measure of a variable’s ability to separate or distinguish between different groups of data based on their values. Variables with high discriminating capacity are useful for classification and data analysis.</p><p>It is measured through statistics, such as the discrimination coefficient, and the greater the discriminating capacity of a variable, the greater its ability to separate groups or categories.</p><p>Below we have graphs of the quantitative variables in relation to the VN variable. A brief explanation of the interpretability of the graphs is found at the end of this item &#39;<strong>m</strong>&#39;.</p><p>m.1-Variable VN in relation to Variable VQ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gmE7HfCBS-t9FYgX4ioBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNeLIS6ZELtXgZ-jUi_anw.png" /></figure><p>m.2-Variable VN in relation to Variable creatinine_phosphokinase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZM1Py_nSMoUXekUMBiyktQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hte1qroV7SgOBUHEDHdx9w.png" /></figure><p>m.3-Variable VN in relation to Variable platelets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CI34wU553OodvBNOgrNGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VeCK1s35oy-TO-pfGicb2Q.png" /></figure><p>m.4-Variable VN in relation to Variable serum_sodium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2DoJmi9fkW2sSbgY8mLPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISR2LyGiL89V2Zf5ExPIgw.png" /></figure><p>m.5-Variable VN in relation to Variable time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X89dYEWfsatX1eFQ0bz1MA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FABqWxQH-UnVmfELJp4huQ.png" /></figure><p>m.6-Variable VN in relation to Variable age</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEcbVEpWLYV-KTb5mFga1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ujitjWc9ZAQN78ko_fX8g.png" /></figure><p>We can see above that two types of graphs were created trying to improve their interpretability. The first of them with the variable categories separated by axis and the second using the ggplot libraries plotting a histogram with overlapping of the variable categories.</p><ul><li><strong>Plot with the variable categories separated by axis</strong></li></ul><p>This is a type of graph that time and experience help in interpreting, however, after some research, we can mention that a plot of the discriminating capacity of a variable is usually a bar or curve on a graph that shows how the variable behaves in relation to different groups or categories. To interpret this type of plot, it is important to observe the position of the bar or the shape of the curve and the areas where it rises or falls.</p><p>If the bar is “tall” and “narrow” in a certain region, this indicates that the variable has a high discriminating ability in that region, and is able to clearly differentiate groups or categories in that range of values. If the bar is “low” and “wide”, this indicates that the variable has a low discriminating capacity in this region, and is not able to clearly differentiate groups or categories in this range of values.</p><ul><li><strong>Histogram with overlapping of the variable categories</strong></li></ul><p>Histogram bars represent the frequency within each VN category. The bars are filled with different colors for each category (VN), facilitating visual comparison. If the distributions (bars) of the different categories are well separated with little or no overlap, this indicates that the variable has a good discriminating capacity in that range of values.</p><p>On the other hand, if there is a lot of overlap between the distributions of the different categories, this suggests that the variable has a low discriminating capacity. When we observe that the bars of different categories are located in different intervals and that there is little overlap, this indicates that the variable can be a good discriminant between the categories.</p><p>In other words, to correctly interpret the histogram, we must focus on separating the category distributions. Less overlap and well-separated distributions indicate a variable with good discriminating ability.</p><p>Finally, it is important to note that the discriminating capacity of a variable can vary across the sample space. Furthermore, it is important to observe the Y axis, that is, the value of the discrimination coefficient of these values ​​must be compared with the cutoff limit to be considered as “good” or “bad” discriminators[1, 2].</p><p>Thus, we can observe in the plots above that each quantitative variable has its discriminating capacity, in a specific range of values ​​for the categories of the VN variable, for each of them. This information could be considered when making Discriminant Analysis in Part 3.</p><p><strong>n. Box Plots</strong></p><p>At the end of this Part 1, we included the construction of three boxplots as an aid for the analysis of quantitative variables related to VN (death event), and better understanding of the data regarding the other items following this work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Qzc-Or1lVHcFP_Gaz0m_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hTH4XzHR2AOlRQgbExW2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SH6yMBDghZjROIvMD3EKIA.png" /></figure><h3>IV — Conclusions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KWn9CbQni-ua2ssh" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article (Part 1), we reviewed, in a brief way, some topics of the theory for Multivariate Data Analysis, defined the objective, and performed exploratory data analysis and some visualizations to help understand the characteristics of the data.</p><p>I hope the content is useful. I understand that the article was quite long, but it is always recommended to have a good understanding of the data before delving into the analysis.</p><p>In the next article (<a href="https://medium.com/p/102defac2281/edit">Part 2</a>) we develop a Factor Analysis and a Clustering Analysis. In the last article with <a href="https://medium.com/p/8210a695f64f/edit">Part 3</a>, a Linear Regression and a Discriminant Analysis are carried out.</p><p>Thanks for reading! If you have questions or suggestions, feel free to connect with me on <a href="https://www.linkedin.com/in/paulorsoliveira">LinkedIn</a>.</p><p><strong>References:</strong></p><p>[1] -Multivariate Data Analysis — Joseph F. Hair, William C. Black et. al. — 6ª Edition — Bookman — 2009.</p><p>[2] -Applied Multivariate Statistics with R — Statistics for Biology and Health — Daniel Zelterman, ©Springer International Publishing Switzerland 2015.</p><p>[3] -<a href="https://www.who.int/health-topics/cardiovascular-diseases/#tab=tab_1">https://www.who.int/health-topics/cardiovascular-diseases/#tab=tab_1</a></p><p>[4] -<a href="https://www.acc.org/latest-in-cardiology/articles/2024/01/01/01/42/feature-new-study-reveals-latest-data-on-global-burden-of-cardiovascular-disease">https://www.acc.org/latest-in-cardiology/articles/2024/01/01/01/42/feature-new-study-reveals-latest-data-on-global-burden-of-cardiovascular-disease</a></p><p>[5] -<a href="https://bmcmedinformdecismak.biomedcentral.com/">https://bmcmedinformdecismak.biomedcentral.com</a> /articles/10.1186/s12911–020–1023–5</p><p>[6] -<a href="https://my.clevelandclinic.org/health/diseases/21656-hyperlipidemia">https://my.clevelandclinic.org/health/diseases/21656-hyperlipidemia</a></p><p>[7] -<a href="https://archive.ics.uci.edu/ml/datasets/Heart+failure+clinical+records">https://archive.ics.uci.edu/ml/datasets/Heart+failure+clinical+records</a></p><p>[8] -<a href="https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0181001.">https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0181001</a></p><p>[9] -<a href="https://my.clevelandclinic.org/health/articles/16950-ejection-fraction">https://my.clevelandclinic.org/health/articles/16950-ejection-fraction</a></p><p>[10] -<a href="https://rdcu.be/c23uf">https://rdcu.be/c23uf</a></p><p>[11] -Data Science For Dummies®, 3rd Edition, Published by: John Wiley &amp; Sons, Inc., 111 River Street, Hoboken, NJ 07030–5774, <a href="http://www.wiley.com/">www.wiley.com</a></p><p>LinkedIn: <a href="http://www.linkedin.com/in/paulorsoliveira">www.linkedin.com/in/paulorsoliveira</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bce77a7cb31c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock Market Analysis]]></title>
            <link>https://medium.com/@proberto3122/stock-market-analysis-20990f235e63?source=rss-7afebe988e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/20990f235e63</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Paulo R S Oliveira]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 22:00:32 GMT</pubDate>
            <atom:updated>2024-06-12T20:53:57.408Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>I. INTRODUCTION</strong></p><p>Although we cannot predict with absolute accuracy 100% prices in the stock market, we continue to participate in this complex challenge through increasingly sophisticated analyses of the various variables that affect market value on a given day, such as weather conditions, economic situations, investor sentiments, news of wars and political events, that cause rapid changes causing random fluctuations in the price of assets [1] [21].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xHAy9rQFzoYv2Wkk" /><figcaption>Photo by <a href="https://unsplash.com/@rubensukatendel?utm_source=medium&amp;utm_medium=referral">Ruben Sukatendel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>DISCLAIMER: The information contained in this Article is purely educational in nature and does not constitute any kind of advice. It is not to promote any action or give any specific investment guidance or recommendation. Past profitability does not necessarily represent an indication of future profitability. Any investments in the financial and capital markets are subject to risks of loss of invested capital.</em></blockquote><p>By using stock analysis, investors and traders make decisions to buy and sell stocks, and studying and evaluating time series and current information helps investors and traders gain an advantage in the markets to make informed decisions [2]. Thus, some years have incorporated, as a valuable instrument, the application of methods for the development of trading and investment strategies based on Artificial Intelligence, and the use of Algorithms and Deep Learning, to assist the analysis of stock price movement[3], because the pattern of price change is still one of the main interest of many investors [4]. The basic assumption that underlaws time series analysis is that there is a more or less constant causal system, related to time, that has influenced data in the past and can continue to do so in the future. This causal system usually acts by creating non-random patterns that can be detected in a time series graph [5].</p><p>It should be mentioned that the use of AI and Machine Learning [6] to predict stock price trends and develop trading strategies is contrary to the Efficient Market Hypothesis (HME)[7]. In this sense, the term “efficiency” denotes the fact that investors do not have the opportunity to make abnormal profits in the market compared to other investors, because the relevant information is already incorporated into stock prices, so that if someone gets an advantage, the whole market will realize this benefit and the price of the asset will be adjusted. In other words, you cannot beat themarket[8]. As a counterpoint to HME, Andrew Lo (2004, 2005), in order to provide a better explanation of how market behavior occurs, elaborated the Adaptive Markets Hypothetical (HMA)[9], from which we can infer that, due to rational decisions made by individuals, stock prices could be predictive, and thus, profits could be obtained through price predictions of these assets.</p><p>It is also necessary to mention that there are two schools of thought that are used by investment managers to make their decisions: (<strong>i</strong>) technical analysis, which uses the price history and the negotiated volume of actions for decision-making; (<strong>ii</strong>) fundamentalist analysis, which tries to obtain the expected price of the role based on a study of the company, such as its financial health, macroeconomic perspectives, the company’s strategic planning and the panorama of the sector in which it is inserted[10].</p><p><strong>II. ASSETS FOR ANALYSIS</strong></p><p>The aim of this article is to investigate if it is possible <strong>graphically visualize</strong> the prediction of stock prices through machine learning algorithms, and from this information to assemble an investment strategy. For this, we selected some algorithms and time series, between January 2010 and April 2022, of capital market shares. We will use for our analysis the stock of SONAE, which is traded on Euronext(Lisbon), Cia Vale’s ADR, which is traded on nyse (New York), AMBEV’s stock traded on B3(Sao Paulo), SAMSUNG Electronicshares traded on the South Korean Stock Exchange, and finally we will consider APPLE’s role traded on Nasdaq on Nasdaq, to design our models.</p><p>The figure below contains a summary of the assets analyzed in the models that were developed for the elaboration of the graphs containing the price prediction obtained by the tools used. The use of two tools aims to assist in verifying the robustness of which is the best model/algorithm for that given action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7S8P09Ui-Fqk1K6v3ZQoMQ.png" /><figcaption>By Author</figcaption></figure><p>It is known that one of the concerns of investors is to find discorrelated assets[11], but with the same level of expected return, and the modern theory of portfolios shows that the investor could achieve the same return with lower levels of risk when they have access to diversification, so we decided to have stocks from different economic segments from different countries for this research work.</p><p>Time series analysis is an approach to extract significant data characteristics and generate other useful insights applied to the business situation, monitoring of industrial processes, etc. Time series data is usually a sequence of observations stored in order of time, and their analysis helps you understand the patterns verified in a given period, a set of metric data points that are critical to any business. Thus, time series forecasting techniques have the possibility to answer business questions such as how much stock to maintain, how much site traffic is expected in an online store and how many products will be sold next month, what the stock price forecast — all these are important time series problems to solve, and the basic purpose of the analysis is usually to determine a model that describes the pattern that can be used for prediction[11].</p><p><strong>III. INFORMATION ABOUT THE MODELS</strong></p><p>Here is some information about the models/algorithms used, as well as some figures that we highlight in the models that help us understand their performance.</p><ul><li>for the download of the data, was used the open source library, yFinance in order to obtain the stock price data of Yahoo Finance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hVncXh1vgKbXOm7M_pgPA.png" /><figcaption>By Author</figcaption></figure><ul><li>simply assign the ticker symbol of the action to be parsed to the ticker variable and then use the yFinance download method to fetch the stock price data in the desired period.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Hes43OnzCD4d7niYKlGeJQ.png" /><figcaption>By Author</figcaption></figure><ul><li>in our analysis, we searched data from the five actions under study from January 2010 to April 2022.</li></ul><p><strong>a. LSTM Model</strong></p><p>LSTM[12] is an artificial recurrent neural network (RNN) architecture used in the field of deep learning. Unlike standard feedforward neural networks, LSTM[13] has feedback connections. It can not only process unique data points (for example, images), but also entire sequences of data. For the purpose proposed here, we built the LSTM model with 150 neurons in each of the 5 hidden layers. Finally, we assign in addition to the loss function MSE, the adam stochastic gradient descent optimizer, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*SV4Oo2RfeZAdb4QyDXBmNw.png" /><figcaption>By Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*5jfHKG_aDcC5yYsR8204NQ.png" /><figcaption>By Author</figcaption></figure><p><strong>b. Model XGBoost</strong></p><p>XGBoost[14] uses several gradient-driven trees (referred to as n_estimators in the model) to predict the value of a dependent variable. When predicting a time series, the model uses what is known as a retrospective period to predict several steps ahead. For example, if a lookback period of 1 is used, the X_train (or independent variable) uses lame values of the time series regressed relative to the time series in time t (Y_train) to predict future values. There are many types of time series that are simply too volatile or are not suitable to be predicted directly. However, too often, machine learning models such as XGBoost are handled in a plug-and-play manner, where data is entered into the model without any consideration of whether the data itself is suitable for analysis.</p><p>The hyperparameters chosen for the models with XGBoost were as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Nn3bxq5IFB6OAbKKnJBE8A.png" /><figcaption>By Author</figcaption></figure><p>When using an XGBoost model — or any other model — we need to make sure that the time series is analyzed first on its own merits. This means determining a general trend and whether a seasonal pattern is present. The allure of XGBoost [22] is that it is possible to use the model to predict a time series without having to understand the technical components of the time series — and this may not be the case for stock price sequences [15].</p><p><strong>IV. PLOTS VIEW**</strong></p><p>As previously reported, the purpose of this Article is to provide a graphical view of predictions based on the time series of stock prices, so below are the figures related to each of the shares of the companies already mentioned with the respective graphs obtained through the use of XGBoost and LSTM.</p><p><strong>XGBoost ‘vs’ LSTM</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVgrARvveev2lkn37IUB6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5c687X2q1tRNUsS6h9uaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*rg8XCiUrO-uAmff_fjKUlQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wT7fxF-nx8wPCW2vlbsBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGTm55VTwLVIPvonA5tRLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Q6ZHHYv0ZmJs5CPH_cRvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*jkCVu1MPtE1j5q8Z23S7xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qq5jAZ6ulVUVDfpfM_5Vlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TErmkwRouzu7d6_PdAKneQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdfQCYNXkan_UXpAj6IC4g.png" /></figure><p><strong><em>** All graphics in this article are originate from models developed by the author.</em></strong></p><p><strong>V. CONCLUSION</strong></p><p>Looking more closely, we can see peaks and valleys in the various charts and in some of them we can distinguish a trend, but we will certainly need to make a decomposition of the time series to identify which components are acting more forcefully. We will also need to analyze different periods of the series to have a better understanding of some cyclic, seasonal, and irregular variations that the graphs show.</p><blockquote><strong>What’s the best model then?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fj5siFcnsk6TTqSm" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It will depend on the data of the series itself[5] and the characteristics of the use case to which they are applied [16].</p><p>Each of us has a different risk aversion profile and it is difficult to offer general guidance. Nothing prevents us from sitting back and understanding what algorithms do in the right models and what we can expect from them. However, in any discussion related to models, it is always important to remember the statement of George Box (a British statistician whose name is associated with several different statistical techniques) who said:</p><blockquote><strong><em>“All models are wrong, but some are useful ! “</em></strong></blockquote><p>The main goal of training models is not to predict a future stock price with high accuracy (which is technically impossible with any machine learning approach). The models are limited by historical data themselves, which have no magical power to predict a highly accurate future share price[15]. However, there are several experts who argue that we can build a model to estimate the percentage of a stock’s price change based on the recent price movement reflected by the moving average and traded volumes. This estimate of the percentage of price change could help plan an investment strategy to reduce risk.</p><p>We believe that, although we can graphically visualize what the model shows us, there must be also a greater knowledge of the properties of the time series in this way will help: the investor and the analyst/data scientist perceive the trend that a given series is indicating, to check whether there are periodic fluctuations repeating in identical periods, to identify whether there is an increase or reduction of frequency or random error resulting from unexpected events such as disasters, pandemics or terrorist acts, and it is still appropriate to understand whether the series is stationary; that is: if its mean, variance and correlation structure remains constant over time[16].</p><p>At the end of this article, reflection is necessary. The models developed here made use of excellent algorithms and the choice of assets decorrelated in different economic segments with diverse geographical location, meets the theory of portfolio diversification. Despite this, does the visualization of the above charts allow us to plot an investment strategy? I don’t think so! It seems necessary to deepen the analysis of the graphs of the time series visualized above.</p><p>So let’s end it up with a better investment decision, it’s not enough to have a beautiful chart obtained by the best of algorithms. We will need to: <strong>i</strong>) adjust some hyperparameters of the models developed here, <strong>ii</strong>) build new models with other algorithms, type FBProphet [17][18] or NeuralProphet [19], for example, <strong>iii</strong>) add to the analysis, metrics such as The Average Absolute Error and The Average Quadratic Error, and tests such as walk-forward analysis, backtesting [20] and cross-validation among others.</p><p>Therefore, we conclude by highlighting that an analyst/data scientist needs to feel a huge curiosity in thinking about how to solve the problem of the type of prediction of action values of a company and not to scared away due to the complexity of this challenge and understand/accept that machine learning models help us in decision making, but they don’t decide for themselves.</p><p>LinkedIn: <a href="http://www.linkedin.com/in/paulorsoliveira">www.linkedin.com/in/paulorsoliveira</a>.</p><p>References:</p><p>[1]</p><p><a href="https://www.linkedin.com/pulse/os-desafios-de-forecasting-para-opera%C3%A7%C3%B5es-sanches-gomes/?originalSubdomain=pt">https://www.linkedin.com/pulse/os-desafios-de-forecasting-para-opera%C3%A7%C3%B5es-sanches-gomes/?originalSubdomain=pt</a></p><p>[2]</p><p><a href="https://cleartax.in/s/stock-market-analysis">https://cleartax.in/s/stock-market-analysis</a></p><p>[3]</p><p><a href="https://towardsdatascience.com/impact-of-artificial-intelligence-and-machine-learning-on-trading-and-investing-7175ef2ad64e">https://towardsdatascience.com/impact-of-artificial-intelligence-and-machine-learning-on-trading-and-investing-7175ef2ad64e</a></p><p>[4]</p><p><a href="https://python.plainenglish.io/how-to-predict-stock-prices-change-with-random-forest-in-python-f707e101d5c4">https://python.plainenglish.io/how-to-predict-stock-prices-change-with-random-forest-in-python-f707e101d5c4</a></p><p>[5]</p><p>Time Series Analysis — Marcelo Menezes Reis — INE 7001 // <a href="https://www.inf.ufsc.br/~marcelo.menezes.reis/INE7001.html">https://www.inf.ufsc.br/~marcelo.menezes.reis/INE7001.html</a></p><p>[6]</p><p>An Exploratory Study on the Complexity and Machine Learning</p><p>[7]</p><p><a href="https://www.tandfonline.com/doi/abs/10.2469/faj.v21.n5.55,">https://www.tandfonline.com/doi/abs/10.2469/faj.v21.n5.55,</a> Random Walks In Stocks Market Prices, Eugene F. Fama, 1965</p><p>[8]</p><p><a href="https://www.researchgate.net/publication/289992792_The_Efficient_Market_Hypothesis_Review_of_Specialized_Literature_and_Empirical_Research">https://www.researchgate.net/publication/289992792_The_Efficient_Market_Hypothesis_Review_of_Specialized_Literature_and_Empirical_Research</a></p><p>[9]</p><p>Adaptive Markets Hypothetical Test for Brazil, Glenner A. Dourado and Benjamin M. Tabak, September 2013. Papers for Discussion №325.</p><p>[10]</p><p><a href="https://riconnect.rico.com.vc/blog/como-analisar-uma-acao">https://riconnect.rico.com.vc/blog/como-analisar-uma-acao</a></p><p>[11]</p><p><a href="https://www.kadimaasset.com.br/">https://www.kadimaasset.com.br/</a> Kadima Publications — Volume I, March 2016</p><p>[12]</p><p><a href="https://machinelearningknowledge.ai/keras-lstm-layer-explained-for-beginners-with-example/">https://machinelearningknowledge.ai/keras-lstm-layer-explained-for-beginners-with-example/</a></p><p>[13]</p><p><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">https://colah.github.io/posts/2015-08-Understanding-LSTMs/</a></p><p>[14]</p><p><a href="https://github.com/dmlc/xgboost">https://github.com/dmlc/xgboost</a></p><p>[15]</p><p><a href="https://towardsdatascience.com/xgboost-for-time-series-forecasting-dont-use-it-blindly-9ac24dc5dfa9">https://towardsdatascience.com/xgboost-for-time-series-forecasting-dont-use-it-blindly-9ac24dc5dfa9</a></p><p>[16]</p><p><a href="https://medium.com/data-hackers/series-temporais-parte-1-a0e75a512e72">https://medium.com/data-hackers/series-temporais-parte-1-a0e75a512e72</a></p><p>[17]</p><p><a href="https://towardsdatascience.com/a-quick-start-of-time-series-forecasting-with-a-practical-example-using-fb-prophet-31c4447a2274">https://towardsdatascience.com/a-quick-start-of-time-series-forecasting-with-a-practical-example-using-fb-prophet-31c4447a2274</a></p><p>[18]</p><p>Forecasting at Scale — Sean J. Taylor and Benjamin Letham (Facebook)</p><p>[19]</p><p><a href="https://towardsdatascience.com/facebooks-prophet-deep-learning-neuralprophet-76796aed1d86">https://towardsdatascience.com/facebooks-prophet-deep-learning-neuralprophet-76796aed1d86</a></p><p>[20]</p><p><a href="https://medium.com/devtrader/entendendo-um-backtest-31945d601c1f">https://medium.com/devtrader/entendendo-um-backtest-31945d601c1f</a> -</p><p>[21]</p><p>Master’s Thesis — Gustavo Carvalho Santos — ML Algorithms for B3 Stock Prediction</p><p>[22]</p><p><a href="https://www.cienciadedatos.net/documentos/py39-forecasting-time-series-with-skforecast-xgboost-lightgbm-catboost.html">Forecasting time series with gradient boosting: Skforecast, XGBoost, LightGBM and CatBoost</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20990f235e63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Definition and Management of Metrics in Data Governance]]></title>
            <link>https://medium.com/@proberto3122/definition-and-management-of-metrics-in-data-governance-ce2c066a2070?source=rss-7afebe988e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce2c066a2070</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[engagement]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[metrics-and-analytics]]></category>
            <dc:creator><![CDATA[Paulo R S Oliveira]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 13:17:23 GMT</pubDate>
            <atom:updated>2024-06-12T21:06:03.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UssXdOo5htcjyDKg" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha?utm_source=medium&amp;utm_medium=referral">fabio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>I. INTRODUCTION</strong></p><p>We begin this article using the words of John Edwards [9], who is a veteran business technology journalist with several business and technology publications, who says: <em>“Today, every data transaction is a business transaction. That’s why it’s vital to build a data governance framework that is strong, secure, adaptable, and as error-free as possible. A critical mistake many IT leaders make is introducing data governance policies without ensuring that all important parts of the company have the tools and knowledge to implement them effectively</em>.”</p><p>Data Governance (GD) has been a difficult area of ​​business to work in. When everything is working and no noise is causing problems, your efforts go unnoticed. On the other hand, when problems arise and things go wrong, data governance is the first area to blame — <strong><em>processes don’t work, and you are not controlling it correctly!</em></strong> Therefore, to demonstrate to shareholders [2] that the effort and investment made in GD are benefiting the business, reducing costs, and increasing revenue, it will be necessary to implement some metrics. This will allow the company to understand and see the improvement that is occurring.</p><p><strong>But where to start and what to measure?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xEO9jb2xfBfPWp34" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=medium&amp;utm_medium=referral">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To do so, we need to define ‘Data Governance Metrics’. In other words, we try to say something based on the determination of its uniqueness and describe what is specific and distinct about metrics, their meaning and their importance. So, the question immediately arises:</p><p><strong>Why are metrics important?</strong></p><p>Metrics are important because they can show whether or not there is alignment with business strategy and can <em>“help ensure that business process silos within the organization consistently understand and are aligned with governance program expectations” </em>says Kelle O’Neal [6], founder and CEO of First San Francisco Partners. “Metrics can demonstrate the ongoing relevance and value of your data governance program.” <em>“You will find that the definition of value, the definition of relevance, and how you align your organization changes over time; which means your metrics will also change over time,”</em> concludes O’Neal. Having established the importance of the metric, we now need to apply this understanding in the context of Data Governance.</p><p><strong>What are metrics in Data Governance?</strong></p><p>There is no doubt that data governance has brought new business and development opportunities. However, beyond having opportunities at hand, you need to understand, manage and measure them. That’s where Metrics Management in Data Governance comes in. The classic definition of metrics states that they are quantifiable measurements used to analyze the outcome of a specific process, action, or strategy. In other words, a metric is a number that represents the measure that you will monitor to understand what works (or not) in your work.</p><p><strong><em>But can we only look at a metric as a quantitative measure?</em></strong></p><p>The metric depends on what you want and need to measure. Among so many possibilities, to know which metrics are useful for your strategy, it is necessary to develop a plan.</p><p>John Ladley in his book ‘Data Governance’ [5] teaches us <em>“that we cannot manage what we do not measure</em>”. Over time, the Data Governance program will need to develop a way to monitor its effectiveness. Without it, the GD program will certainly disappear. Investigations show that metrics will be difficult to collect at first. After all, in the initial stage of the Data Governance program implementation process, there is no history or habit of data management, therefore, there is no ‘infrastructure’ to install a metric appropriately. But eventually, metrics will evolve from simple surveys and counts to true activity monitoring.</p><p>This is why Ladley teaches us that we must “<em>quantify the costs</em>”. He says that we need to <em>“examine current IT costs, as well as all other information-related costs. Also include all capital costs, depreciation, and overhead”.</em> In his talks, John Ladley also states that:<em> “any analysis of the cost of poor data quality must also be taken into account. Include the costs of departmental usage databases (silos), spreadsheets, and ‘ShadowIT’. This is a good exercise to calculate the initial cost, as it shows how much is being spent now, without data governance”.</em>[5]</p><p>Being recognized as difficult, questions will necessarily arise such as:</p><p><strong><em>How do you know if your efforts are working or if you are dragging your feet and getting nowhere?</em></strong></p><p>Firstly, it is necessary to understand what the problems are, the objectives and the impacts of solving them.</p><p>Quoting Kelle O’Neal [6] again: <em>“Metrics are one of the hardest aspects of data governance [to understand] and also one of the most important,”</em> she said because metrics provide an opportunity to establish a baseline to <em>“know what bad data means and potentially what good data could mean”</em> creating a starting point for getting the organization as a whole to understand the need for better data. Metrics can help align an organization with a set of shared goals, “<em>and that alignment of expectations is really important</em>.” Metrics can also provide an opportunity to engage with stakeholders.</p><p><strong>II. DISCUSSION</strong></p><p>Experts and several authors argue that the first step to implementing any data governance process and related practices is to fully understand the people, processes, and tools that are currently used to maintain data. They say, we can’t fix what we don’t understand, so getting a solid picture of the data lifecycle in advance is critical.</p><p>Another important step is communication regarding the need and value proposition regarding Data Governance. It is necessary to obtain the right support throughout the organization. <strong><em>“We did just that and secured executive and stakeholder support from the IT and business teams, which got us off to a great start</em>”</strong>, has been the testimony of those who have been successful in their businesses.</p><p>However, we need to agree with other authors that there is still something important missing to be added to the ‘menu’. It means we need to develop and publish meaningful metrics to show improvement and progress towards business objectives. Management at every company will want to see substantial evidence that their data governance initiative is positioned to succeed, so we need to make sure to establish a regular flow for sharing metrics and reports.</p><p>But, metrics should always refer to the underlying business objectives to demonstrate achievement against business value, and when necessary, refine the plan, analyze feedback, and clarify evolving business needs to maintain focus and the value proposition of Data Governance. In many instances, data initiatives have the ability to begin generating value during the initiative, well before completion, as any incremental improvements in data quality and availability can generate immediate insights to drive better decision-making.</p><p>We must also agree that failure to manage data is similar to failure to manage capital, and this results in waste and missed opportunities, as data not only represents value and opportunities, and when poorly managed, it also represents ethical and security risks. Security can cause misuse and loss of reliability, thus generating unreliability.</p><p>In this particular, an article by Suriya N Subramanian [1], mentions in his post on Linkedin, that some simple metrics help for the success of Data Governance. Therefore, we highlight, in a reduced form, that the way to show the progress of successful data governance is through monitoring some key indicators, such as:</p><p>i) Improvement in Data Quality Indices</p><p>ii) Adherence to Data Management Standards and Processes</p><p>iii) Reduction of risk events</p><p>iv) Reduction in data rectification costs</p><p>Nevertheless, we need to mention that nowadays a company’s management must realize that there is progress towards a set of metrics that can be measured, as well as the impact of this progress on the organization. Several authors also mention that this progress can be measured in four contexts: people, processes, technology, and data.</p><p><strong>a) Progress metrics: people</strong></p><p>When implementing a data governance program, there are ways to measure progress as it relates to people, such as:</p><p>1. tasks and activities that involve alignment<br>2. designation and integration of people as part of the program<br>3. the number of people who have been trained and their continued participation<br>4. tracking the number of resolved issues<br>5. the number of approved projects</p><p><strong>b) Measures of progress: processes</strong></p><p>Experts in the field argue that measuring processes is a great way to measure how well governance is embedded in the organization, including:</p><p>1. identify which processes have an impact on your objectives and focus your measurement on them<br>2. identify and articulate how processes are created<br>3. how implementation planning should occur<br>4. how the processes will be executed<br>5. Do people understand what the new process is?<br>6. Are people using the new process?<br>7. are we working with our backlog of processes?</p><p><strong>c) Measures of progress: technology</strong></p><p>Investigators of the progress of technology planning and implementation within the Data Governance program state that:<br>1. Progress can be measured by data integrity between systems,<br>2. by the number of consolidated data sources,<br>3. by the number of data targets using metadata</p><p><strong>d) Progress metrics: data</strong></p><p>Authors specializing in the field of Data Governance and several researchers agree that options for measuring progress with data may include analyzing common data entities and how improvement requests for these data entities are managed or documenting these data entities, because perhaps in this analysis we are looking at the efficiency of the process.</p><p>However, despite having mentioned a wide range of metrics in the four items above, this range does not exhaust what analysts, researchers, authors, and specialists usually highlight in their works, articles, and interviews. [2][3][4]</p><p><strong><em>We don’t even need to mention that we’re swimming in metrics, right?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FFUjAiy23-LXnc9s" /><figcaption>Photo by <a href="https://unsplash.com/@mcverry?utm_source=medium&amp;utm_medium=referral">Mikail McVerry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It would take a lot of effort to address all the feedback to address all of them. We believe we should reduce it, as a provocation for future debate, and perhaps we should focus on the metrics of:</p><p>• Data Accuracy<br>• Cost Reduction<br>• Number and frequency of audit visits</p><p><strong>III. CRITICAL ANALYSIS</strong></p><p>As the number of IT metrics multiplies, it’s important to focus on key indicators that offer at-a-glance insight into essential business functions.</p><p>Evidently, metrics are essential tools that help an organization’s management focus its teams and resources on important core business areas, such as transformation and operations. However, while highly useful, metrics can also be dangerous when used inappropriately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jt5BHgT58VaKC62y" /><figcaption>Photo by <a href="https://unsplash.com/@roadtripwithraj?utm_source=medium&amp;utm_medium=referral">Road Trip with Raj</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s easy, for example, to rely on the wrong metric to track a specific trade, a mistake that can lead to inaccurate or misleading results. Complicating matters is the constant stream of new metrics, many of which have yet to prove their value over the long term.</p><p>Numbers say many things, but they do not show everything. It is necessary to look beyond the numbers to understand and understand what is really happening. Many experts argue that when putting together a package of metrics that can be used to capture the impact of Data Governance on transformations and operations, their minimalism should be fundamental.</p><p>Avoiding clutter and confusion to instead focus on a core set of fundamental metrics that provide a clear view of critical issues and challenges. And while additional analysis tools can be added over time to augment and illuminate important trends, it’s best to start with just a few basic tools.</p><p>Matt Mead, CTO at technology consulting firm SPR [8], believes IT and business team engagement is a powerful metric for measuring success.</p><p><em>“We know that teams undergo psychological development through training, confrontation, standardization, and performance”, </em>he says. <em>“We also know that it takes time for joint technical and business teams, typically created for an organizational transformation, to solidify and mesh</em>”. Mead notes that he often sees clients failing to allocate enough time for changes to take hold. Instead, under-engaged business and IT project leaders declare success and move prematurely to the next stage.</p><p><em>“The best metric, especially during the first year, is to measure the </em><strong><em>engagement</em></strong><em> level of all team business and IT team members,” </em>he advises.</p><p><em>“If engagement is high, you have the foundation to be successful,” </em>says Mead<em>.</em></p><p><em>“If engagement is low, failure is likely.”</em></p><p>Therefore, we need to discover one or more characteristics of what is being measured. So, we need to understand that the result of an indicator is feedback. <strong>Not every result is a number, but every indicator is a result.</strong> Thus, it provides information about what has already happened (or what should have happened). Thus, understanding feedback is related both to understanding what happened and whether it occurred efficiently or not during the process.</p><p>Take for example semi-annual metrics. This does not mean that we should only check the metric after six months. We can do monthly or bi-weekly checks to get feedback on what has already happened and make corrections [7].</p><p>These fixes may seem superficial, even because it is an immediate action. However, we need to evolve to an understanding of feedback when we look at the number of times it was necessary to adjust and why this number of corrections occurred. Feedback helps to align and correct, but understanding helps to promote change. Changes are different from adjustments. Understanding the accumulation of adjustments requires a deep analysis of the causes, as we may be faced with situations that concern the gain or loss of company value that Data Governance and its Metrics may cause, despite all the concerns we may take, or no matter how technical the implementation of Data Governance in the company was.</p><p><strong>IV. CONCLUSION</strong></p><p>As we mentioned in the introduction to this article, and after having highlighted above the importance (and in a certain way the exaggerated quantity) of metrics in Data Governance, we want to mention as part of our conclusion, what Kelle O’Neal, founder and CEO of First San Francisco Partners, presented at DATAVERSITY® Enterprise Data Governance Online 2017. She said, “<em>When it comes to metrics, less is more</em>.”</p><p>We highlight that investors, creditors, shareholders, and society in general end up bearing some losses generated in organizations, and although the metrics deal with past events, our concern with the organization must consider the future, as the past is only history, relevant history, but just history.</p><p>It is in the future that the risk of poorly established, poorly managed, and poorly evaluated metrics lies, since the establishment, management, and evaluation are carried out by people, hence the need to involve interested parties becomes super important.</p><p>As Peter Drucker taught us, the “first function” of a manager, Drucker said: “<em>is people. It’s the relationship with people, the development of mutual trust. . . the creation of a community.</em>” Or, as Albert Einstein observed: “<em>Not everything that can be counted counts, and not everything that counts can be counted</em>.”[11].</p><p>This way, we want to highlight the importance of the need to obtain <strong>engagement</strong> in the establishment and management of GD metrics, as without the proper coverage of the entire organization, there will be no point in starting and defining the correct scope of the metrics if they are ‘forgotten’ on the organization’s bulletin board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y9rKYAED7esFID04" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So I turn again to Kelle O’Neal, who teaches us that we don’t need to measure everything, she says: <em>“You just need to choose what is important and meaningful to your stakeholder group and your program”.</em></p><p>Therefore, when reflecting on mutual trust, engagement and stakeholders, it is almost impossible not to end our article by mentioning the spectacular phrase by Sheryl Sandberg, former COO of Facebook, who said:</p><p><em>“Speaking can transform minds, which can transform behaviors, which can transform institutions.”</em></p><p>References:</p><p>[1] Suriya N Subramanian, Simple Metrics for a Successful Data Governance</p><p>available online: <a href="https://www.linkedin.com/pulse/simple-metrics-successful-data-governance-suriya-n-subramanian-fcca/">https://www.linkedin.com/pulse/simple-metrics-successful-data-governance-suriya-n-subramanian-fcca/</a></p><p>[2] DAMA — DMBOK — 2nd Edition(2017)</p><p>[3] liz henderson, Treading Water in Your Data Efforts?</p><p>available on line:</p><p><a href="https://lizhendersondata.wordpress.com/2015/10/26/treading-water-in-your-data-efforts/">https://lizhendersondata.wordpress.com/2015/10/26/treading-water-in-your-data-efforts/</a></p><p>[4] 35 Metrics You Should Use to Monitor Data Governance</p><p>available online: <a href="https://datafloq.com/read/35-metrics-monitor-data-governance/1601">https://datafloq.com/read/35-metrics-monitor-data-governance/1601</a></p><p>[5] John Ladley, DATA GOVERNANCE — How to Design, Deploy, and Sustain an Effective Data Governance Program (2012), Elsevier Inc.</p><p>[6] Data Governance Program Effectiveness by the Numbers, By <a href="https://www.dataversity.net/author/amber-dennis/">Amber Lee Dennis</a> on <a href="https://www.dataversity.net/data-governance-program-effectiveness-numbers/">September 6, 2017</a></p><p>available online: <a href="https://www.dataversity.net/data-governance-program-effectiveness-numbers/">https://www.dataversity.net/data-governance-program-effectiveness-numbers/</a></p><p>[7] Monise Carla, O que é análise crítica de indicadores?</p><p>available online: <a href="https://blogdaqualidade.com.br/o-que-e-analise-critica-de-indicadores/">https://blogdaqualidade.com.br/o-que-e-analise-critica-de-indicadores/</a></p><p>[8] Articles by Matt Mead, Matt Mead is the Chief Technology Officer at SPR Consulting.</p><p>available online: <a href="https://spr.com/author/matt/">https://spr.com/author/matt/</a></p><p>[9] Articles by John Edwards</p><p>Available online: <a href="https://www.cio.com/article/3639530/7-data-governance-mistakes-to-avoid.html">https://www.cio.com/article/3639530/7-data-governance-mistakes-to-avoid.html</a></p><p>[10] <a href="https://kalendae.com.br/blog/cobit-gerenciamento-da-ti/">https://kalendae.com.br/blog/cobit-gerenciamento-da-ti/</a></p><p><a href="https://kalendae.com.br/blog/cobit-2019/">https://kalendae.com.br/blog/cobit-2019/</a></p><p>[11] John Doerr, Measure What Matters (2018), Portfolio/Penguin</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce2c066a2070" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>