<?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 Leonard de Assis on Medium]]></title>
        <description><![CDATA[Stories by Leonard de Assis on Medium]]></description>
        <link>https://medium.com/@ldeassis?source=rss-f66426153337------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*11DqYJ-cf_sv0UZ8.jpg</url>
            <title>Stories by Leonard de Assis on Medium</title>
            <link>https://medium.com/@ldeassis?source=rss-f66426153337------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:35:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ldeassis/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[Não há cangurus na Áustria]]></title>
            <link>https://medium.com/@ldeassis/n%C3%A3o-h%C3%A1-cangurus-na-%C3%A1ustria-18b4087acf80?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b4087acf80</guid>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 15:33:13 GMT</pubDate>
            <atom:updated>2025-09-11T15:33:13.290Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Leonard Assis</strong></p><p>Desde pequeno, eu queria muito ter um canguru de estimação. Não um cachorro, não um gato. Um canguru. Talvez fosse o jeito como eles pulam com elegância, ou aquele olhar curioso que parece sempre pronto para uma conversa. Enquanto meus colegas sonhavam com videogames ou bicicletas, eu sonhava com um marsupial no quintal — quem sabe até com nome australiano, tipo Bruce ou Matilda.</p><p>O tempo passou, e em vez de zoologia, fui parar no mundo dos dados. Hoje sou profissional de analytics — o tipo de pessoa que vê beleza em uma planilha bem estruturada e emoção em uma curva de tendência. Mas o canguru nunca saiu do radar. Ele virou personagem recorrente nas minhas ideias, nos meus dashboards imaginários, e até nas metáforas que uso em reuniões:<br> “Vamos dar um salto estratégico, igual a um canguru bem treinado.”</p><p>À primeira vista, dados e cangurus parecem habitar mundos distintos — um vive em planilhas, o outro no outback australiano. Mas olhe mais de perto, e verá que ambos têm algo em comum: eles pulam.</p><p>Os cangurus não caminham — eles saltam. E os dados também. Eles não se movem em linha reta, mas em saltos de significado, revelando padrões, tendências e histórias ocultas. Um canguru pode cobrir até nove metros com um único impulso. Um dado bem tratado pode atravessar anos de confusão com uma única inferência bem colocada.</p><p>E o salto não é aleatório: um canguru acumula energia, calcula o ângulo e projeta a distância. É quase um modelo preditivo em ação, estimando a próxima posição a partir do presente. Assim como uma regressão, ele considera as condições atuais para prever onde irá cair. Às vezes erra, claro — há variação, há ruído. Mas mesmo no erro, há aprendizado: é o equivalente estatístico de um intervalo de confiança.</p><p>Ambos também vivem em clusters. Os vermelhos dominam o interior árido; os cinzentos, as florestas tropicais; outros preferem a costa. É como se a natureza rodasse um algoritmo silencioso de classificação, agrupando espécies conforme variáveis de cor, altura e habitat. Cada canguru encontra seu grupo quando olhamos pelas variáveis certas.</p><p>E há mais: o tempo. Os saltos se encadeiam como uma série temporal, cada ponto dependente do anterior. Da mesma forma, as populações de cangurus oscilam com o clima e a vegetação, subindo e descendo como curvas de tendência. Um inverno rigoroso pode reduzir um cluster inteiro, enquanto uma primavera úmida faz a curva disparar para cima.</p><p>No fundo, penso que um canguru é quase um modelo bayesiano ambulante. A cada salto, atualiza suas crenças sobre o terreno: se a grama está firme, se há predadores por perto, se a direção escolhida ainda faz sentido. É a pura essência da estatística bayesiana — cada nova evidência ajusta a probabilidade de chegar mais longe.</p><p>Em 2023, viajei para a Europa com minha esposa. O roteiro incluía Espanha, Hungria, República Tcheca e… Áustria! Viena era charmosa, os cafés eram acolhedores, e os alpes pareciam saídos de um cartão-postal. Mas o que me marcou mesmo foi a primeira placa que vi ao entrar numa loja de souvenirs:</p><blockquote>No kangaroos in Austria.</blockquote><p>Sim, em inglês. Uma frase direta, quase defensiva, como quem diz: “Antes que você pergunte, não — aqui não tem cangurus.” Ri alto. A Áustria, cansada de ser confundida com a Austrália, resolveu deixar claro logo na entrada. E ali, entre chaveiros e canecas, percebi que meu sonho de infância tinha virado piada turística.</p><p>De volta ao Brasil, decidi transformar essa paixão em projeto. Mergulhei em bases de dados públicas australianas, como o Atlas of Living Australia e os registros do governo. Descobri que há entre 42 e 50 milhões de cangurus na Austrália — quase o dobro da população humana do país. A maior concentração está na costa leste, onde o clima é mais ameno e a vegetação mais abundante. O canguru vermelho domina o interior árido, enquanto os cinzentos preferem as florestas tropicais.</p><p>Criei séries históricas, correlações climáticas, análises que mais pareciam acompanhar um grande rebanho de modelos estatísticos pulando pelo território. E ali, entre probabilidades e inferências, percebi que meu sonho infantil tinha se transformado em storytelling analítico. Um salto — literal e figurado — entre o desejo e o dado.</p><p>Hoje, quando alguém me pergunta por que gosto tanto de cangurus, eu sorrio e respondo:</p><blockquote>Porque eles pulam como os dados bem tratados — com propósito, direção e leveza.</blockquote><p>E se alguém ainda confundir Áustria com Austrália, eu mostro a foto da placa e digo:</p><blockquote>Não há cangurus na Áustria. Mas há muitos nos meus modelos, minhas análises, em tudo que faço</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b4087acf80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Compositional Data in Analytics: Foundations, Pitfalls, and Practical Modeling Workflow]]></title>
            <link>https://medium.com/@ldeassis/compositional-data-in-analytics-foundations-pitfalls-and-practical-modeling-workflow-9152e93eeeaf?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/9152e93eeeaf</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 12:31:58 GMT</pubDate>
            <atom:updated>2025-08-19T12:31:58.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VJEeSigEqt7Ei1lsEsthg.png" /></figure><p>In analytics and statistics, <strong>compositional data</strong> form a unique and often misunderstood class of information. These datasets consist of parts of a whole, where each observation is a vector of positive values constrained to sum to a constant — typically 1 or 100%. This constraint introduces a geometry that violates the assumptions of traditional statistical methods, making compositional data both challenging and essential to handle correctly.</p><h3>🧭 What Are Compositional Data?</h3><p>At their core, compositional data are <strong>relative</strong>. The absolute magnitude of each component carries little meaning in isolation; what matters is the proportion of one part relative to the others.</p><p>This relative nature appears across diverse domains:</p><ul><li><strong>Agriculture</strong>: Soil composition as the proportions of sand, silt, and clay</li><li><strong>Economics</strong>: Household budgets distributed across housing, food, transportation, and other categories</li><li><strong>Geology</strong>: Rocks expressed as the relative abundance of minerals</li><li><strong>Microbiome research</strong>: The share of different bacterial species in a sample</li><li><strong>Marketing</strong>: Allocation of campaign spending across multiple channels</li></ul><p>The key point: compositional data describe <em>trade-offs</em>. If one part grows, at least one other must shrink.</p><h3>📊 Why Compositional Data Matter</h3><p>Compositional data are everywhere. Their importance comes from the way they reveal systems governed by <strong>interdependence</strong>. Unlike unconstrained variables, these values cannot vary independently — an increase in one component forces a decrease in others.</p><p>This constraint leads to pitfalls. A naive correlation between two components might appear strong simply because of the constant-sum structure, not because of a genuine relationship. Applying regression or clustering directly on raw percentages can therefore yield misleading conclusions.</p><h3>⚠️ Frequent Pitfalls</h3><p>Some of the most common mistakes when working with compositional data include:</p><ul><li><strong>Treating raw data as unconstrained</strong>: Applying standard models directly leads to spurious results</li><li><strong>Ignoring the relative scale</strong>: Interpreting absolute values instead of proportional changes</li><li><strong>Mishandling zeros</strong>: Log-ratio transformations fail with zeros present</li><li><strong>Choosing poor transformations</strong>: For example, ALR with a weak reference part</li><li><strong>Forgetting the geometry</strong>: Back-transformed predictions must respect the compositional structure</li><li><strong>Feeding raw data into ML pipelines</strong>: Algorithms like decision trees or neural networks can misinterpret constrained relationships</li></ul><h3>🔄 Transformations: ALR, CLR, and ILR</h3><p>To analyze compositional data properly, we need to map them from the <strong>simplex</strong> (their constrained space) into <strong>Euclidean space</strong>, where conventional statistical methods apply. Three main log-ratio transformations are used:</p><p><strong>ALR (Additive Log-Ratio)</strong></p><ul><li>Uses one component as a reference, computing log-ratios of all others relative to it</li><li>✅ Simple, intuitive, interpretable</li><li>❌ Highly dependent on the chosen reference</li></ul><p><strong>CLR (Centered Log-Ratio)</strong></p><ul><li>Computes log-ratios of each component relative to the geometric mean of all components</li><li>✅ Symmetric, useful for visualization and exploratory analysis</li><li>❌ Data remain in a subspace, which complicates regression or machine learning</li></ul><p><strong>ILR (Isometric Log-Ratio)</strong></p><ul><li>Projects data into an orthonormal basis that preserves distances</li><li>✅ Statistically rigorous, ideal for ML and inferential models</li><li>❌ Less intuitive interpretation for domain experts</li></ul><h3>🚫 The Challenge of Zeros</h3><p>Zeros pose a significant issue: log-ratios require strictly positive values. But zeros can arise for several reasons:</p><ul><li><strong>Structural zeros</strong>: True absence of a component</li><li><strong>Rounded zeros</strong>: Values below a detection limit</li><li><strong>Missing zeros</strong>: Measurement or recording errors</li></ul><p>Possible solutions include:</p><ul><li><strong>Multiplicative replacement</strong>: Substitute zeros with small positive values</li><li><strong>Bayesian imputation</strong>: Estimate values using model-based approaches</li></ul><p>The method chosen depends on whether zeros are meaningful absences or artifacts of measurement.</p><h3>🛠️ A Practical Workflow for Compositional Data Analysis</h3><p>A disciplined workflow helps avoid the most common mistakes:</p><ol><li><strong>Identify the structure</strong>: Are variables constrained parts of a whole?</li><li><strong>Address zeros</strong>: Replace or impute them based on domain knowledge</li><li><strong>Choose a transformation</strong>: CLR for exploration, ALR for interpretability, ILR for modeling</li><li><strong>Apply standard methods</strong>: Regression, clustering, ML — on the transformed data</li><li><strong>Interpret carefully</strong>: Focus on <em>relative</em> changes, not absolutes</li><li><strong>Back-transform results</strong>: Ensure final outputs respect the constant-sum constraint</li></ol><h3>🐍 Python Example: Transforming Compositional Data</h3><pre>import numpy as np<br>from skbio.stats.composition import clr, alr, ilr, multiplicative_replacement<br><br># Example compositional dataset (3-part composition)<br>X = np.array([<br>    [0.2, 0.3, 0.5],<br>    [0.1, 0.4, 0.5],<br>    [0.25, 0.25, 0.5]<br>])<br><br># Step 1: Replace zeros if necessary<br>X_replaced = multiplicative_replacement(X)<br><br># Step 2: Apply transformations<br>X_clr = clr(X_replaced)          # Centered Log-Ratio<br>X_alr = alr(X_replaced)          # Additive Log-Ratio<br>X_ilr = ilr(X_replaced)          # Isometric Log-Ratio<br><br>print(&quot;CLR:\n&quot;, X_clr)<br>print(&quot;ALR:\n&quot;, X_alr)<br>print(&quot;ILR:\n&quot;, X_ilr)</pre><h3>🧠 Final Thoughts</h3><p>Compositional data are not a statistical niche — they are everywhere. From soil nutrients to consumer spending, they encode insights about trade-offs and balances in real systems. But they demand respect for their geometry.</p><p>By identifying them, applying the right transformations, and interpreting results in relative terms, analysts can unlock powerful and accurate models.</p><p>As data science matures, <strong>mastering compositional data analysis is becoming a core competency</strong>. In the end, ratios are not restrictions — they are the language of balance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9152e93eeeaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Pitfalls of Log Transforming Signed Data: Why `np.sign(x)]]></title>
            <link>https://medium.com/@ldeassis/the-hidden-pitfalls-of-log-transforming-signed-data-why-np-sign-x-74e394e4dde2?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/74e394e4dde2</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 14:25:49 GMT</pubDate>
            <atom:updated>2025-08-18T14:25:49.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Hidden Pitfalls of Log Transforming Signed Data: Why `np.sign(x) * log(abs(x))` Can Break Your Pipeline ⚠️</h3><h3>🧩 Introduction</h3><p>This has happened to me a few times.<br>And it made me think about how to solve this problem.</p><p>Logarithmic transformations are a cornerstone of data preprocessing. They help stabilize variance, reduce right-skewness, and make multiplicative relationships additive. In regression, for example, log-transformed predictors often reduce heteroskedasticity and yield interpretable elasticities.</p><p>But there’s a catch: the logarithm is only defined for **positive real numbers**. So what happens when your dataset contains negatives or zeros?</p><p>A common “hack” looks like this:</p><pre>np.sign(x) * np.log(np.abs(x) + ε)</pre><p>This trick seems elegant. It preserves the sign and applies a log transform to the magnitude. But under the hood, it’s unstable, non-invertible, and can wreak havoc on your statistical pipeline.</p><h3>🧨 The Problem: Small Values and Unstable Inversion</h3><p>Imagine values between **−0.01 and +0.01**. After applying the signed log transform, these tiny values explode into large positive or negative numbers.</p><p>Now try to invert them:</p><pre>np.sign(x) * (np.exp(np.abs(x)) - ε)</pre><p>Instead of returning something close to ±0.01, the values inflate to around ±90. This isn’t a floating-point error — it’s a mathematical inevitability.</p><p>The problem is that <strong>logs compress large values but stretch small ones</strong>. Near zero, tiny differences are exaggerated; inversion via the exponential only amplifies the distortion. And if your transformed data is normalized, passed through PCA, or perturbed by noise, the sign itself may flip, further corrupting the reconstruction.</p><h3>🔍 The Statistical Explanation</h3><p>Why does this happen? Let’s reframe it in statistical terms:</p><ul><li><strong>Variance stabilization backfires</strong>: Classic log transforms stabilize variance in multiplicative processes. But the signed version <strong>inflates variance</strong> near zero.</li><li><strong>Non-bijective mapping</strong>: A good transformation should be monotonic and bijective on its domain. The signed log is neither. Multiple small inputs collapse to similar outputs, making inversion ill-posed.</li><li><strong>Distorted correlation structure</strong>: Feeding signed-log features into PCA or regression alters covariance relationships, potentially introducing spurious dependencies.</li><li><strong>Noise amplification</strong>: Measurement noise near zero is disproportionately magnified, converting Gaussian noise into heavy-tailed behavior — violating assumptions of many models.</li></ul><p>In short: what looks like a harmless one-liner is mathematically fragile.</p><h3>🧪 Edge Cases That Break It</h3><ul><li><strong>Zero values</strong> → With ε, zero maps to log(ε)`. On inversion, all such cases collapse to the same constant.</li><li><strong>Near-zero noise</strong> → Small Gaussian noise flips signs unpredictably after transformation.</li><li><strong>Normalization layers</strong> → Once standardized or PCA-transformed, the connection between sign and magnitude collapses entirely.</li></ul><p>These issues aren’t rare — they’re inherent to the transformation.</p><h3>✅ Robust Alternatives</h3><p>So what should you use instead? Here are three statistically sound alternatives:</p><h4><strong>Yeo–Johnson Transformation</strong>:</h4><p>A generalization of Box–Cox that supports negative values; Smooth, monotonic, and invertible, and Available in scikit-learn:</p><pre>from sklearn.preprocessing import PowerTransformer<br>pt = PowerTransformer(method=&quot;yeo-johnson&quot;)</pre><h4><strong>Two-channel decomposition:</strong></h4><p>Split the variable into positive and negative parts:</p><pre>- `x_pos = log(x) if x &gt; 0 else 0`<br>- `x_neg = log(-x) if x &lt; 0 else 0`</pre><ul><li>Treat them as two separate nonnegative features.</li><li>Inversion is trivial and information-preserving.</li></ul><h4>Inverse Hyperbolic Sine (asinh)</h4><ul><li>Defined on the entire real line.</li><li>Behaves like `log(2x)` for large |x|, but remains well-behaved near zero.</li><li>Widely used in econometrics for stabilizing variance in signed data.</li></ul><p>Each of these maintains the core benefits of log transformations — variance stabilization, interpretability, monotonicity — without introducing the instability of the signed log trick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_xiRqT0Msvnr5cBZ87btA.jpeg" /><figcaption>Instability of the Signed Log vs. Robust Alternatives</figcaption></figure><p>The plots above illustrate why the signed log transformation is fragile and why alternatives like <strong>asinh</strong> and <strong>Yeo–Johnson</strong> are more reliable.</p><ul><li><strong>(Top-left: Transformations across the full domain)</strong><br> All three methods compress large magnitudes, but the signed log produces sharp discontinuities around zero. Asinh and Yeo–Johnson remains smooth across the entire real line.</li><li><strong>(Top-right: Zoom near zero)</strong><br> Here the instability becomes obvious. Values close to zero are mapped to extreme outputs under the signed log, while asinh and Yeo–Johnson preserve continuity and scale more gently.</li><li><strong>(Bottom-left: Inversion failure of signed log)</strong><br> Attempting to invert the signed log reveals catastrophic distortion. Small values (e.g., ±0.01) inflate into much larger numbers, demonstrating that the transformation is not reliably reversible.</li><li><strong>(Bottom-right: Behavior on larger magnitudes)</strong><br> For |x| ≥ 1, all transforms behave more stably. This explains why the signed log “seems fine” in many practical cases — but the breakdown near zero still undermines robustness in real-world pipelines.</li></ul><p>Together, these figures highlight a crucial insight: <strong>the signed log transform is not monotonic, not bijective, and not statistically safe near zero</strong>. If your data includes both positive and negative values, methods like <strong>Yeo–Johnson</strong> or <strong>asinh</strong> should be your default choice.</p><h3>🧠 Final Thoughts</h3><p>The signed log transform may look clever, but it’s a statistical landmine. Near zero, it amplifies noise, breaks invertibility, and corrupts relationships between variables.</p><p>If your pipeline values **stability, interpretability, and robustness**, steer clear of `np.sign(x) * log(abs(x))`. Instead, use Yeo–Johnson, asinh, or a split-channel approach.</p><p>Preprocessing is not just about making numbers “fit.” It’s about preserving the statistical properties of your data so your models learn from reality — not artifacts.</p><h3>📚 References</h3><ul><li>Box, G. E. P., &amp; Cox, D. R. (1964). <em>An Analysis of Transformations</em>. Journal of the Royal Statistical Society.</li><li>Yeo, I.-K., &amp; Johnson, R. A. (2000). <em>A new family of power transformations to improve normality or symmetry</em>. Biometrika.</li><li>Burbidge, J. B., Magee, L., &amp; Robb, A. L. (1988). <em>Alternative transformations to handle extreme values of the dependent variable</em>. Journal of the American Statistical Association.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74e394e4dde2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DuckDB for Data Scientists: The In-Memory Analytics Engine You Didn’t Know You Needed]]></title>
            <link>https://medium.com/@ldeassis/duckdb-for-data-scientists-the-in-memory-analytics-engine-you-didnt-know-you-needed-598e0f163b34?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/598e0f163b34</guid>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 15:50:30 GMT</pubDate>
            <atom:updated>2025-08-11T15:50:30.827Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently came across DuckDB for the first time. I thought it was just another option for working with dataframes in Python, but no! It pleasantly surprised me. Find out why in this post.</p><h3>What is DuckDB?</h3><p>DuckDB is an <strong>in-process analytical database management system</strong> designed for fast, OLAP-style queries on large datasets. Think of it as the <strong>SQLite of analytics</strong> — lightweight, embeddable, and incredibly fast for complex analytical workloads.</p><p>Unlike traditional database servers, DuckDB runs <strong>inside your Python process</strong> (or R, or C++), with no need for a separate service. This makes it ideal for data science workflows where you want SQL power without operational overhead.</p><p>It is columnar, optimized for analytics, and integrates seamlessly with existing workflows. You can run complex SQL queries directly on your data files, whether they are local or stored in the cloud.</p><h3>How It Works Compared to Pandas</h3><p>From a data scientist’s perspective, DuckDB and Pandas aim to solve overlapping but different problems.</p><p>Pandas is a Python-native library, row-oriented by default, and uses Python’s data structures to manipulate dataframes. It is extremely flexible but loads the entire dataset into memory, which can be limiting for large datasets.</p><p>DuckDB, on the other hand, is columnar and optimized for analytical queries. It can read data directly from disk without loading it entirely into memory, allowing you to work efficiently with datasets that would be slow or impossible to handle in Pandas. DuckDB also executes queries in parallel and uses vectorized execution, making it significantly faster for joins, aggregations, and filtering large datasets.</p><p>In practice, you might use Pandas for data manipulation that requires Python functions or complex transformations, but switch to DuckDB when you need SQL’s expressiveness and performance on large datasets.</p><p>Example:</p><pre># Pandas style: load entire CSV into memory<br>import pandas as pd<br>df = pd.read_csv(&#39;big_data.csv&#39;)<br>result = df.groupby(&#39;category&#39;)[&#39;value&#39;].mean()<br><br>import duckdb<br># DuckDB style: query CSV directly without full load<br>result = duckdb.query(&quot;&quot;&quot;<br>    SELECT category, AVG(value) as avg_value<br>    FROM &#39;big_data.csv&#39;<br>    GROUP BY category<br>&quot;&quot;&quot;).to_df()</pre><h3>File Formats Supported</h3><p>One of DuckDB’s strengths is that it can query multiple file formats directly, without an import step. It supports CSV and TSV, Parquet with predicate pushdown and column pruning, JSON and JSONL including nested structures, Arrow and Feather formats, SQLite databases, and even modern table formats like Delta Lake and Iceberg through extensions.</p><p>DuckDB also integrates with cloud object storage such as Amazon S3, Google Cloud Storage, and Azure Blob Storage, allowing you to run SQL queries directly against files in the cloud.</p><p>Example: Querying a Parquet file directly from S3</p><pre>duckdb.query(&quot;&quot;&quot;<br>    SELECT *<br>    FROM read_parquet(&#39;s3://my-bucket/data/*.parquet&#39;,<br>                      AWS_REGION=&#39;us-east-1&#39;,<br>                      AWS_ACCESS_KEY_ID=&#39;...&#39;,<br>                      AWS_SECRET_ACCESS_KEY=&#39;...&#39;)<br>&quot;&quot;&quot;)</pre><h3>Main Commands and Patterns</h3><p>DuckDB supports the full SQL-92 standard, along with advanced features like window functions and CTEs.</p><h4><strong>Selecting and Filtering</strong></h4><pre>SELECT name, age<br>FROM people<br>WHERE age &gt; 30<br>ORDER BY age DESC<br>LIMIT 10;</pre><h4><strong>Joins</strong></h4><pre>SELECT o.order_id, c.customer_name, o.amount<br>FROM orders o<br>JOIN customers c<br>  ON o.customer_id = c.id<br>WHERE o.amount &gt; 500;</pre><h4><strong>Aggregations</strong></h4><pre>SELECT category, COUNT(*) as total, AVG(price) as avg_price<br>FROM products<br>GROUP BY category<br>HAVING AVG(price) &gt; 100;</pre><h4><strong>Window Functions</strong></h4><pre>SELECT name, salary,<br>       RANK() OVER (ORDER BY salary DESC) as rank<br>FROM employees;</pre><h4>Insert, Delete and Update …</h4><p>Although DuckDB is primarily designed for <strong>read-heavy analytical workloads</strong> rather than transactional systems, it does support standard SQL commands for modifying data. This means you can create tables, insert rows, update values, and delete records — but in most data science workflows, these operations are used in <strong>temporary tables</strong> or <strong>staging datasets</strong>, rather than in persistent transactional databases.</p><p>You can add rows to duckDB just like any SQL database:</p><pre>CREATE TABLE people (id INTEGER, name VARCHAR, age INTEGER);<br><br>INSERT INTO people VALUES<br>(1, &#39;Alice&#39;, 32),<br>(2, &#39;Bob&#39;, 28);<br><br>-- Insert results from another query<br>INSERT INTO people<br>SELECT id, name, age FROM other_table WHERE age &gt; 30;</pre><p>You can often use INSERT o populate small in-memory tables for intermediate analysis steps or prototyping ETL logic.</p><p>DuckDB allows you to modify existing rows using UPDATE:</p><pre>UPDATE people<br>SET age = age + 1<br>WHERE name = &#39;Alice&#39;;</pre><p>Because DuckDB operates in a <strong>vectorized execution model</strong>, updates to large in-memory datasets can still be fast — but in analytics, this is more of a convenience feature than a core workflow.</p><p>o remove rows from a table:</p><pre>DELETE FROM people<br>WHERE age &lt; 30;</pre><p>If the WHERE clause is omitted, all rows in the table will be deleted. In analytical contexts, it’s more common to <strong>filter data in a query</strong> rather than physically deleting it.</p><p>While DuckDB supports these commands, they are not what makes DuckDB shine. Most data scientists use DuckDB to query existing datasets directly — often without altering the source files — and rely on SQL’s filtering, projection, and transformation capabilities to shape the data. However, when creating temporary datasets for simulation, testing, or intermediate ETL steps, the ability to INSERT, UPDATE, and DELETE in-memory is a powerful addition.</p><h4>… and CTE</h4><p>Common Table Expressions (CTEs) are a SQL feature that allows you to define <strong>temporary, named result sets</strong> that can be referenced within a query. In DuckDB, CTEs work exactly as they do in other SQL systems — but their value is especially high in analytics because they let you <strong>organize complex logic</strong> without materializing intermediate datasets.</p><p>A CTE is defined using the WITH keyword, and it exists only for the duration of the query in which it is used. This fits perfectly with DuckDB’s in-memory, analytical nature: you can chain transformations, aggregations, and joins without storing anything permanently.</p><pre>WITH high_value_orders AS (<br>    SELECT *<br>    FROM read_parquet(&#39;s3://my-bucket/orders.parquet&#39;)<br>    WHERE amount &gt; 1000<br>),<br>customer_totals AS (<br>    SELECT customer_id, COUNT(*) AS order_count<br>    FROM high_value_orders<br>    GROUP BY customer_id<br>)<br>SELECT c.customer_id, c.order_count<br>FROM customer_totals c<br>WHERE c.order_count &gt; 5;</pre><p>Here’s what’s happening:</p><ol><li><strong>high_value_orders</strong> filters the raw dataset to include only orders over 1000 units.</li><li><strong>customer_totals</strong> aggregates this filtered dataset to count orders per customer.</li><li>The final query filters to customers with more than five high-value orders.</li></ol><p><strong>Why CTEs Are Valuable in DuckDB for Data Science</strong></p><ul><li><strong>Readability</strong>: Complex analytical queries can be broken into logical steps, each with its own name.</li><li><strong>Reusability within a query</strong>: The same intermediate dataset can be referenced multiple times without repeating logic.</li><li><strong>No permanent storage required</strong>: Perfect for exploratory analysis and rapid prototyping.</li><li><strong>Combine with file reads</strong>: You can query directly from CSV, Parquet, or JSON in a CTE, then chain transformations.</li></ul><p><strong>Tip for Data Scientists</strong><br> CTEs in DuckDB have not materialized<strong> unless needed</strong> — they are optimized and merged into the final query plan whenever possible. This means you can use multiple layers of CTEs without worrying about performance degradation, as long as you keep your filtering and projection steps efficient.</p><h3>DuckDB in the Cloud</h3><p>Since DuckDB is not a server but an embedded database, there is no “deploy to cloud” process in the traditional sense. However, it integrates exceptionally well with cloud-based data lakes and serverless environments.</p><p>You can query files directly from S3, GCS, or Azure Blob without downloading them first. DuckDB also runs efficiently inside AWS Lambda, Google Cloud Functions, and Azure Functions, making it perfect for lightweight ETL tasks. Through extensions, it supports reading from Delta Lake and Apache Iceberg tables stored in the cloud.</p><p>Example: Query multiple Parquet files stored in GCS</p><pre>duckdb.query(&quot;&quot;&quot;<br>    SELECT user_id, SUM(amount) as total_spent<br>    FROM read_parquet(&#39;gs://my-bucket/sales/*.parquet&#39;,<br>                      GOOGLE_APPLICATION_CREDENTIALS=&#39;/path/key.json&#39;)<br>    GROUP BY user_id<br>&quot;&quot;&quot;)</pre><h3>Conclusions</h3><p>DuckDB offers an elegant, high-performance alternative for data scientists who want SQL speed without infrastructure headaches. It is fast, lightweight, flexible, and interoperable with multiple tools and data formats.</p><p>It is not meant to replace Pandas or Spark in every scenario, but for medium-to-large analytical datasets that fit in memory or can be streamed from disk, DuckDB can be the simplest and fastest option available.</p><p>If your current workflow still relies on Pandas for heavy aggregations, it’s worth trying DuckDB. You may find it becomes your <strong>secret performance weapon</strong> for analytical workloads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=598e0f163b34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development in Python: A Practical Guide for Intermediate Developers]]></title>
            <link>https://medium.com/@ldeassis/test-driven-development-in-python-a-practical-guide-for-intermediate-developers-fed4a41bf04e?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed4a41bf04e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 16:10:57 GMT</pubDate>
            <atom:updated>2025-08-10T16:10:57.229Z</atom:updated>
            <content:encoded><![CDATA[<p>Test-Driven Development (TDD) is more than just a testing strategy — it’s a mindset that encourages clean design, robust code, and confidence in refactoring. If you’re comfortable with Python and basic unit testing, this guide will help you elevate your development workflow using TDD.</p><h3>What Is TDD?</h3><p>TDD is a software development process where tests are written before the actual code. The workflow follows a simple cycle:</p><ol><li><strong>Red</strong> — Write a test that fails.</li><li><strong>Green</strong> — Write the minimal code to make the test pass.</li><li><strong>Refactor</strong> — Clean up the code while keeping the test green.</li></ol><p>This cycle enforces discipline and ensures that every piece of functionality is covered by a test.</p><h3>Why Use TDD?</h3><ul><li>Forces you to think about design before implementation</li><li>Encourages modular, decoupled code</li><li>Makes refactoring safer</li><li>Improves documentation through tests</li><li>Reduces bugs and regressions</li></ul><h3>Setting Up Your Environment</h3><p>You can use Python’s built-in unittest module, but for a more expressive and modern experience, pytest is highly recommended.</p><p>Install pytest:</p><pre>pip install pytest</pre><p>Directory structure:</p><pre>project/<br> ├── app.py<br> └── tests/<br>       └── test_app.py</pre><h3>Step-by-Step TDD Example: Building a Calculator</h3><p>Let’s build a simple calculator using TDD. We’ll start with a soma (sum) function.</p><h4>Step 1: Write a Failing Test</h4><p>Create tests/test_app.py:</p><pre>from app import soma<br>def test_soma_dois_numeros():<br>  assert soma(2, 3) == 5</pre><p>Run the test:</p><pre>pytest</pre><p>You’ll get an ImportError or NameError because soma doesn’t exist yet. That’s expected.</p><h4>Step 2: Make the Test Pass</h4><p>Create app.py:</p><pre>def soma(a, b):<br>  return a+b</pre><p>Run the test again:</p><pre>pytest</pre><p>Now the test should pass. You’ve completed the Red-Green cycle.</p><h4>Step 3: Refactor</h4><p>There’s not much to refactor here, but in more complex scenarios, this is where you clean up logic, rename variables, or improve performance — without changing behavior.</p><p>Expanding the Calculator</p><p>Let’s add subtraction, multiplication, and division, using TDD for each.</p><p>Subtraction</p><pre># tests/test_app.py<br>from app import subtrai<br><br>def test_subtrai_dois_numeros():<br>  assert subtrai(5, 3) == 2</pre><pre># app.py<br>def subtrai(a, b):<br>  return a - b</pre><p>Repeat the cycle for multiplication and division.</p><h4>Edge Cases</h4><p>Don’t forget to test edge cases:</p><pre>def test_divisao_por_zero():<br>  with pytest.raises(ZeroDivisionError):<br>    divide(10, 0)</pre><p>This ensures your code handles exceptions gracefully.</p><h4>Best Practices</h4><ul><li>Write small, focused tests</li><li>Name tests descriptively</li><li>Test both expected and unexpected inputs</li><li>Keep tests fast and isolated</li><li>Use fixtures for setup if needed</li></ul><h4>When TDD Might Not Be Ideal</h4><p>While TDD is powerful, it’s not always the best fit:</p><ul><li>For exploratory coding or prototyping</li><li>When requirements are unclear</li><li>In performance-critical code where micro-optimizations matter</li></ul><p>Use TDD when correctness, maintainability, and confidence in refactoring are priorities.</p><h3>TDD in Data &amp; Analytics: Why It Matters</h3><p>In the world of Data &amp; Analytics, the stakes are high. Decisions are made based on insights derived from data pipelines, statistical models, and machine learning algorithms. A single bug in a transformation step or a miscalculated metric can lead to flawed conclusions and costly mistakes. This is where Test-Driven Development becomes invaluable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJgndYhQ0wMn9z2o9S6-SA.png" /></figure><h4>Ensuring data integrity</h4><p>Data pipelines often involve multiple stages: extraction, transformation, loading (ETL), and analysis. TDD helps validate each stage by enforcing tests that check:</p><ul><li>Schema consistency</li><li>Null or missing value handling</li><li>Correctness of transformations</li><li>Aggregation logic</li></ul><p>By writing tests before implementing transformations, you ensure that your pipeline behaves as expected even as data evolves.</p><h4>Validating business logic</h4><p>Analytics often encode business rules — such as revenue calculations, churn definitions, or segmentation criteria. TDD allows you to formalize these rules in tests, making them explicit and verifiable. This reduces ambiguity and ensures that your logic aligns with stakeholder expectations.</p><h4>Confidence in refactoring</h4><p>Data workflows are frequently updated to accommodate new sources, metrics, or performance improvements. Without tests, refactoring becomes risky. With TDD, you can refactor confidently, knowing that your tests will catch regressions.</p><h4>Reproducibility and documentation</h4><p>Tests serve as executable documentation. They show how data should behave under specific conditions, which is especially useful in collaborative environments or when onboarding new team members.</p><h4>Applying TDD in analytics workflows</h4><p>Here are some practical examples of TDD in analytics:</p><ul><li>Writing tests for SQL queries using tools like pytest and sqlite3</li><li>Validating Pandas DataFrames transformations</li><li>Testing statistical functions for edge cases and expected distributions</li><li>Ensuring machine learning preprocessing steps behave consistently</li></ul><p>Example:</p><pre>def test_normalize_column():<br> df = pd.DataFrame({&#39;value&#39;: [10, 20, 30]})<br> result = normalize(df[&#39;value&#39;])<br> expected = pd.Series([0.0, 0.5, 1.0])<br> pd.testing.assert_series_equal(result, expected)</pre><p>This test ensures that your normalization logic is correct and reproducible.</p><h3>Final Thoughts</h3><p>TDD isn’t just about writing tests — it’s about writing better software. By thinking through behavior before implementation, you build systems that are easier to maintain, extend, and trust. Python’s simplicity and tools like pytest make TDD a natural fit for developers who want to level up their craft.</p><p>If you’re ready to go deeper, try applying TDD to a real-world project: a REST API, a CLI tool, or even a game engine. The principles remain the same, and the benefits compound over time.</p><p>In Data &amp; Analytics, correctness is not optional — it’s foundational. TDD helps you build analytical systems that are reliable, maintainable, and trustworthy. Whether you’re building dashboards, predictive models, or ETL pipelines, adopting TDD will elevate the quality and impact of your work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed4a41bf04e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ The Random Bit Draw Problem: A Fun Exploration with C and C++]]></title>
            <link>https://medium.com/@ldeassis/the-random-bit-draw-problem-a-fun-exploration-with-c-and-c-04ca6702acd9?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/04ca6702acd9</guid>
            <category><![CDATA[random]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[rng]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 14:50:53 GMT</pubDate>
            <atom:updated>2025-07-26T14:50:53.041Z</atom:updated>
            <content:encoded><![CDATA[<p>I have no gift for teaching. Not due to lack of knowledge or skill, but because I’m extremely demanding — especially with myself. In the early 2000s, I worked for about five years in the gambling industry, where I constantly pushed myself to find the most efficient ways to generate numbers for casino games.</p><p>Inspired by that period, I recently came up with a playful scenario involving random number generation. And rather than simply generating random integers in sequence, I thought: why not add a bit of algorithmic challenge and explore some computer science?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihmMOWnFNCc26nxZRR8Kvg.png" /></figure><h3>The Challenge</h3><p>Imagine a process where we need to draw 4 integers between 0 and \(2^{15}-1\) — easy, right?</p><p>But here’s the twist: <br>Let’s impose a constraint — the **total number of 1s across all 4 binary numbers must be exactly 30**. Still doable. But we also want each of the 60 bits (4 × 15 bits) to have an equal probability of being selected.</p><h3>Formal constraints</h3><ul><li>Draw 4 integers between 0 and \(2^{15}−1\) (i.e., 15-bit numbers).</li><li>The sum of all **1-bits** across the 4 integers must be <strong>exactly 30.</strong></li><li>These 30 bits must be randomly distributed among the 60 available bits.</li><li>Each of the 60 bits must have <strong>equal probability</strong> of being selected.<br>- The draw must be <strong>reproducible</strong> (e.g., via a fixed random seed).</li></ul><p>This problem is fascinating because it blends <strong>randomness</strong>, <strong>bit-level constraints</strong>, and <strong>combinatorial thinking</strong> — all fundamental concepts in computer science, especially in embedded systems and algorithm design.</p><h3>Implementation Strategy</h3><p>Here’s my simple plan to implement it:</p><ol><li>Generate a bit array with exactly 30 ones and 30 zeros (total: 60 bits).</li><li>Shuffle the 60 bits uniformly.</li><li>Split them into 4 blocks of 15 bits.</li><li>Convert each block into an integer.</li><li>Done! You now have 4 integers with exactly 30 bits set to 1, evenly and randomly distributed.</li></ol><h3>Language Comparison</h3><p>How would this problem behave in different programming languages?</p><h4>Python</h4><p>The main challenges are how to deal with slow at bit-level manipulation and it needs more care with large ints.</p><p>The advantages are clean code, we can use libraries like `random` and `bitarray` but … The performance is not ideal</p><h4>C and C++</h4><p>In C we must deal with Manual memory and take care with type control. In other hand, code is extremely fast, and we have full control over bits with the function rand() but … C is verbose and prone to pointer-related bugs.</p><p>C++ is like C, but supports bitset, vector and have a modern random. std::bitset , std::mt19937are easier and safer to use but … is slightly more complex than C.</p><h4>Java</h4><p>The Java native int types are 32-bit; because of this, we need to enforce 15-bit logic, and we may face an additional challenge when we start thinking about integers above 32-bit limit. On the other hand, this language can provide very strong types, a good RNG like Random and SecureRandom</p><p>Because of this, we will start implementing in C/C++</p><h3>Basic Implementation in C</h3><p>Here’s a rudimentary implementation in C:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;stdint.h&gt;<br>#include &lt;time.h&gt;<br><br>#define TOTAL_BITS 60<br>#define ONES 30<br>#define NUMS 4<br>#define BITS_PER_NUM 15<br><br>void shuffle(uint8_t *array, size_t n) {<br>    for (size_t i = n - 1; i &gt; 0; i--) {<br>        size_t j = rand() % (i + 1);<br>        uint8_t tmp = array[i];<br>        array[i] = array[j];<br>        array[j] = tmp;<br>    }<br>}<br><br>int main() {<br>    srand(42);  // Fixed seed for reproducibility<br><br>    uint8_t bits[TOTAL_BITS];<br>    for (int i = 0; i &lt; ONES; i++) bits[i] = 1;<br>    for (int i = ONES; i &lt; TOTAL_BITS; i++) bits[i] = 0;<br><br>    shuffle(bits, TOTAL_BITS);<br><br>    uint16_t numbers[NUMS] = {0};<br><br>    for (int i = 0; i &lt; NUMS; i++) {<br>        for (int j = 0; j &lt; BITS_PER_NUM; j++) {<br>            if (bits[i * BITS_PER_NUM + j]) {<br>                numbers[i] |= (1 &lt;&lt; j);<br>            }<br>        }<br>    }<br><br>    for (int i = 0; i &lt; NUMS; i++) {<br>        printf(&quot;Number %d: %u (bits = &quot;, i + 1, numbers[i]);<br>        for (int b = BITS_PER_NUM - 1; b &gt;= 0; b--) {<br>            printf(&quot;%d&quot;, (numbers[i] &gt;&gt; b) &amp; 1);<br>        }<br>        printf(&quot;)\\n&quot;);<br>    }<br><br>    return 0;<br>}</pre><p>And when we run this code, the output is:</p><pre>Number 1: 32547 (bits = 111111110111011)<br>Number 2: 31598 (bits = 111101101111110)<br>Number 3: 16287 (bits = 011111111000111)<br>Number 4: 14609 (bits = 011100010011001)</pre><p>We can see that the numbers have 13, 13, 12 and 8 bits respectively and add up to 30.</p><p>Let’s migrate to C++, for a safer and more expressive implementation:</p><pre>#include &lt;iostream&gt;<br>#include &lt;array&gt;<br>#include &lt;random&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;bitset&gt;<br><br>const int TOTAL_BITS = 60;<br>const int ONES = 30;<br>const int NUMS = 4;<br>const int BITS_PER_NUM = 15;<br><br>void generate(std::array&lt;int, NUMS&gt;&amp; numbers) {<br>    std::array&lt;uint8_t, TOTAL_BITS&gt; bits{};<br>    for (int i = 0; i &lt; ONES; ++i) bits[i] = 1;<br><br>    std::mt19937 rng(42); // Reproducibility<br>    std::shuffle(bits.begin(), bits.end(), rng);<br><br>    for (int i = 0; i &lt; NUMS; ++i) {<br>        int val = 0;<br>        for (int j = 0; j &lt; BITS_PER_NUM; ++j) {<br>            if (bits[i * BITS_PER_NUM + j]) {<br>                val |= (1 &lt;&lt; j);<br>            }<br>        }<br>        numbers[i] = val;<br>    }<br>}<br><br>void print(const std::array&lt;int, NUMS&gt;&amp; numbers) {<br>    for (int i = 0; i &lt; NUMS; ++i) {<br>        std::bitset&lt;BITS_PER_NUM&gt; b(numbers[i]);<br>        std::cout &lt;&lt; &quot;Number &quot; &lt;&lt; i + 1 &lt;&lt; &quot;: &quot; &lt;&lt; numbers[i]<br>                  &lt;&lt; &quot; (bits = &quot; &lt;&lt; b &lt;&lt; &quot;)\\n&quot;;<br>    }<br>}<br><br>int main() {<br>    std::array&lt;int, NUMS&gt; numbers;<br>    generate(numbers);<br>    print(numbers);<br>    return 0;<br>}</pre><p>the code output is:</p><pre>Number 1: 32547 (bits = 111111110111011)<br>Number 2: 31598 (bits = 111101101111110)<br>Number 3: 16287 (bits = 011111111000111)<br>Number 4: 14609 (bits = 011100010011001)</pre><h3>Advantages of the C++ version:</h3><ul><li>Uses std::array and std::bitset for safety and readability;</li><li>Modern RNG (std::mt19937, std::shuffle);</li><li>Safer and cleaner than raw C.</li></ul><h3>What’s next</h3><p>What if… we wanted to <strong>detect specific bit patterns</strong> within the generated numbers?</p><p>Stay tuned for the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04ca6702acd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vamos falar sobre PEP8 em Python?]]></title>
            <link>https://medium.com/@ldeassis/vamos-falar-sobre-pep8-em-python-9c09e621f724?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c09e621f724</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 14:08:00 GMT</pubDate>
            <atom:updated>2025-03-20T14:08:00.539Z</atom:updated>
            <content:encoded><![CDATA[<p>O Python é uma linguagem de programação conhecida por sua legibilidade e simplicidade. Isso é, em grande parte, devido à ênfase na clareza e na organização do código, algo que é refletido em um dos seus mais importantes documentos: a <strong>PEP 8</strong> (Python Enhancement Proposal 8), que define as diretrizes de estilo para a escrita de código Python. Neste artigo, exploraremos o que é o PEP 8, suas recomendações e as mais importantes para garantir que o código seja bem estruturado, legível e mantenha boas práticas de programação.</p><h3>O que é o PEP 8?</h3><p>O <strong>PEP 8</strong> é um conjunto de convenções de estilo para o código Python, desenvolvido por Guido van Rossum, o criador da linguagem, e mantido pela comunidade Python. O objetivo desse padrão é promover a legibilidade do código, facilitando a colaboração entre programadores e evitando confusões. O PEP 8 é amplamente adotado por desenvolvedores de Python, e muitas ferramentas de linters (como o pylint e flake8) ajudam a garantir que o código siga essas convenções.</p><h3>Principais Diretrizes do PEP 8</h3><p><strong>Indentação e Espaços em Branco</strong></p><p>A indentação é uma das regras mais importantes do PEP 8. Python usa a indentação para definir blocos de código, e não há chaves como em outras linguagens. Portanto, é crucial que a indentação seja consistente.</p><ul><li><strong>4 espaços por nível de indentação</strong>: Recomenda-se usar 4 espaços em vez de tabulações.</li><li><strong>Evite espaços em branco desnecessários</strong>: Não use espaços extras nas expressões, como antes ou depois de parênteses, colchetes ou chaves.</li></ul><p>Exemplo correto:</p><pre>def minha_funcao():     if True:         print(&quot;Tudo certo!&quot;)</pre><p><strong>Comprimento das Linhas</strong></p><p>Para garantir que o código seja legível e que se encaixe bem em diferentes tamanhos de tela, o PEP 8 recomenda que as linhas de código não ultrapassem <strong>79 caracteres</strong>.</p><p>Em casos excepcionais, como comentários e docstrings, o limite pode ser de <strong>72 caracteres</strong>.</p><p>Exemplo:</p><pre># Este é um comentário que segue o limite de 79 caracterespy</pre><p><strong>Nomes de Variáveis, Funções e Classes</strong></p><p>A PEP 8 define convenções claras para a nomeação de variáveis, funções e classes, com o objetivo de melhorar a legibilidade e a clareza do código.</p><ul><li><strong>Funções e variáveis</strong>: Utilize <strong>letras minúsculas</strong> e se necessário, separe palavras com <strong>underscores</strong> (snake_case).</li><li><strong>Classes</strong>: Utilize o estilo <strong>CapWords</strong> (também conhecido como CamelCase).</li><li><strong>Constantes</strong>: Use <strong>letras maiúsculas</strong> e separe palavras com <strong>underscores</strong> (UPPERCASE_SNAKE_CASE).</li></ul><p>Exemplo:</p><pre>def calcular_media(notas):     pass  class Estudante:     pass</pre><p><strong>Comentários e Docstrings</strong></p><p>O PEP 8 recomenda o uso adequado de comentários e docstrings para garantir que o código seja bem documentado e fácil de entender.</p><ul><li><strong>Comentários</strong>: Devem ser completos e começar com letras maiúsculas, seguidos de um espaço. Eles devem ser usados para explicar “por que” algo é feito, não o “como”.</li><li><strong>Docstrings</strong>: Para funções, classes e módulos, deve-se usar docstrings para descrever o comportamento do código. As docstrings devem ser sempre entre aspas triplas e começar com uma descrição concisa.</li></ul><p>Exemplo:</p><pre>def calcular_area(base, altura):<br>  &quot;&quot;&quot;Calcula a área de um triângulo.&quot;&quot;&quot;<br>  return (base * altura) / 2</pre><p><strong>Importações</strong></p><p>O PEP 8 especifica a ordem correta para importações de módulos: primeiro importações padrão, depois de bibliotecas de terceiros e, por fim, importações locais. Deve-se também deixar uma linha em branco entre cada grupo de importações.</p><p>Exemplo:</p><pre>import os<br>import sys<br>import requests<br>from meu_modulo import minha_funcao</pre><p><strong>Evite Código Complexo e Longo</strong></p><p>Em termos de legibilidade, o PEP 8 também aconselha evitar a complexidade excessiva. Isso significa que é preferível escrever código mais simples, dividido em funções pequenas, que sejam fáceis de entender e testar.</p><ul><li><strong>Quebre funções longas</strong>: Se uma função estiver se tornando muito longa, ela pode ser dividida em várias funções menores.</li><li><strong>Use variáveis claras</strong>: Escolha nomes que descrevam claramente o papel da variável no código.</li></ul><p><strong>Espaços em Branco em Expressões e Instruções</strong></p><p>Embora o PEP 8 incentive o uso de espaços para melhorar a legibilidade, ele também recomenda evitar o uso excessivo de espaços, como antes de um parêntese em uma chamada de função.</p><p>Exemplo correto:</p><pre>resultado = minha_funcao(arg1, arg2)</pre><h3>Por que seguir o PEP 8?</h3><p>A principal razão para seguir o PEP 8 é a <strong>legibilidade</strong>. Quando todos os desenvolvedores seguem as mesmas convenções, o código se torna mais fácil de ler, entender e manter. Além disso, quando diferentes programadores colaboram no mesmo projeto, é importante que o código siga um padrão para evitar confusão.</p><ul><li><strong>Facilidade na manutenção</strong>: Um código bem estruturado e legível facilita a localização de erros e ajustes.</li><li><strong>Integração com ferramentas</strong>: Muitas ferramentas e linters já são configuradas para detectar e corrigir erros de estilo com base no PEP 8, o que torna o processo de desenvolvimento mais ágil.</li><li><strong>Consistência</strong>: Padrões claros ajudam a criar consistência entre projetos diferentes, permitindo que os desenvolvedores se adaptem rapidamente a novos projetos e equipes.</li></ul><h3>Conclusão</h3><p>O PEP 8 é um dos pilares que torna Python uma linguagem tão acessível e eficiente. Segui-lo é uma prática recomendada para programadores Python, não apenas para garantir a qualidade do código, mas também para promover boas práticas de desenvolvimento. Embora nem todas as recomendações do PEP 8 sejam absolutas, as mais importantes, como a indentação, o comprimento das linhas e a clareza nos nomes e comentários, são essenciais para um código legível e sustentável.</p><p><strong>Referências</strong>:</p><ul><li>PEP 8 — Style Guide for Python Code. Disponível em: <a href="https://pep8.org/">https://pep8.org/</a></li><li>van Rossum, G. (2001). PEP 8 — Style Guide for Python Code. Python Software Foundation. Disponível em: <a href="https://www.python.org/dev/peps/pep-0008/">https://www.python.org/dev/peps/pep-0008/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c09e621f724" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformando o CRISP-DM em um Cronograma Waterfall]]></title>
            <link>https://medium.com/@ldeassis/transformando-o-crisp-dm-em-um-cronograma-waterfall-9b240c257b4b?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b240c257b4b</guid>
            <category><![CDATA[planning]]></category>
            <category><![CDATA[crisp-dm]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 16:26:52 GMT</pubDate>
            <atom:updated>2024-12-04T16:26:52.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Depois de um ano escrevendo exclusivamente em inglês, achei necessário escrever um artigo em português brasileiro. E o escolhido foi um artigo que eu já havia preparado em inglês e estava guardado. Eu o traduzi do inglês (Língua que eu o tinha escrito) para o portugu~es brasileiro utilizando o google tradutor, não fiz revisão detalhada, apenas acreditei na tradução retornada.</p><h3>Introdução</h3><p>O <strong>CRISP-DM</strong> (Cross-Industry Standard Process for Data Mining) é uma metodologia amplamente utilizada em projetos de ciência de dados devido à sua flexibilidade e estrutura iterativa. Em sua forma original, o CRISP-DM se aproxima de métodos ágeis, pois permite revisões constantes e ajustes ao longo do projeto. Por outro lado, o modelo <strong>Waterfall</strong>, mais tradicional, estrutura as etapas de forma sequencial, com entregáveis claros ao término de cada fase.</p><p>Adotar o modelo Waterfall para projetos baseados no CRISP-DM traz consequências práticas significativas. Entre os benefícios, destaca-se a facilidade de planejamento, com prazos e custos definidos antecipadamente. Além disso, o modelo é particularmente adequado para projetos em que os requisitos estão bem estabelecidos desde o início. No entanto, essa abordagem reduz a flexibilidade para reagir a mudanças, o que pode ser prejudicial em ambientes dinâmicos, onde os dados ou as necessidades dos stakeholders podem evoluir ao longo do tempo.</p><p>Neste artigo, exploramos como o CRISP-DM pode ser adaptado ao modelo Waterfall, detalhando cada etapa, os esforços envolvidos, e as consequências positivas e negativas dessa escolha.</p><h3>Adaptação do CRISP-DM no Modelo Waterfall</h3><p>No modelo Waterfall, as etapas do CRISP-DM são realizadas em sequência, com entregáveis formais que servem como marcos do progresso do projeto. Abaixo, descrevemos como cada fase é estruturada, destacando o esforço e os entregáveis esperados:</p><h3>1. Entendimento do Negócio</h3><p>A fase inicial consiste em compreender os objetivos organizacionais e traduzir esses objetivos em metas específicas para o projeto de dados. Reuniões com stakeholders, análise de documentos e definição de métricas de sucesso são fundamentais para garantir alinhamento e clareza.</p><ul><li><strong>Entregáveis</strong>: Documento com os objetivos do projeto, métricas de sucesso e cronograma inicial.</li><li><strong>Esforço estimado</strong>: 10–15% do total.</li></ul><h3>2. Entendimento dos Dados</h3><p>Nesta etapa, os dados disponíveis são analisados para avaliar sua qualidade, relevância e alinhamento com os objetivos definidos. Inclui atividades como coleta inicial, identificação de lacunas e análise exploratória para entender limitações e potenciais.</p><ul><li><strong>Entregáveis</strong>: Relatório de qualidade e disponibilidade dos dados, com insights preliminares.</li><li><strong>Esforço estimado</strong>: 15–20% do total.</li></ul><h3>3. Preparação dos Dados</h3><p>A preparação de dados é a fase mais demorada e crítica. Aqui, os dados brutos são transformados em um formato adequado para a modelagem. Isso inclui limpeza, transformação, integração e redução dimensional, quando necessário.</p><ul><li><strong>Entregáveis</strong>: Conjunto de dados pronto para modelagem e documentação detalhada das transformações realizadas.</li><li><strong>Esforço estimado</strong>: 30–40% do total.</li></ul><h3>4. Modelagem</h3><p>Com os dados preparados, inicia-se a aplicação de algoritmos para construir modelos que atendam aos objetivos do projeto. A escolha e ajuste dos modelos são realizados com base nos dados disponíveis e nas metas previamente estabelecidas.</p><ul><li><strong>Entregáveis</strong>: Modelos treinados, avaliados e relatórios comparativos de desempenho.</li><li><strong>Esforço estimado</strong>: 15–20% do total.</li></ul><h3>5. Avaliação</h3><p>Na avaliação, verifica-se se os modelos desenvolvidos realmente atendem aos objetivos definidos. Essa fase é crucial para evitar a implementação de soluções que não agregam valor ou que falhem em entregar os resultados esperados.</p><ul><li><strong>Entregáveis</strong>: Relatório de avaliação dos modelos e aprovação final pelos stakeholders.</li><li><strong>Esforço estimado</strong>: 5–10% do total.</li></ul><h3>6. Implementação</h3><p>Por fim, os modelos aprovados são integrados aos sistemas ou processos organizacionais. Isso pode incluir a criação de dashboards, APIs ou rotinas automatizadas, além do treinamento dos usuários.</p><ul><li><strong>Entregáveis</strong>: Solução implementada, documentação técnica e treinamento da equipe.</li><li><strong>Esforço estimado</strong>: 10–15% do total.</li></ul><h3>Consequências da Escolha pelo Waterfall</h3><p><strong>Vantagens</strong></p><ol><li><strong>Planejamento Detalhado</strong>: Permite prever com maior precisão prazos, custos e recursos necessários.</li><li><strong>Clareza nos Entregáveis</strong>: Cada etapa tem objetivos e entregáveis bem definidos, facilitando a comunicação com stakeholders.</li><li><strong>Controle de Escopo</strong>: Projetos com requisitos estáveis se beneficiam da linearidade do modelo, reduzindo ambiguidades.</li></ol><p><strong>Desvantagens</strong></p><ol><li><strong>Risco de Rigidez</strong>: Alterações nos dados ou nos objetivos do negócio podem ser difíceis de acomodar em fases avançadas.</li><li><strong>Iteratividade Reduzida</strong>: Correções ou revisões dependem do término das fases, o que pode atrasar o projeto.</li><li><strong>Dependência de Dados Preliminares</strong>: Qualquer problema não identificado nas fases iniciais pode comprometer etapas posteriores.</li></ol><h3>Considerações Técnicas</h3><h3>Planejamento e Monitoramento</h3><p>A utilização do modelo Waterfall exige um planejamento robusto, com a identificação de marcos intermediários para evitar desvios significativos. O monitoramento contínuo do progresso em relação aos entregáveis é fundamental.</p><h3>Mitigação de Riscos</h3><p>Projetos que envolvem dados complexos devem incluir uma análise aprofundada na etapa de “Entendimento dos Dados” para minimizar problemas que possam impactar a “Preparação dos Dados” ou a “Modelagem”.</p><h3>Revisões Planejadas</h3><p>Embora o Waterfall não seja iterativo, é recomendável planejar revisões intermediárias ao final de fases críticas, como “Preparação dos Dados” e “Avaliação”. Essas revisões permitem ajustes sem comprometer significativamente o cronograma.</p><h3>Conclusão</h3><p>A transformação do CRISP-DM para um cronograma Waterfall é adequada para projetos com requisitos bem definidos e ambientes estáveis. Apesar das limitações em flexibilidade, essa abordagem pode garantir maior previsibilidade e controle sobre o escopo e os recursos. Projetos mais dinâmicos, no entanto, podem se beneficiar de métodos ágeis ou híbridos que combinem o melhor dos dois mundos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b240c257b4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Design Patterns in Machine Learning and Artificial Intelligence: A Practical Guide]]></title>
            <link>https://medium.com/@ldeassis/leveraging-design-patterns-in-machine-learning-and-artificial-intelligence-a-practical-guide-41ca94dbec19?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/41ca94dbec19</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 22:32:26 GMT</pubDate>
            <atom:updated>2024-08-13T22:32:26.632Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-evolving fields of Machine Learning (ML) and Artificial Intelligence (AI), the development of robust, maintainable, and scalable systems is critical. As these systems grow in complexity, developers increasingly rely on design patterns — proven solutions to common problems in software design. Design patterns provide a structured approach to building systems, enabling developers to address challenges such as data preprocessing, model training, and deployment more effectively. This article explores the role of design patterns in ML and AI, highlighting key patterns particularly useful in these domains, and provides Python code examples to demonstrate how these patterns can be applied in practice. Additionally, we will discuss the importance of ETL (Extract, Transform, Load) processes and feature engineering in preparing data for ML models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FC8rar_e9_bzI6FU" /><figcaption>Image generated by artificial Intelligence</figcaption></figure><h3>The Role of ETL and Feature Engineering in Machine Learning</h3><p>Before diving into the design patterns, it’s essential to understand the importance of ETL and feature engineering in ML. ETL is a process that involves extracting data from various sources, transforming it into a format suitable for analysis, and loading it into a data warehouse or ML model. Feature engineering, on the other hand, involves creating new features or modifying existing ones to improve the performance of ML models.</p><h4><strong>When to Perform ETL and Feature Engineering</strong></h4><ul><li><strong>Handling Diverse Data Sources:</strong> When data is collected from multiple sources with different formats and structures, an ETL process is necessary to unify the data into a consistent format suitable for analysis.</li><li><strong>Improving Model Accuracy:</strong> Feature engineering is critical when the raw data does not provide sufficient information for the model to learn effectively. By creating new features or transforming existing ones, you can enhance the model’s ability to capture patterns in the data.</li><li><strong>Dealing with Missing or Noisy Data:</strong> In cases where the dataset contains missing values or noise, ETL processes can be used to clean and preprocess the data, while feature engineering can help in constructing robust features that minimize the impact of these issues.</li><li><strong>Optimizing Performance:</strong> For large datasets, efficient ETL processes and well-engineered features can significantly reduce the complexity and computational cost of training ML models.</li></ul><h3>Design Patterns in Machine Learning and Artificial Intelligence</h3><p>As ML and AI systems become more sophisticated, the need for well-structured design patterns becomes apparent. These patterns help developers navigate the unique challenges posed by ML and AI, such as managing complex workflows, ensuring code reusability, and integrating models into production environments.</p><h4>Pipeline Pattern</h4><p>The pipeline pattern is one of the most prevalent design patterns in ML. It involves breaking down the ML process into a series of stages, each responsible for a specific task, such as data preprocessing, feature extraction, model training, and evaluation. By structuring the workflow in this way, the pipeline pattern ensures that data flows smoothly through each stage, making the overall process more manageable and efficient.</p><p><strong>Use Case: </strong>Imagine you need to preprocess data, extract features, and train a model on a dataset. The pipeline pattern allows you to encapsulate these steps in a sequence that can be reused and modified with ease.</p><p><strong>Python Example</strong>:</p><pre>from sklearn.pipeline import Pipeline<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.decomposition import PCA<br>from sklearn.ensemble import RandomForestClassifier<br><br>pipeline = Pipeline([<br>    (&#39;scaler&#39;, StandardScaler()),<br>    (&#39;pca&#39;, PCA(n_components=2)),<br>    (&#39;classifier&#39;, RandomForestClassifier())<br>])<br><br># Fit and predict<br>pipeline.fit(X_train, y_train)<br>predictions = pipeline.predict(X_test)</pre><p>This code demonstrates a pipeline where the data is first scaled, then reduced in dimensionality using PCA, and finally classified using a RandomForestClassifier.</p><h4>Model-View-Controller (MVC) Pattern</h4><p>The Model-View-Controller (MVC) pattern separates the representation of information (the model) from the user’s interaction with it (the view), with a controller managing the communication between the two. In ML, the model represents the data and algorithms used for prediction or analysis, the view handles the visualization of these predictions, and the controller facilitates interaction between the user and the system.</p><p><strong>Use Case</strong>: In a web application where users interact with an ML model to get predictions, the MVC pattern ensures that the model logic, user interface, and input control are well-separated and easy to manage.</p><p><strong>Python Example:</strong></p><pre>class Model:<br>    def predict(self, data):<br>        # Mock prediction logic<br>        return data * 2<br><br>class View:<br>    def display(self, result):<br>        print(f&quot;Prediction: {result}&quot;)<br><br>class Controller:<br>    def __init__(self, model, view):<br>        self.model = model<br>        self.view = view<br><br>    def handle_input(self, data):<br>        result = self.model.predict(data)<br>        self.view.display(result)<br><br># Usage<br>model = Model()<br>view = View()<br>controller = Controller(model, view)<br>controller.handle_input(5)</pre><p>Here, the `Model` handles the data and predictions, the `View` is responsible for displaying the result, and the `Controller` manages the interaction between the two.</p><h4>Singleton Pattern</h4><p>The singleton pattern ensures that a class has only one instance and provides a global point of access to it. This pattern is particularly useful in scenarios where resources, such as database connections or trained models, need to be shared across different parts of an application.</p><p><strong>Use Case</strong>: If you have a trained ML model that needs to be used across different parts of an application, the singleton pattern can ensure that only one instance of the model is created and used.</p><p><strong>Python Example:</strong></p><pre>class SingletonModel:<br>    _instance = None<br><br>    def __new__(cls, *args, **kwargs):<br>        if not cls._instance:<br>            cls._instance = super().__new__(cls, *args, **kwargs)<br>        return cls._instance<br><br>    def predict(self, data):<br>        # Mock prediction logic<br>        return data * 2<br><br># Usage<br>model1 = SingletonModel()<br>model2 = SingletonModel()<br><br>assert model1 is model2  # Both are the same instance<br>print(model1.predict(10))</pre><p>This example shows how the `SingletonModel` ensures that only one instance is created, even if multiple references are made to it.</p><h4>Observer Pattern</h4><p>The observer pattern allows an object (the observer) to subscribe to and receive updates from another object (the subject). In ML, this pattern can be applied to monitor the performance of models in production environments, triggering actions like retraining when specific conditions are met.</p><p><strong>Use Case:</strong> Suppose you have a model in production that needs to be retrained whenever its accuracy drops below a certain threshold. The observer pattern can be used to monitor the model and trigger retraining automatically.</p><p><strong>Python Example:</strong></p><pre>class Model:<br>    def __init__(self):<br>        self._observers = []<br><br>    def subscribe(self, observer):<br>        self._observers.append(observer)<br><br>    def notify(self, message):<br>        for observer in self._observers:<br>            observer.update(message)<br><br>    def run(self):<br>        accuracy = self._check_accuracy()<br>        if accuracy &lt; 0.8:<br>            self.notify(&quot;Accuracy dropped below 0.8, retraining needed!&quot;)<br><br>    def _check_accuracy(self):<br>        return 0.75  # Mock accuracy<br><br>class Observer:<br>    def update(self, message):<br>        print(f&quot;Observer: {message}&quot;)<br><br># Usage<br>model = Model()<br>observer = Observer()<br>model.subscribe(observer)<br>model.run()</pre><p>In this example, the `Observer` class listens for changes in the `Model` class. When the model’s accuracy drops below a threshold, the observer is notified, and necessary actions can be taken.</p><h4>Strategy Pattern</h4><p>The strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. In ML, this pattern is useful for selecting different algorithms or models at runtime, depending on the problem or data characteristics.</p><p><strong>Use Case: </strong>You might want to switch between different regression models depending on the data you are working with. The strategy pattern allows you to easily change the algorithm without modifying the overall structure.</p><p><strong>Python Example</strong>:</p><pre>class RegressionStrategy:<br>    def apply(self, data):<br>        pass<br><br>class LinearRegressionStrategy(RegressionStrategy):<br>    def apply(self, data):<br>        return sum(data) * 0.5  # Mock linear regression<br><br>class PolynomialRegressionStrategy(RegressionStrategy):<br>    def apply(self, data):<br>        return sum(data) * 1.5  # Mock polynomial regression<br><br>class Context:<br>    def __init__(self, strategy: RegressionStrategy):<br>        self._strategy = strategy<br><br>    def execute_strategy(self, data):<br>        return self._strategy.apply(data)<br><br># Usage<br>data = [1, 2, 3]<br><br>context = Context(LinearRegressionStrategy())<br>print(context.execute_strategy(data))  # Linear regression<br><br>context = Context(PolynomialRegressionStrategy())<br>print(context.execute_strategy(data))  # Polynomial regression</pre><p>This example demonstrates how the `Context` class can switch between different regression strategies without needing to change the way it interacts with the strategy.</p><h4>Factory Pattern</h4><p>The factory pattern provides an interface for creating objects without specifying the exact class of object that will be created. In ML, this pattern can be applied to instantiate different types of models or pipelines based on configuration settings or user input.</p><p><strong>Use Case</strong>: Suppose you want to create different types of classifiers based on user input, such as a decision tree or a random forest. The factory pattern allows you to encapsulate the creation logic and simplify object instantiation.</p><p><strong>Python Example</strong>:</p><pre>class ModelFactory:<br>    def create_model(self, model_type):<br>        if model_type == &quot;decision_tree&quot;:<br>            return DecisionTreeClassifier()<br>        elif model_type == &quot;random_forest&quot;:<br>            return RandomForestClassifier()<br>        else:<br>            raise ValueError(&quot;Unknown model type&quot;)<br><br># Usage<br>factory = ModelFactory()<br>model = factory.create<br><br>_model(&quot;random_forest&quot;)<br>model.fit(X_train, y_train)</pre><p>In this example, the `ModelFactory` class creates instances of different models based on the provided `model_type`, streamlining the process of model creation.</p><h4>Decorator Pattern</h4><p>The decorator pattern allows behavior to be added to an object dynamically. In the ML context, this pattern can be used to add additional functionality to models or data processing steps, such as logging, validation, or transformation, without modifying the original object.</p><p><strong>Use Case</strong>: If you need to add logging or performance monitoring to a model without altering its original code, the decorator pattern provides a flexible and non-intrusive way to do so.</p><p><strong>Python Example</strong>:</p><pre>class Model:<br>    def predict(self, data):<br>        return sum(data) * 2<br><br>class LoggingDecorator:<br>    def __init__(self, model):<br>        self._model = model<br><br>    def predict(self, data):<br>        print(f&quot;Logging: Predicting with data {data}&quot;)<br>        return self._model.predict(data)<br><br># Usage<br>model = Model()<br>decorated_model = LoggingDecorator(model)<br>print(decorated_model.predict([1, 2, 3]))</pre><p>Here, the `LoggingDecorator` adds logging functionality to the `Model` without changing its original implementation, demonstrating how behavior can be dynamically added to objects.</p><h3>Conclusion</h3><p>Design patterns are a powerful tool in the development of Machine Learning and Artificial Intelligence systems. By providing structured solutions to common design challenges, these patterns help developers create systems that are more robust, maintainable, and scalable. Additionally, the importance of ETL and feature engineering in preparing data for these systems cannot be overstated, as they play a crucial role in ensuring data quality and enhancing model performance. Whether you are dealing with data preprocessing, model management, or system architecture, design patterns offer a roadmap to building efficient and reliable ML and AI systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41ca94dbec19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Tree Algorithms: A Comprehensive Guide]]></title>
            <link>https://medium.com/@ldeassis/decision-tree-algorithms-a-comprehensive-guide-8a15a5ddc318?source=rss-f66426153337------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a15a5ddc318</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Leonard de Assis]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 18:31:02 GMT</pubDate>
            <atom:updated>2024-08-02T18:31:02.619Z</atom:updated>
            <content:encoded><![CDATA[<p>Decision trees are a fundamental tool in machine learning, widely used for both classification and regression tasks due to their simplicity and interpretability. This article covers the origins of decision tree algorithms, their core principles, and the differences in adjustment criteria for classification and regression problems. We will also compare key algorithms — CART, ID3, C4.5, and C5.0 — focusing on their resistance to overfitting, pruning methods, numerical criteria, feature selection, handling of imbalanced data, and algorithm speed. Additionally, we provide Python implementations of these algorithms, following PEP8 standards and using only the numpy library.</p><h3>Origins of Decision Trees</h3><p>Decision trees have their origins in the field of statistics. The methodology dates back to the 1960s and 1970s, with early contributions from statisticians such as Breiman, Friedman, Olshen, and Stone, who developed the Classification and Regression Trees (CART) algorithm. Ross Quinlan’s work on ID3, followed by C4.5 and later C5.0, introduced significant improvements in tree pruning, feature selection, and handling of missing values. These developments have made decision trees a versatile and powerful tool in machine learning.</p><h3>The Main Idea Behind Decision Trees</h3><p>The fundamental concept of decision tree algorithms is to recursively partition the data space into subsets, forming a tree-like structure of decisions. Each internal node represents a test on an attribute, each branch represents the outcome of the test, and each leaf node represents a class label (in classification) or a continuous value (in regression).</p><h4>Classification trees</h4><p>In classification trees, the goal is to partition the data into homogeneous subsets with respect to the target variable. The tree grows by selecting the attribute that maximizes a certain criterion, such as information gain or Gini index, at each node. <strong>This process continues until a stopping criterion is met, such as a maximum tree depth or a minimum number of samples per leaf.</strong></p><h4>Regression trees</h4><p>Regression trees, on the other hand, aim to partition the data to minimize the variance of the target variable within each subset. The splitting criterion is often based on minimizing the sum of squared errors (SSE) within the partitions. <strong>As with classification trees, the process continues until a stopping criterion is reached, ensuring the tree does not overfit the data.</strong></p><h3>Adjustment criteria</h3><h4>Spitting</h4><p>Splitting is the process of selecting an attribute and a value to divide the dataset into subsets. For classification, common criteria include information gain, Gini index, and gain ratio. For regression, criteria like variance reduction and mean squared error are used.</p><ul><li><strong>Information Gain</strong>: Measures the reduction in entropy after a dataset is split on an attribute.</li><li><strong>Gini Impurity</strong>: Measures the frequency at which any element of the dataset would be mislabeled if it was randomly labeled.</li><li><strong>Gain Ratio</strong>: An extension of Information Gain that reduces its bias towards features with many values. It is calculated as the Information Gain divided by the intrinsic information of the split.</li></ul><h4>Pruning</h4><p>Pruning is the technique of removing branches that have little importance, which helps to prevent overfitting. Pruning can be done pre-pruning (stopping the tree growth early) or post-pruning (removing branches from a fully grown tree). There are two main types of pruning:</p><ul><li><strong>Pre-pruning</strong>: Stops the tree growth early based on criteria like maximum depth or minimum number of samples required to split a node.</li><li><strong>Post-pruning</strong>: Allows the tree to grow fully and then removes nodes that do not provide substantial predictive power.</li></ul><h3>Differences in Criteria for Categorical and Continuous Variables</h3><p>When dealing with categorical variables, the splitting process involves evaluating each possible category combination. For continuous variables, the algorithm considers every possible split point to find the optimal partition. The choice of criteria and handling of variable types significantly impact the tree’s performance and interpretability.</p><h3>Key Algorithms</h3><h4>CART (Classification and Regression Trees)</h4><p>CART, developed by Breiman et al., is a binary tree that uses Gini index for classification and variance reduction for regression. It is robust to noisy data and handles both categorical and continuous variables efficiently. However, CART is prone to overfitting, which necessitates careful pruning.</p><h4>ID3 (Iterative Dichotomiser 3)</h4><p>ID3, introduced by Ross Quinlan, uses information gain as the splitting criterion. It builds trees quickly but can produce deep trees prone to overfitting. ID3 handles categorical variables well but requires modifications to deal with continuous variables.</p><h4>C4.5</h4><p>C4.5, an extension of ID3 by Quinlan, addresses many limitations of ID3. It introduces gain ratio as a splitting criterion, handles both categorical and continuous variables, and includes mechanisms for tree pruning and handling missing values. C4.5 produces more compact and accurate trees compared to ID3.</p><h4>C5.0</h4><p>C5.0, the latest iteration by Quinlan, offers several improvements over C4.5, including better handling of large datasets, faster training times, and improved accuracy. C5.0 also integrates boosting, which enhances the model’s performance by combining multiple trees to reduce variance and bias.</p><p>Boosting is an ensemble technique that improves the accuracy of decision trees by combining the predictions of several base models. In the context of C5.0, boosting helps to mitigate overfitting and enhances the model’s generalization capability.</p><h3>Details and Comparison of Decision Tree Algorithms</h3><h4>CART (Classification and Regression Trees)</h4><p>Developed by Breiman et al., CART uses Gini impurity for classification and variance reduction for regression. It supports binary splits and both classification and regression tasks. CART is straightforward and robust but can suffer from overfitting without pruning.</p><h4>ID3 (Iterative Dichotomiser 3)</h4><p>Introduced by Quinlan, ID3 uses Information Gain as the splitting criterion. It is easy to understand but prone to overfitting due to its tendency to grow very deep trees. ID3 does not handle continuous features directly and lacks built-in pruning mechanisms.</p><h4>C4.5</h4><p>A successor to ID3, C4.5 improves by handling continuous attributes, missing values, and incorporating pruning. It uses Gain Ratio instead of Information Gain to avoid bias towards features with many values, making it more robust to overfitting than ID3.</p><h4>C5.0</h4><p>An enhancement of C4.5, C5.0 offers faster execution and smaller decision trees. It introduces boosting, which improves accuracy and robustness. C5.0 handles large datasets efficiently and includes advanced pruning techniques.</p><h4>Boosting in C5.0</h4><p>Boosting converts weak learners into strong learners by sequentially applying them to reweighted versions of the data. In C5.0, boosting improves the model’s accuracy by focusing on difficult cases, making the algorithm more resistant to overfitting and better at handling imbalanced data.</p><h4>Summary of Comparison</h4><p>In summary, while CART, ID3, C4.5, and C5.0 share common principles, they differ in their splitting criteria, handling of data types, pruning methods, and resistance to overfitting.</p><ul><li><strong>Overfitting Resistance</strong>: C5.0 &gt; C4.5 &gt; CART &gt; ID3</li><li><strong>Pruning</strong>: C5.0 and C4.5 have advanced pruning techniques, whereas ID3 lacks pruning, and CART requires manual pruning.</li><li><strong>Numerical Criteria</strong>: CART uses Gini impurity, ID3 uses Information Gain, C4.5 uses Gain Ratio, and C5.0 uses an improved version of Gain Ratio.</li><li><strong>Feature Selection</strong>: All algorithms use greedy methods for feature selection at each node, but C4.5 and C5.0 handle continuous features better.</li><li><strong>Imbalanced Data</strong>: C5.0 is the most robust to imbalanced data due to its boosting mechanism.</li><li><strong>Speed</strong>: C5.0 &gt; C4.5 &gt; CART &gt; ID3</li></ul><h3>Python Implementation</h3><p>Below is the Python implementation of the CART, C4.5, and C5.0 algorithms using only the numpy library. Each algorithm is derived from a base class and includes handling for both categorical and continuous predictors.</p><h4>Classification Tree base class</h4><pre>import numpy as np<br><br>class ClassificationTree:<br>    &quot;&quot;&quot;<br>    Base class for classification trees.<br>    &quot;&quot;&quot;<br><br>    def __init__(self):<br>        self.tree = None<br><br>    def fit(self, X, y):<br>        raise NotImplementedError(&quot;This method should be overridden.&quot;)<br><br>    def predict(self, X):<br>        raise NotImplementedError(&quot;This method should be overridden.&quot;)<br><br>    def _split(self, X, y):<br>        raise NotImplementedError(&quot;This method should be overridden.&quot;)<br><br>    def _grow_tree(self, X, y):<br>        raise NotI</pre><h4>Regression Tree base class</h4><pre>import numpy as np<br><br>class RegressionTree:<br>    &quot;&quot;&quot;<br>    Base class for regression trees.<br>    &quot;&quot;&quot;<br><br>    def __init__(self):<br>        self.tree = None<br><br>    def fit(self, X, y):<br>        raise NotImplementedError(&quot;This method should be overridden.&quot;)<br><br>    def predict(self, X):<br>        raise NotImplementedError(&quot;This method should be overridden.&quot;)<br><br>    def _split(self, X, y):<br>        raise NotImplementedError(&quot;This method should be overridden.&quot;)<br><br>    def _grow_tree(self, X, y):<br>        raise NotImplementedError(&quot;This method should be overridden.&quot;)</pre><h4>ID3 for classification</h4><pre>import numpy as np<br><br>class ID3Classifier(ClassificationTree):<br>    &quot;&quot;&quot;<br>    ID3 algorithm for classification.<br>    &quot;&quot;&quot;<br><br>    def fit(self, X, y):<br>        &quot;&quot;&quot;<br>        Fit the ID3 classifier to the data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        &quot;&quot;&quot;<br>        self.tree = self._grow_tree(X, y)<br><br>    def predict(self, X):<br>        &quot;&quot;&quot;<br>        Predict the class labels for the input data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        <br>        Returns:<br>        np.ndarray<br>            Predicted class labels.<br>        &quot;&quot;&quot;<br>        return np.array([self._predict(inputs) for inputs in X])<br><br>    def _entropy(self, y):<br>        &quot;&quot;&quot;<br>        Calculate the entropy of a dataset.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        float<br>            Entropy of the dataset.<br>        &quot;&quot;&quot;<br>        hist = np.bincount(y)<br>        ps = hist / len(y)<br>        return -np.sum([p * np.log2(p) for p in ps if p &gt; 0])<br><br>    def _information_gain(self, X_column, y, split_threshold):<br>        &quot;&quot;&quot;<br>        Calculate the information gain of a potential split.<br>        <br>        Parameters:<br>        X_column : np.ndarray<br>            Feature column.<br>        y : np.ndarray<br>            Target vector.<br>        split_threshold : float<br>            Value to split the feature on.<br>        <br>        Returns:<br>        float<br>            Information gain of the split.<br>        &quot;&quot;&quot;<br>        left_indices = X_column &lt;= split_threshold<br>        right_indices = X_column &gt; split_threshold<br>        if sum(left_indices) == 0 or sum(right_indices) == 0:<br>            return 0<br><br>        n = len(y)<br>        n_left, n_right = sum(left_indices), sum(right_indices)<br>        e_left, e_right = self._entropy(y[left_indices]), self._entropy(y[right_indices])<br>        child_entropy = (n_left / n) * e_left + (n_right / n) * e_right<br>        return self._entropy(y) - child_entropy<br><br>    def _best_split(self, X, y):<br>        &quot;&quot;&quot;<br>        Find the best split for a dataset.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Best split information.<br>        &quot;&quot;&quot;<br>        best_gain = -1<br>        split = {}<br><br>        for col in range(X.shape[1]):<br>            X_column = X[:, col]<br>            thresholds = np.unique(X_column)<br>            for threshold in thresholds:<br>                gain = self._information_gain(X_column, y, threshold)<br>                if gain &gt; best_gain:<br>                    best_gain = gain<br>                    split = {<br>                        &#39;feature_index&#39;: col,<br>                        &#39;threshold&#39;: threshold,<br>                        &#39;gain&#39;: gain<br>                    }<br><br>        return split<br><br>    def _grow_tree(self, X, y):<br>        &quot;&quot;&quot;<br>        Recursively grow the decision tree.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Grown decision tree.<br>        &quot;&quot;&quot;<br>        if len(np.unique(y)) == 1:<br>            return y[0]<br><br>        if X.shape[1] == 0:<br>            return np.bincount(y).argmax()<br><br>        split = self._best_split(X, y)<br>        if split[&#39;gain&#39;] == 0:<br>            return np.bincount(y).argmax()<br><br>        left_indices = X[:, split[&#39;feature_index&#39;]] &lt;= split[&#39;threshold&#39;]<br>        right_indices = X[:, split[&#39;feature_index&#39;]] &gt; split[&#39;threshold&#39;]<br><br>        left_subtree = self._grow_tree(X[left_indices], y[left_indices])<br>        right_subtree = self._grow_tree(X[right_indices], y[right_indices])<br><br>        return {<br>            &#39;feature_index&#39;: split[&#39;feature_index&#39;],<br>            &#39;threshold&#39;: split[&#39;threshold&#39;],<br>            &#39;left&#39;: left_subtree,<br>            &#39;right&#39;: right_subtree<br>        }<br><br>    def _predict(self, inputs):<br>        &quot;&quot;&quot;<br>        Predict class for a single input.<br>        <br>        Parameters:<br>        inputs : np.ndarray<br>            Feature vector.<br>        <br>        Returns:<br>        int<br>            Predicted class label.<br>        &quot;&quot;&quot;<br>        node = self.tree<br>        while isinstance(node, dict):<br>            if inputs[node[&#39;feature_index&#39;]] &lt;= node[&#39;threshold&#39;]:<br>                node = node[&#39;left&#39;]<br>            else:<br>                node = node[&#39;right&#39;]<br>        return node<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    X = np.array([[2.771244718, 1.784783929],<br>                  [1.728571309, 1.169761413],<br>                  [3.678319846, 2.81281357],<br>                  [3.961043357, 2.61995032],<br>                  [2.999208922, 2.209014212],<br>                  [7.497545867, 3.162953546],<br>                  [9.00220326, 3.339047188],<br>                  [7.444542326, 0.476683375],<br>                  [10.12493903, 3.234550982],<br>                  [6.642287351, 3.319983761]])<br>    y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])<br><br>    classifier = ID3Classifier()<br>    classifier.fit(X, y)<br>    predictions = classifier.predict(X)<br>    print(predictions)</pre><ol><li><strong>Entropy Calculation</strong>: The _entropy method computes the entropy of a dataset, which is a measure of the uncertainty in the data.</li><li><strong>Information Gain Calculation</strong>: The _information_gain method calculates the information gain of a potential split by comparing the entropy before and after the split.</li><li><strong>Best Split Selection</strong>: The _best_split method iterates through all possible splits to find the one that yields the highest information gain.</li><li><strong>Tree Growth</strong>: The _grow_tree method recursively splits the dataset based on the best splits until all data points in a node belong to the same class or no further splits are possible.</li><li><strong>Prediction</strong>: The _predict method traverses the grown tree to predict the class label for a given input.</li></ol><p>This implementation demonstrates a basic ID3 classifier for classification tasks. It constructs a decision tree based on information gain and uses the tree to make predictions on new data.</p><h4>CART for classification</h4><pre>import numpy as np<br><br>class CARTClassifier(ClassificationTree):<br>    &quot;&quot;&quot;<br>    CART algorithm for classification.<br>    &quot;&quot;&quot;<br><br>    def fit(self, X, y):<br>        &quot;&quot;&quot;<br>        Fit the CART classifier to the data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        &quot;&quot;&quot;<br>        self.tree = self._grow_tree(X, y)<br><br>    def predict(self, X):<br>        &quot;&quot;&quot;<br>        Predict the class labels for the input data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        <br>        Returns:<br>        np.ndarray<br>            Predicted class labels.<br>        &quot;&quot;&quot;<br>        return np.array([self._predict(inputs) for inputs in X])<br><br>    def _gini(self, y):<br>        &quot;&quot;&quot;<br>        Calculate the Gini impurity of a dataset.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        float<br>            Gini impurity of the dataset.<br>        &quot;&quot;&quot;<br>        hist = np.bincount(y)<br>        ps = hist / len(y)<br>        return 1 - np.sum([p ** 2 for p in ps if p &gt; 0])<br><br>    def _information_gain(self, y, left_y, right_y):<br>        &quot;&quot;&quot;<br>        Calculate the information gain of a potential split.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        left_y : np.ndarray<br>            Left split target vector.<br>        right_y : np.ndarray<br>            Right split target vector.<br>        <br>        Returns:<br>        float<br>            Information gain of the split.<br>        &quot;&quot;&quot;<br>        p = len(left_y) / len(y)<br>        return self._gini(y) - p * self._gini(left_y) - (1 - p) * self._gini(right_y)<br><br>    def _best_split(self, X, y):<br>        &quot;&quot;&quot;<br>        Find the best split for a dataset.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Best split information.<br>        &quot;&quot;&quot;<br>        best_gain = -1<br>        split = {}<br><br>        for col in range(X.shape[1]):<br>            X_column = X[:, col]<br>            thresholds = np.unique(X_column)<br>            for threshold in thresholds:<br>                left_indices = X_column &lt;= threshold<br>                right_indices = X_column &gt; threshold<br>                if sum(left_indices) == 0 or sum(right_indices) == 0:<br>                    continue<br>                gain = self._information_gain(y, y[left_indices], y[right_indices])<br>                if gain &gt; best_gain:<br>                    best_gain = gain<br>                    split = {<br>                        &#39;feature_index&#39;: col,<br>                        &#39;threshold&#39;: threshold,<br>                        &#39;gain&#39;: gain<br>                    }<br><br>        return split<br><br>    def _grow_tree(self, X, y):<br>        &quot;&quot;&quot;<br>        Recursively grow the decision tree.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Grown decision tree.<br>        &quot;&quot;&quot;<br>        if len(np.unique(y)) == 1:<br>            return y[0]<br><br>        if X.shape[1] == 0:<br>            return np.bincount(y).argmax()<br><br>        split = self._best_split(X, y)<br>        if split[&#39;gain&#39;] == 0:<br>            return np.bincount(y).argmax()<br><br>        left_indices = X[:, split[&#39;feature_index&#39;]] &lt;= split[&#39;threshold&#39;]<br>        right_indices = X[:, split[&#39;feature_index&#39;]] &gt; split[&#39;threshold&#39;]<br><br>        left_subtree = self._grow_tree(X[left_indices], y[left_indices])<br>        right_subtree = self._grow_tree(X[right_indices], y[right_indices])<br><br>        return {<br>            &#39;feature_index&#39;: split[&#39;feature_index&#39;],<br>            &#39;threshold&#39;: split[&#39;threshold&#39;],<br>            &#39;left&#39;: left_subtree,<br>            &#39;right&#39;: right_subtree<br>        }<br><br>    def _predict(self, inputs):<br>        &quot;&quot;&quot;<br>        Predict class for a single input.<br>        <br>        Parameters:<br>        inputs : np.ndarray<br>            Feature vector.<br>        <br>        Returns:<br>        int<br>            Predicted class label.<br>        &quot;&quot;&quot;<br>        node = self.tree<br>        while isinstance(node, dict):<br>            if inputs[node[&#39;feature_index&#39;]] &lt;= node[&#39;threshold&#39;]:<br>                node = node[&#39;left&#39;]<br>            else:<br>                node = node[&#39;right&#39;]<br>        return node<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    X = np.array([[2.771244718, 1.784783929],<br>                  [1.728571309, 1.169761413],<br>                  [3.678319846, 2.81281357],<br>                  [3.961043357, 2.61995032],<br>                  [2.999208922, 2.209014212],<br>                  [7.497545867, 3.162953546],<br>                  [9.00220326, 3.339047188],<br>                  [7.444542326, 0.476683375],<br>                  [10.12493903, 3.234550982],<br>                  [6.642287351, 3.319983761]])<br>    y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])<br><br>    classifier = CARTClassifier()<br>    classifier.fit(X, y)<br>    predictions = classifier.predict(X)<br>    print(predictions)</pre><ol><li><strong>Gini Impurity Calculation</strong>: The _gini method calculates the Gini impurity, which measures the likelihood of incorrect classification of a randomly chosen element.</li><li><strong>Information Gain Calculation</strong>: The _information_gain method calculates the information gain of a potential split based on the reduction in Gini impurity.</li><li><strong>Best Split Selection</strong>: The _best_split method iterates through all possible splits to find the one that yields the highest information gain based on Gini impurity.</li><li><strong>Tree Growth</strong>: The _grow_tree method recursively splits the dataset based on the best splits until all data points in a node belong to the same class or no further splits are possible.</li><li><strong>Prediction</strong>: The _predict method traverses the grown tree to predict the class label for a given input.</li></ol><p>This implementation demonstrates a basic CART classifier for classification tasks. It constructs a decision tree based on Gini impurity and uses the tree to make predictions on new data.</p><h4>C4.5 for classification</h4><pre>import numpy as np<br><br>class C45Classifier(ClassificationTree):<br>    &quot;&quot;&quot;<br>    C4.5 algorithm for classification.<br>    &quot;&quot;&quot;<br><br>    def fit(self, X, y):<br>        &quot;&quot;&quot;<br>        Fit the C4.5 classifier to the data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        &quot;&quot;&quot;<br>        self.tree = self._grow_tree(X, y)<br><br>    def predict(self, X):<br>        &quot;&quot;&quot;<br>        Predict the class labels for the input data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        <br>        Returns:<br>        np.ndarray<br>            Predicted class labels.<br>        &quot;&quot;&quot;<br>        return np.array([self._predict(inputs) for inputs in X])<br><br>    def _entropy(self, y):<br>        &quot;&quot;&quot;<br>        Calculate the entropy of a dataset.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        float<br>            Entropy of the dataset.<br>        &quot;&quot;&quot;<br>        hist = np.bincount(y)<br>        ps = hist / len(y)<br>        return -np.sum([p * np.log2(p) for p in ps if p &gt; 0])<br><br>    def _information_gain(self, y, left_y, right_y):<br>        &quot;&quot;&quot;<br>        Calculate the information gain of a potential split.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        left_y : np.ndarray<br>            Left split target vector.<br>        right_y : np.ndarray<br>            Right split target vector.<br>        <br>        Returns:<br>        float<br>            Information gain of the split.<br>        &quot;&quot;&quot;<br>        p = len(left_y) / len(y)<br>        return self._entropy(y) - p * self._entropy(left_y) - (1 - p) * self._entropy(right_y)<br><br>    def _gain_ratio(self, y, left_y, right_y):<br>        &quot;&quot;&quot;<br>        Calculate the gain ratio of a potential split.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        left_y : np.ndarray<br>            Left split target vector.<br>        right_y : np.ndarray<br>            Right split target vector.<br>        <br>        Returns:<br>        float<br>            Gain ratio of the split.<br>        &quot;&quot;&quot;<br>        gain = self._information_gain(y, left_y, right_y)<br>        split_info = - (len(left_y) / len(y)) * np.log2(len(left_y) / len(y)) - (len(right_y) / len(y)) * np.log2(len(right_y) / len(y))<br>        if split_info == 0:<br>            return 0<br>        return gain / split_info<br><br>    def _best_split(self, X, y):<br>        &quot;&quot;&quot;<br>        Find the best split for a dataset.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Best split information.<br>        &quot;&quot;&quot;<br>        best_gain_ratio = -1<br>        split = {}<br><br>        for col in range(X.shape[1]):<br>            X_column = X[:, col]<br>            thresholds = np.unique(X_column)<br>            for threshold in thresholds:<br>                left_indices = X_column &lt;= threshold<br>                right_indices = X_column &gt; threshold<br>                if sum(left_indices) == 0 or sum(right_indices) == 0:<br>                    continue<br>                gain_ratio = self._gain_ratio(y, y[left_indices], y[right_indices])<br>                if gain_ratio &gt; best_gain_ratio:<br>                    best_gain_ratio = gain_ratio<br>                    split = {<br>                        &#39;feature_index&#39;: col,<br>                        &#39;threshold&#39;: threshold,<br>                        &#39;gain_ratio&#39;: gain_ratio<br>                    }<br><br>        return split<br><br>    def _grow_tree(self, X, y):<br>        &quot;&quot;&quot;<br>        Recursively grow the decision tree.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Grown decision tree.<br>        &quot;&quot;&quot;<br>        if len(np.unique(y)) == 1:<br>            return y[0]<br><br>        if X.shape[1] == 0:<br>            return np.bincount(y).argmax()<br><br>        split = self._best_split(X, y)<br>        if split[&#39;gain_ratio&#39;] == 0:<br>            return np.bincount(y).argmax()<br><br>        left_indices = X[:, split[&#39;feature_index&#39;]] &lt;= split[&#39;threshold&#39;]<br>        right_indices = X[:, split[&#39;feature_index&#39;]] &gt; split[&#39;threshold&#39;]<br><br>        left_subtree = self._grow_tree(X[left_indices], y[left_indices])<br>        right_subtree = self._grow_tree(X[right_indices], y[right_indices])<br><br>        return {<br>            &#39;feature_index&#39;: split[&#39;feature_index&#39;],<br>            &#39;threshold&#39;: split[&#39;threshold&#39;],<br>            &#39;left&#39;: left_subtree,<br>            &#39;right&#39;: right_subtree<br>        }<br><br>    def _predict(self, inputs):<br>        &quot;&quot;&quot;<br>        Predict class for a single input.<br>        <br>        Parameters:<br>        inputs : np.ndarray<br>            Feature vector.<br>        <br>        Returns:<br>        int<br>            Predicted class label.<br>        &quot;&quot;&quot;<br>        node = self.tree<br>        while isinstance(node, dict):<br>            if inputs[node[&#39;feature_index&#39;]] &lt;= node[&#39;threshold&#39;]:<br>                node = node[&#39;left&#39;]<br>            else:<br>                node = node[&#39;right&#39;]<br>        return node<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    X = np.array([[2.771244718, 1.784783929],<br>                  [1.728571309, 1.169761413],<br>                  [3.678319846, 2.81281357],<br>                  [3.961043357, 2.61995032],<br>                  [2.999208922, 2.209014212],<br>                  [7.497545867, 3.162953546],<br>                  [9.00220326, 3.339047188],<br>                  [7.444542326, 0.476683375],<br>                  [10.12493903, 3.234550982],<br>                  [6.642287351, 3.319983761]])<br>    y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])<br><br>    classifier = C45Classifier()<br>    classifier.fit(X, y)<br>    predictions = classifier.predict(X)<br>    print(predictions)</pre><ol><li><strong>Entropy Calculation</strong>: The _entropy method computes the entropy of a dataset, which measures the uncertainty in the data.</li><li><strong>Information Gain Calculation</strong>: The _information_gain method calculates the information gain of a potential split by comparing the entropy before and after the split.</li><li><strong>Gain Ratio Calculation</strong>: The _gain_ratio method computes the gain ratio, which adjusts the information gain by the intrinsic information of a split.</li><li><strong>Best Split Selection</strong>: The _best_split method iterates through all possible splits to find the one that yields the highest gain ratio.</li><li><strong>Tree Growth</strong>: The _grow_tree method recursively splits the dataset based on the best splits until all data points in a node belong to the same class or no further splits are possible.</li><li><strong>Prediction</strong>: The _predict method traverses the grown tree to predict the class label for a given input.</li></ol><p>This implementation demonstrates a basic C4.5 classifier for classification tasks. It constructs a decision tree based on gain ratio and uses the tree to make predictions on new data.</p><h4>C5.0 for classification</h4><pre>import numpy as np<br><br>class C50Classifier(ClassificationTree):<br>    &quot;&quot;&quot;<br>    C5.0 algorithm for classification without boosting.<br>    &quot;&quot;&quot;<br><br>    def fit(self, X, y):<br>        &quot;&quot;&quot;<br>        Fit the C5.0 classifier to the data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        &quot;&quot;&quot;<br>        self.tree = self._grow_tree(X, y)<br><br>    def predict(self, X):<br>        &quot;&quot;&quot;<br>        Predict the class labels for the input data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        <br>        Returns:<br>        np.ndarray<br>            Predicted class labels.<br>        &quot;&quot;&quot;<br>        return np.array([self._predict(inputs) for inputs in X])<br><br>    def _entropy(self, y):<br>        &quot;&quot;&quot;<br>        Calculate the entropy of a dataset.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        float<br>            Entropy of the dataset.<br>        &quot;&quot;&quot;<br>        hist = np.bincount(y)<br>        ps = hist / len(y)<br>        return -np.sum([p * np.log2(p) for p in ps if p &gt; 0])<br><br>    def _information_gain(self, y, left_y, right_y):<br>        &quot;&quot;&quot;<br>        Calculate the information gain of a potential split.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        left_y : np.ndarray<br>            Left split target vector.<br>        right_y : np.ndarray<br>            Right split target vector.<br>        <br>        Returns:<br>        float<br>            Information gain of the split.<br>        &quot;&quot;&quot;<br>        p = len(left_y) / len(y)<br>        return self._entropy(y) - p * self._entropy(left_y) - (1 - p) * self._entropy(right_y)<br><br>    def _gain_ratio(self, y, left_y, right_y):<br>        &quot;&quot;&quot;<br>        Calculate the gain ratio of a potential split.<br>        <br>        Parameters:<br>        y : np.ndarray<br>            Target vector.<br>        left_y : np.ndarray<br>            Left split target vector.<br>        right_y : np.ndarray<br>            Right split target vector.<br>        <br>        Returns:<br>        float<br>            Gain ratio of the split.<br>        &quot;&quot;&quot;<br>        gain = self._information_gain(y, left_y, right_y)<br>        split_info = - (len(left_y) / len(y)) * np.log2(len(left_y) / len(y)) - (len(right_y) / len(y)) * np.log2(len(right_y) / len(y))<br>        if split_info == 0:<br>            return 0<br>        return gain / split_info<br><br>    def _best_split(self, X, y):<br>        &quot;&quot;&quot;<br>        Find the best split for a dataset.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Best split information.<br>        &quot;&quot;&quot;<br>        best_gain_ratio = -1<br>        split = {}<br><br>        for col in range(X.shape[1]):<br>            X_column = X[:, col]<br>            thresholds = np.unique(X_column)<br>            for threshold in thresholds:<br>                left_indices = X_column &lt;= threshold<br>                right_indices = X_column &gt; threshold<br>                if sum(left_indices) == 0 or sum(right_indices) == 0:<br>                    continue<br>                gain_ratio = self._gain_ratio(y, y[left_indices], y[right_indices])<br>                if gain_ratio &gt; best_gain_ratio:<br>                    best_gain_ratio = gain_ratio<br>                    split = {<br>                        &#39;feature_index&#39;: col,<br>                        &#39;threshold&#39;: threshold,<br>                        &#39;gain_ratio&#39;: gain_ratio<br>                    }<br><br>        return split<br><br>    def _grow_tree(self, X, y):<br>        &quot;&quot;&quot;<br>        Recursively grow the decision tree.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Grown decision tree.<br>        &quot;&quot;&quot;<br>        if len(np.unique(y)) == 1:<br>            return y[0]<br><br>        if X.shape[1] == 0:<br>            return np.bincount(y).argmax()<br><br>        split = self._best_split(X, y)<br>        if split[&#39;gain_ratio&#39;] == 0:<br>            return np.bincount(y).argmax()<br><br>        left_indices = X[:, split[&#39;feature_index&#39;]] &lt;= split[&#39;threshold&#39;]<br>        right_indices = X[:, split[&#39;feature_index&#39;]] &gt; split[&#39;threshold&#39;]<br><br>        left_subtree = self._grow_tree(X[left_indices], y[left_indices])<br>        right_subtree = self._grow_tree(X[right_indices], y[right_indices])<br><br>        return {<br>            &#39;feature_index&#39;: split[&#39;feature_index&#39;],<br>            &#39;threshold&#39;: split[&#39;threshold&#39;],<br>            &#39;left&#39;: left_subtree,<br>            &#39;right&#39;: right_subtree<br>        }<br><br>    def _predict(self, inputs):<br>        &quot;&quot;&quot;<br>        Predict class for a single input.<br>        <br>        Parameters:<br>        inputs : np.ndarray<br>            Feature vector.<br>        <br>        Returns:<br>        int<br>            Predicted class label.<br>        &quot;&quot;&quot;<br>        node = self.tree<br>        while isinstance(node, dict):<br>            if inputs[node[&#39;feature_index&#39;]] &lt;= node[&#39;threshold&#39;]:<br>                node = node[&#39;left&#39;]<br>            else:<br>                node = node[&#39;right&#39;]<br>        return node<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    X = np.array([[2.771244718, 1.784783929],<br>                  [1.728571309, 1.169761413],<br>                  [3.678319846, 2.81281357],<br>                  [3.961043357, 2.61995032],<br>                  [2.999208922, 2.209014212],<br>                  [7.497545867, 3.162953546],<br>                  [9.00220326, 3.339047188],<br>                  [7.444542326, 0.476683375],<br>                  [10.12493903, 3.234550982],<br>                  [6.642287351, 3.319983761]])<br>    y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])<br><br>    classifier = C50Classifier()<br>    classifier.fit(X, y)<br>    predictions = classifier.predict(X)<br>    print(predictions)</pre><h4>C5.0Classifier Without Boosting</h4><ul><li><strong>Entropy Calculation</strong>: The _entropy method calculates the entropy of a dataset.</li><li><strong>Information Gain Calculation</strong>: The _information_gain method measures the reduction in entropy due to a split.</li><li><strong>Gain Ratio Calculation</strong>: The _gain_ratio method adjusts information gain by the split&#39;s intrinsic information.</li><li><strong>Best Split Selection</strong>: The _best_split method identifies the optimal split based on gain ratio.</li><li><strong>Tree Growth</strong>: The _grow_tree method recursively builds the tree using the best splits.</li><li><strong>Prediction</strong>: The _predict method traverses the tree to classify inputs.</li></ul><pre>import numpy as np<br>from sklearn.utils import resample<br><br>class C50ClassifierWithBoosting(ClassificationTree):<br>    &quot;&quot;&quot;<br>    C5.0 algorithm for classification with boosting.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, n_estimators=10):<br>        &quot;&quot;&quot;<br>        Initialize the C5.0 classifier with boosting.<br>        <br>        Parameters:<br>        n_estimators : int<br>            Number of boosting rounds.<br>        &quot;&quot;&quot;<br>        self.n_estimators = n_estimators<br>        self.trees = []<br><br>    def fit(self, X, y):<br>        &quot;&quot;&quot;<br>        Fit the C5.0 classifier to the data with boosting.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        &quot;&quot;&quot;<br>        for _ in range(self.n_estimators):<br>            # Bootstrap sampling<br>            X_resampled, y_resampled = resample(X, y, replace=True)<br>            tree = C50Classifier()<br>            tree.fit(X_resampled, y_resampled)<br>            self.trees.append(tree)<br><br>    def predict(self, X):<br>        &quot;&quot;&quot;<br>        Predict the class labels for the input data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        <br>        Returns:<br>        np.ndarray<br>            Predicted class labels.<br>        &quot;&quot;&quot;<br>        predictions = np.array([self._predict(x) for x in X])<br>        return np.array([np.bincount(p).argmax() for p in predictions])<br><br>    def _predict(self, inputs):<br>        &quot;&quot;&quot;<br>        Predict class for a single input using majority voting from all trees.<br>        <br>        Parameters:<br>        inputs : np.ndarray<br>            Feature vector.<br>        <br>        Returns:<br>        int<br>            Predicted class label.<br>        &quot;&quot;&quot;<br>        votes = [tree._predict(inputs) for tree in self.trees]<br>        return np.bincount(votes).argmax()<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    X = np.array([[2.771244718, 1.784783929],<br>                  [1.728571309, 1.169761413],<br>                  [3.678319846, 2.81281357],<br>                  [3.961043357, 2.61995032],<br>                  [2.999208922, 2.209014212],<br>                  [7.497545867, 3.162953546],<br>                  [9.00220326, 3.339047188],<br>                  [7.444542326, 0.476683375],<br>                  [10.12493903, 3.234550982],<br>                  [6.642287351, 3.319983761]])<br>    y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])<br><br>    classifier = C50ClassifierWithBoosting(n_estimators=10)<br>    classifier.fit(X, y)<br>    predictions = classifier.predict(X)<br>    print(predictions)</pre><h4>C5.0Classifier With Boosting</h4><ul><li><strong>Boosting Initialization</strong>: __init__ initializes the classifier with a specified number of boosting rounds.</li><li><strong>Fitting with Boosting</strong>: The fit method performs bootstrapped sampling and fits a series of C5.0 classifiers.</li><li><strong>Prediction with Boosting</strong>: The predict method aggregates predictions from all trees using majority voting.</li><li><strong>Single Input Prediction</strong>: The _predict method returns the most frequent class label from all trees for a given input.</li></ul><p>Each implementation demonstrates a specific approach to decision tree classification, with the boosting version using ensemble techniques to potentially enhance performance.</p><h4>CART for Regression</h4><pre>import numpy as np<br><br>class CARTRegressor(RegressorTree):<br>    &quot;&quot;&quot;<br>    CART algorithm for regression.<br>    &quot;&quot;&quot;<br><br>    def fit(self, X, y):<br>        &quot;&quot;&quot;<br>        Fit the CART regressor to the data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        &quot;&quot;&quot;<br>        self.tree = self._grow_tree(X, y)<br><br>    def predict(self, X):<br>        &quot;&quot;&quot;<br>        Predict the target values for the input data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        <br>        Returns:<br>        np.ndarray<br>            Predicted target values.<br>        &quot;&quot;&quot;<br>        return np.array([self._predict(inputs) for inputs in X])<br><br>    def _mean_squared_error(self, y_true, y_pred):<br>        &quot;&quot;&quot;<br>        Calculate the mean squared error between true and predicted values.<br>        <br>        Parameters:<br>        y_true : np.ndarray<br>            True target values.<br>        y_pred : np.ndarray<br>            Predicted target values.<br>        <br>        Returns:<br>        float<br>            Mean squared error.<br>        &quot;&quot;&quot;<br>        return np.mean((y_true - y_pred) ** 2)<br><br>    def _best_split(self, X, y):<br>        &quot;&quot;&quot;<br>        Find the best split for a dataset.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Best split information.<br>        &quot;&quot;&quot;<br>        best_mse = float(&#39;inf&#39;)<br>        split = {}<br><br>        for col in range(X.shape[1]):<br>            X_column = X[:, col]<br>            thresholds = np.unique(X_column)<br>            for threshold in thresholds:<br>                left_indices = X_column &lt;= threshold<br>                right_indices = X_column &gt; threshold<br>                if sum(left_indices) == 0 or sum(right_indices) == 0:<br>                    continue<br><br>                left_y, right_y = y[left_indices], y[right_indices]<br>                left_mean = np.mean(left_y)<br>                right_mean = np.mean(right_y)<br>                mse = (len(left_y) * self._mean_squared_error(left_y, left_mean) +<br>                       len(right_y) * self._mean_squared_error(right_y, right_mean)) / len(y)<br><br>                if mse &lt; best_mse:<br>                    best_mse = mse<br>                    split = {<br>                        &#39;feature_index&#39;: col,<br>                        &#39;threshold&#39;: threshold,<br>                        &#39;mse&#39;: mse<br>                    }<br><br>        return split<br><br>    def _grow_tree(self, X, y):<br>        &quot;&quot;&quot;<br>        Recursively grow the decision tree.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Grown decision tree.<br>        &quot;&quot;&quot;<br>        if len(np.unique(y)) == 1:<br>            return y[0]<br><br>        if X.shape[1] == 0:<br>            return np.mean(y)<br><br>        split = self._best_split(X, y)<br>        if split[&#39;mse&#39;] == float(&#39;inf&#39;):<br>            return np.mean(y)<br><br>        left_indices = X[:, split[&#39;feature_index&#39;]] &lt;= split[&#39;threshold&#39;]<br>        right_indices = X[:, split[&#39;feature_index&#39;]] &gt; split[&#39;threshold&#39;]<br><br>        left_subtree = self._grow_tree(X[left_indices], y[left_indices])<br>        right_subtree = self._grow_tree(X[right_indices], y[right_indices])<br><br>        return {<br>            &#39;feature_index&#39;: split[&#39;feature_index&#39;],<br>            &#39;threshold&#39;: split[&#39;threshold&#39;],<br>            &#39;left&#39;: left_subtree,<br>            &#39;right&#39;: right_subtree<br>        }<br><br>    def _predict(self, inputs):<br>        &quot;&quot;&quot;<br>        Predict target value for a single input.<br>        <br>        Parameters:<br>        inputs : np.ndarray<br>            Feature vector.<br>        <br>        Returns:<br>        float<br>            Predicted target value.<br>        &quot;&quot;&quot;<br>        node = self.tree<br>        while isinstance(node, dict):<br>            if inputs[node[&#39;feature_index&#39;]] &lt;= node[&#39;threshold&#39;]:<br>                node = node[&#39;left&#39;]<br>            else:<br>                node = node[&#39;right&#39;]<br>        return node<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    X = np.array([[2.771244718, 1.784783929],<br>                  [1.728571309, 1.169761413],<br>                  [3.678319846, 2.81281357],<br>                  [3.961043357, 2.61995032],<br>                  [2.999208922, 2.209014212],<br>                  [7.497545867, 3.162953546],<br>                  [9.00220326, 3.339047188],<br>                  [7.444542326, 0.476683375],<br>                  [10.12493903, 3.234550982],<br>                  [6.642287351, 3.319983761]])<br>    y = np.array([0.1, 0.2, 0.4, 0.3, 0.5, 1.2, 1.4, 1.1, 1.5, 1.3])<br><br>    regressor = CARTRegressor()<br>    regressor.fit(X, y)<br>    predictions = regressor.predict(X)<br>    print(predictions)</pre><ol><li><strong>Mean Squared Error Calculation</strong>: The _mean_squared_error method calculates the mean squared error between true and predicted values, which is used to evaluate the quality of splits.</li><li><strong>Best Split Selection</strong>: The _best_split method finds the optimal split for the dataset by evaluating the mean squared error for potential splits and selecting the one that minimizes this error.</li><li><strong>Tree Growth</strong>: The _grow_tree method recursively builds the regression tree, splitting the data based on the best splits until all data points in a node have the same value or no further splits improve the model.</li><li><strong>Prediction</strong>: The _predict method traverses the regression tree to predict the target value for a given input.</li></ol><p>This implementation provides a basic CART regressor that builds a decision tree to predict continuous target values based on the mean squared error criterion.</p><p>There are several ways to optimize CARTRegressor to improve performance and efficiency.<br>We can instead of considering all features for each split, randomly sample a subset of features. This can reduce computational cost and improve performance, especially on resource-intensive datasets.<br>Another option that improves efficiency would be after the tree is built, perform complexity pruning, which removes branches from the tree that have little contribution to the model’s accuracy. This can reduce overfitting and improve generalization.</p><pre>import numpy as np<br>from sklearn.utils import resample<br><br>class CARTRegressor(RegressorTree):<br>    &quot;&quot;&quot;<br>    Optimized CART algorithm for regression with complexity pruning.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, max_depth=None, min_samples_split=2):<br>        &quot;&quot;&quot;<br>        Initialize the CART regressor.<br>        <br>        Parameters:<br>        max_depth : int or None<br>            Maximum depth of the tree.<br>        min_samples_split : int<br>            Minimum number of samples required to split an internal node.<br>        &quot;&quot;&quot;<br>        self.max_depth = max_depth<br>        self.min_samples_split = min_samples_split<br>        self.tree = None<br><br>    def fit(self, X, y):<br>        &quot;&quot;&quot;<br>        Fit the CART regressor to the data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        &quot;&quot;&quot;<br>        self.tree = self._grow_tree(X, y, depth=0)<br><br>    def predict(self, X):<br>        &quot;&quot;&quot;<br>        Predict the target values for the input data.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        <br>        Returns:<br>        np.ndarray<br>            Predicted target values.<br>        &quot;&quot;&quot;<br>        return np.array([self._predict(inputs) for inputs in X])<br><br>    def _mean_squared_error(self, y_true, y_pred):<br>        &quot;&quot;&quot;<br>        Calculate the mean squared error between true and predicted values.<br>        <br>        Parameters:<br>        y_true : np.ndarray<br>            True target values.<br>        y_pred : np.ndarray<br>            Predicted target values.<br>        <br>        Returns:<br>        float<br>            Mean squared error.<br>        &quot;&quot;&quot;<br>        return np.mean((y_true - y_pred) ** 2)<br><br>    def _best_split(self, X, y):<br>        &quot;&quot;&quot;<br>        Find the best split for a dataset.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        <br>        Returns:<br>        dict<br>            Best split information.<br>        &quot;&quot;&quot;<br>        best_mse = float(&#39;inf&#39;)<br>        split = {}<br><br>        num_features = X.shape[1]<br>        for col in range(num_features):<br>            X_column = X[:, col]<br>            thresholds = np.unique(X_column)<br>            for threshold in thresholds:<br>                left_indices = X_column &lt;= threshold<br>                right_indices = X_column &gt; threshold<br>                if sum(left_indices) &lt; self.min_samples_split or sum(right_indices) &lt; self.min_samples_split:<br>                    continue<br><br>                left_y, right_y = y[left_indices], y[right_indices]<br>                left_mean = np.mean(left_y)<br>                right_mean = np.mean(right_y)<br>                mse = (len(left_y) * self._mean_squared_error(left_y, left_mean) +<br>                       len(right_y) * self._mean_squared_error(right_y, right_mean)) / len(y)<br><br>                if mse &lt; best_mse:<br>                    best_mse = mse<br>                    split = {<br>                        &#39;feature_index&#39;: col,<br>                        &#39;threshold&#39;: threshold,<br>                        &#39;mse&#39;: mse<br>                    }<br><br>        return split<br><br>    def _grow_tree(self, X, y, depth):<br>        &quot;&quot;&quot;<br>        Recursively grow the decision tree with pruning.<br>        <br>        Parameters:<br>        X : np.ndarray<br>            Feature matrix.<br>        y : np.ndarray<br>            Target vector.<br>        depth : int<br>            Current depth of the tree.<br>        <br>        Returns:<br>        dict or float<br>            Grown decision tree or target value.<br>        &quot;&quot;&quot;<br>        if len(np.unique(y)) == 1:<br>            return y[0]<br><br>        if self.max_depth is not None and depth &gt;= self.max_depth:<br>            return np.mean(y)<br><br>        if X.shape[1] == 0 or len(y) &lt; self.min_samples_split:<br>            return np.mean(y)<br><br>        split = self._best_split(X, y)<br>        if split[&#39;mse&#39;] == float(&#39;inf&#39;):<br>            return np.mean(y)<br><br>        left_indices = X[:, split[&#39;feature_index&#39;]] &lt;= split[&#39;threshold&#39;]<br>        right_indices = X[:, split[&#39;feature_index&#39;]] &gt; split[&#39;threshold&#39;]<br><br>        left_subtree = self._grow_tree(X[left_indices], y[left_indices], depth + 1)<br>        right_subtree = self._grow_tree(X[right_indices], y[right_indices], depth + 1)<br><br>        return {<br>            &#39;feature_index&#39;: split[&#39;feature_index&#39;],<br>            &#39;threshold&#39;: split[&#39;threshold&#39;],<br>            &#39;left&#39;: left_subtree,<br>            &#39;right&#39;: right_subtree<br>        }<br><br>    def _predict(self, inputs):<br>        &quot;&quot;&quot;<br>        Predict target value for a single input.<br>        <br>        Parameters:<br>        inputs : np.ndarray<br>            Feature vector.<br>        <br>        Returns:<br>        float<br>            Predicted target value.<br>        &quot;&quot;&quot;<br>        node = self.tree<br>        while isinstance(node, dict):<br>            if inputs[node[&#39;feature_index&#39;]] &lt;= node[&#39;threshold&#39;]:<br>                node = node[&#39;left&#39;]<br>            else:<br>                node = node[&#39;right&#39;]<br>        return node<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    X = np.array([[2.771244718, 1.784783929],<br>                  [1.728571309, 1.169761413],<br>                  [3.678319846, 2.81281357],<br>                  [3.961043357, 2.61995032],<br>                  [2.999208922, 2.209014212],<br>                  [7.497545867, 3.162953546],<br>                  [9.00220326, 3.339047188],<br>                  [7.444542326, 0.476683375],<br>                  [10.12493903, 3.234550982],<br>                  [6.642287351, 3.319983761]])<br>    y = np.array([0.1, 0.2, 0.4, 0.3, 0.5, 1.2, 1.4, 1.1, 1.5, 1.3])<br><br>    regressor = CARTRegressor(max_depth=5, min_samples_split=2)<br>    regressor.fit(X, y)<br>    predictions = regressor.predict(X)<br>    print(predictions)</pre><ol><li><strong>Maximum Depth (</strong><strong>max_depth)</strong>: Limits the depth of the tree to prevent it from growing too complex. This helps in reducing overfitting and improves generalization.</li><li><strong>Minimum Samples Split (</strong><strong>min_samples_split)</strong>: Ensures that a node must have at least a certain number of samples before it can be split. This prevents the model from creating overly specific branches that may not generalize well.</li><li><strong>Efficient Split Evaluation</strong>: The _best_split method is optimized to handle only feasible splits by checking the minimum number of samples required for a split.</li></ol><p>These optimizations can help make the CART regressor more efficient and robust, especially when working with large datasets.</p><h3>References</h3><ol><li>Breiman, L., Friedman, J. H., Olshen, R. A., &amp; Stone, C. J. (1984). Classification and Regression Trees. Wadsworth International Group.</li><li>Quinlan, J. R. (1986). Induction of decision trees. Machine Learning, 1(1), 81–106.</li><li>Quinlan, J. R. (1993). C4.5: Programs for Machine Learning. Morgan Kaufmann.</li><li>Quinlan, J. R. (1998). Data Mining Tools See5 and C5.0. Retrieved from <a href="http://www.rulequest.com/see5-info.html">http://www.rulequest.com/see5-info.html</a></li></ol><p>This article provides a comprehensive overview of decision tree algorithms, including their origins, core concepts, and practical implementation. The Python code demonstrates how to build and use these algorithms, showcasing their unique features and improvements over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a15a5ddc318" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>