<?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 Abdullah Younis on Medium]]></title>
        <description><![CDATA[Stories by Abdullah Younis on Medium]]></description>
        <link>https://medium.com/@abdullah.hosam13?source=rss-e9311f2995fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JHnfhJHrMaEz1Vlz</url>
            <title>Stories by Abdullah Younis on Medium</title>
            <link>https://medium.com/@abdullah.hosam13?source=rss-e9311f2995fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:22:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdullah.hosam13/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[Vision Intelligence systems: Aerial Intelligence OBB Detector Anatomy]]></title>
            <link>https://medium.com/@abdullah.hosam13/vision-intelligence-systems-aerial-intelligence-obb-detector-anatomy-679c6ae6d67c?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/679c6ae6d67c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[war]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[palantir]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 23:52:42 GMT</pubDate>
            <atom:updated>2026-04-01T23:52:42.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VduNEIjjl4k7GT29ubavZQ.jpeg" /></figure><p>Access the following Github repo <a href="https://github.com/abdullah-younnis/Aerial-Intelligence-OBB-Detector">Aerial Intelligence OBB Detector</a></p><p>In my previous article, I discussed how modern warfare isn’t just about weapons anymore — it’s about intelligent systems that understand reality and act upon it.</p><p>You can see it here on medium: <a href="https://medium.com/@abdullah.hosam13/modern-wars-intelligence-beats-weapons-40a80d73d34d">modern wars intelligence beats-weapons</a></p><p>But let’s get closer… and dive a layer deeper:</p><p>What actually powers these systems?</p><p>From Data… to Understanding: Any intelligent military system needs to start with one thing:</p><p>Perception</p><p>Simply put: The system must “see” the world first, before it can understand or decide within it.</p><p>This is where systems like mine come into play:</p><p>Not just a computer vision model…</p><p>But a fundamental component in a much larger architecture.</p><p><em>The Problem: Reality Isn’t Straight</em></p><p>When you look at satellite or drone imagery, you’ll find:</p><ul><li>Vehicles aren’t moving in straight lines</li><li>Aircraft are parked at different angles</li><li>Ships are moving in irregular directions</li></ul><p>Traditional models use axis-aligned Bounding Boxes (HBB), which leads to:</p><ul><li>Noise around the target</li><li>Loss of directional precision</li><li>Difficulty understanding movement</li></ul><p>The Solution: Understanding the True Shape of Objects</p><p>This is where the concept emerges: Oriented Bounding Boxes (OBB)</p><p>Instead of saying: “<em>There’s a vehicle here</em>”</p><p>The system can say: “<em>There’s a vehicle here… moving in this direction</em>”</p><p>This makes a huge difference.</p><p>What This System Actually Does</p><p>I built the system to rely on:</p><ul><li>High-resolution satellite imagery (4K → 20K)</li><li>Image slicing into smaller patches (for processing)</li><li>A vision model (Rotated RetinaNet)</li><li>Reassembling results into a single image</li></ul><p>In the end, it outputs:</p><ol><li>Target type</li><li>Position</li><li>Dimensions</li><li>Direction (rotation angle)</li></ol><p>You may ask Younis Why Direction Matters?</p><p>Because direction = intent. For example:</p><ul><li>Stationary aircraft → normal state</li><li>Aircraft turning toward runway → preparing for takeoff</li><li>Group of vehicles all heading to one point → potential organized movement</li></ul><p>The difference here isn’t in “what exists”. But in “what’s happening”</p><p>Connecting This to the OODA Loop. If we return to the OODA Loop model:</p><p>1. Observe (Reconnaissance)</p><p>This is where my system comes in:</p><ul><li>Analyzing satellite imagery</li><li>Detecting targets</li><li>Determining directions</li></ul><p>This is the eyes of the system</p><p>2. Orient (Analysis)</p><p>After detection:</p><ul><li>Connecting targets together</li><li>Analyzing directions</li><li>Comparing with previous states</li></ul><p>This is where the picture starts to form.</p><p>3. Decide (Decision Making)</p><p>Based on:</p><ul><li>Number of targets</li><li>Their directions</li><li>Their distribution</li></ul><p>The system determines:</p><blockquote><em>Is this a threat?</em></blockquote><blockquote><em>Should we move?</em></blockquote><blockquote><em>Or just monitor?</em></blockquote><p>4. Act (Execution)</p><p>And finally:</p><ul><li>Sending commands</li><li>Activating drones</li><li>Or even ignoring the event</li></ul><p>The Real Secret: Transforming from Detection → Intelligence</p><p>The important point here:</p><p>This system alone isn’t the “brain of war”</p><p>But it is:</p><p>&gt; The first layer — the perception layer</p><p>But when you add to it:</p><ul><li>Tracking (target tracking)</li><li>Context (maps and areas)</li><li>Event Engine (event analysis)</li><li>Graph Intelligence (connecting everything)</li></ul><p>It transforms from: “It sees”</p><p>To: “It understands… and predicts”</p><p>The Real Challenge</p><p>We’re not dealing with a single image</p><p>We’re dealing with:</p><ul><li>Thousands of images</li><li>Continuous data flow</li><li>Very small targets (5–30 pixels)</li><li>High noise</li></ul><p>This makes:</p><p>Building a stable and accurate system = a real engineering challenge</p><p>Current Reality</p><p>Systems like this are already being used in:</p><ul><li>Satellite imagery analysis</li><li>Military movement monitoring</li><li>Asset tracking (aircraft — ships — vehicles)</li></ul><p>But the real difference lies in:</p><p>&gt; The system’s ability to connect and analyze, not just detect</p><p>Where Are We Heading?</p><p>In the near future, these systems will evolve from:</p><ul><li>Detect objects</li></ul><p>To:</p><ul><li>Understand behavior</li><li>Predict actions</li><li>Recommend decisions</li></ul><p>My Technical Architecture Deep Dive</p><p><em>Why I Chose Rotated RetinaNet?</em></p><p>I designed the system using Rotated RetinaNet — a one-stage anchor-based rotated object detector. I chose this architecture for specific reasons:</p><p>Architecture Components:</p><p>- Backbone: ResNet-50/101 for feature extraction</p><p>- FPN: Feature Pyramid Network for multi-scale fusion</p><p>- Rotated Anchor Generator: Generates 18 anchors per location (3 aspect ratios × 6 angles)</p><p><em>OBB Representation Design</em></p><p>I designed the OBB representation using 5 parameters: (x_center, y_center, width, height, theta) with:</p><p>- Theta angle in range [-90°, 90°)</p><p>- Angle normalization to prevent ambiguity between 0° and 180°</p><p>- Round-trip property: OBB → Polygon → OBB produces equivalent OBB</p><p><em>Advanced Loss System</em></p><p>I implemented three types of losses:</p><p>1. Focal Loss for classification (α=0.25, γ=2.0) to handle extreme class imbalance</p><p>2. Smooth L1 for box regression (dx, dy, dw, dh)</p><p>3. Angle-aware Smooth L1 for angle regression with wrap-around handling at ±90°</p><p><em>SAHI Slicing for Massive Images</em></p><p>To handle images up to 20K×20K pixels, I implemented:</p><p>- Image slicing into 1024×1024 patches with 25% overlap</p><p>- Guaranteed coverage of every pixel by at least one patch</p><p>- Result reassembly with NMS to remove duplicates</p><p><em>Geometry Engine</em></p><p>I built a specialized geometry engine:</p><p>- Rotated IoU: Using Shapely for rotated shape intersection calculation</p><p>- Rotated NMS: Three variants (basic, class-wise, batched)</p><p>- Performance: &lt;10ms on CPU for 100–1000 detections</p><p><em>DOTA Data Processing</em></p><p>I designed the system to process the DOTA dataset with 15 classes:</p><p>- Annotation format: x1 y1 x2 y2 x3 y3 x4 y4 class_name difficulty</p><p>- 4000×4000 image slicing into 1024×1024 patches</p><p>- Inclusion of annotations with ≥30% visibility inside patches</p><p>Comprehensive Testing</p><p>I implemented property-based testing with Hypothesis :</p><p>- 9 geometry tests (OBB round-trip, IoU bounds, NMS)</p><p>- 6 data pipeline tests (annotation parsing, patch coverage)</p><p>- 8 model tests (anchor generation, loss functions)</p><p>- 6 inference tests (SAHI coverage, coordinate transforms)</p><p>Conclusion</p><p>Modern warfare doesn’t just start with a decision…</p><p>It starts with:</p><p>&gt; The ability to see reality accurately</p><p>And models like my Aerial Intelligence OBB Detector</p><p>aren’t just computer vision projects…</p><p>But:</p><p>&gt; Fundamental building blocks in constructing intelligent decision-making systems</p><p>And the most important question:</p><p>If perception is the first step in any intelligent system…</p><p>Are we ready to build the remaining layers?</p><p>Or will we remain stuck at “a model that outputs boxes”?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=679c6ae6d67c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern wars: Intelligence beats weapons]]></title>
            <link>https://medium.com/@abdullah.hosam13/modern-wars-intelligence-beats-weapons-40a80d73d34d?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a80d73d34d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[israel-palestine-conflict]]></category>
            <category><![CDATA[war]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 17:32:29 GMT</pubDate>
            <atom:updated>2026-03-21T17:32:29.696Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*p6P-EIt94jcm3g-OgBa7ow.jpeg" /><figcaption>Photo from media.cybernews.com</figcaption></figure><p>Iran, Israel, the US, Russia, Ukraine… and soon China and Taiwan. What do they all have in common?</p><p>We all saw the news about Anthropic withdrawing from its contract with the Pentagon. That was a small indicator of a much bigger struggle happening behind the scenes — a struggle not just fought with weapons, but with data and artificial intelligence.</p><p>Today, we’re looking at a slightly different angle. As engineers and researchers in AI and machine learning, when we think about military applications, we usually associate them with weapons. But the reality is much deeper. These companies now have extremely advanced simulation technologies and can build systems capable of understanding reality, predicting it, and even shaping it… and most of these technologies are not publicly available and will likely remain so for a long time.</p><p>The goal of this article is to help us understand the bigger picture more clearly. In a follow-up article, I will explain practically how I managed to build a component of these modern war management systems.</p><h3>From Weapons… to Smart Systems</h3><p>We’re not just talking about a specific weapon. We’re talking about a complete system that controls the operations center. A self-sufficient system that receives real-time data, analyzes it, generates scenarios, makes decisions… and even adjusts its decisions based on the circumstances and the budget.</p><p>In short: a central brain for war.</p><p>This becomes clear when we look at systems like the <strong>OODA Loop</strong>, which forms the foundation of US military operational management.</p><h3>OODA Loop: How Decisions Are Made</h3><p>The OODA Loop operates through four interconnected stages:</p><p><strong>Observe:</strong> Collect everything imaginable — satellite images, drones, communications, ground movements, economic data, and social media activity. Anything that can be turned into data enters this stage.</p><p><strong>Orient:</strong> This is the most critical stage. Data alone has no value without context. Here, everything is connected: the enemy’s history, past behaviors in conflicts, psychological state, and economic condition… the full picture starts to emerge.</p><p><strong>Decide:</strong> Based on the analysis, options are determined: how many resources do we have? Equipment readiness? Force distribution? Type of weapons? Every detail influences the decision.</p><p><strong>Act:</strong> Finally, the decision is turned into action: where to strike, when, with what weapons, and how to respond if the enemy reacts.</p><h3>The Real Secret: Speed</h3><p>From all of the above, one thing stands out: <strong>speed</strong>.</p><p>It’s not about who has more information; it’s about who can use that information faster. Simply put, the information you received 30 minutes ago may already be outdated.</p><p>Speed is not just about execution — it’s about analysis and decision-making. This also opens the door to strategic deception: feeding the enemy misleading information or orchestrated movements to force them into mistakes, creating opportunities.</p><h3>The Technical Challenge: Data Volume</h3><p>We’re talking about <strong>tens of terabytes per hour</strong>. A massive data volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itZmEN8a8G3vU_ru7c-CbQ.jpeg" /></figure><p>If you relied only on humans:</p><ul><li>Each analyst would cover a small part</li><li>There’s no complete integration between all sources</li><li>The final picture would be incomplete</li></ul><p>This creates a dangerous gap in understanding and decision-making.</p><h3>The Solution: Systems That Connect Everything</h3><p>This is where AI comes in.</p><p>Instead of an analyst just looking at an image and noting it down, the system:</p><ul><li>Compares the image with historical data</li><li>Connects it to communications or movements</li><li>Tracks the path</li><li>Analyzes the full context</li></ul><p>And finally concludes: is this target important? Is it a threat? Should we act?</p><p>This is what makes decisions faster, more accurate, and gives a more complete situational awareness.</p><h3>The Current Reality</h3><p>These systems are already becoming clear in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s12Z4SGZUaEQ-HeFNdS-sg.jpeg" /></figure><ul><li>Projects like <strong>Project Maven</strong> have been analyzing images and videos for years</li><li>Companies like <strong>Palantir</strong> have reduced the number of soldiers needed dramatically while maintaining the same efficiency</li><li>Systems can create a real-time map of the battlefield</li><li>Autonomous drones can execute missions without human intervention</li><li>Systems select the right soldiers for a mission based on health and psychological data</li></ul><p>In some cases, decision-making can now occur in just a few seconds.</p><h3>Where Are We Headed?</h3><p>The race is no longer just about weapons. It’s about:</p><ul><li>Who has more data</li><li>Who has smarter systems</li><li>Who can make decisions faster</li></ul><p>At the same time, countries like China aim to lead in this field by 2030. While the details are unclear, there is a strong belief that significant progress has been made behind the scenes.</p><h3>Conclusion</h3><p>We are facing a radical transformation in the nature of warfare.</p><p>The question is no longer “who has the strongest weapon,” but “who has the smartest and fastest system.”</p><p>AI is no longer just a tool — it is becoming a <strong>core element of decision-making itself</strong>.</p><p>The big question for us as engineers and researchers: will we be part of building these systems, or will we merely use them after they become a reality?</p><p>Resources:</p><p><a href="https://en.wikipedia.org/wiki/OODA_loop">OODA loop — Wikipedia</a></p><p><a href="https://en.wikipedia.org/wiki/Project_Maven">Project Maven — Wikipedia</a></p><p><a href="https://www.war.gov/News/News-Stories/Article/Article/3377624/dod-investing-in-wearable-technology-that-could-rapidly-predict-disease/">DOD Investing in Wearable Technology That Could Rapidly Predict Disease &gt; U.S. Department of War &gt; Defense Department News | U.S. Department of War</a></p><p><a href="https://lieber.westpoint.edu/gospel-lavender-law-armed-conflict/">Israel — Hamas 2024 Symposium — The Gospel, Lavender, and the Law of Armed Conflict — Lieber Institute West Point</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a80d73d34d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Joinings Hierarchy]]></title>
            <link>https://medium.com/@abdullah.hosam13/sql-joinings-hierarchy-2e6798d9dba5?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6798d9dba5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 10:34:09 GMT</pubDate>
            <atom:updated>2024-09-08T10:34:09.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FcJd3rVzV0IMZB27Fa1CQ.gif" /><figcaption><a href="https://media3.giphy.com/media/vISmwpBJUNYzukTnVx/giphy.gif"><strong>Data Coding GIF by DataCamp — Find &amp; Share on GIPHY</strong></a></figcaption></figure><h3>What Is Set Theory?</h3><ul><li><strong>Definition</strong>: Set theory deals with collections of objects (called sets) and the relationships between those sets.</li></ul><p><strong>Basic Concepts</strong>:</p><ul><li>A <strong>set</strong> is a collection of zero or more elements (objects).</li><li>Elements within a set can be of any data type (numbers, strings, structures, etc.).</li><li>Sets can be finite or infinite.</li><li>Sets can intersect, union, or differ from each other.</li></ul><h3>Sets in SQL:</h3><p>Tables as Sets: In SQL, a table corresponds to a set</p><p>. Each row in the table represents an element (record) within that set.</p><p>Set Operations in SQL: SQL provides set operations inspired by set theory:</p><ul><li><strong>UNION</strong>: Combines elements from two sets (removing duplicates).</li><li><strong>INTERSECT</strong>: Returns common elements between two sets.</li><li><strong>EXCEPT</strong>: Returns elements from the first set that are not in the second set.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jq33ZPOkknY58iNxW7M9bw.jpeg" /><figcaption>A visualization using Venn Diagrams for set theory Source: DataCamp</figcaption></figure><h3><strong>Types of SQL Sets.</strong></h3><h4>UNION And UNION ALL</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*8038GyboAndm1XDlA2iACw.jpeg" /></figure><p><strong>UNION</strong> takes two tables as input and returns all records from both tables<br>if there are two identical records UNION retrieve them once, in other words UNION doesn’t include duplicates.</p><ul><li>The UNION operator combines the result sets of two or more SELECT statements into a single result set.</li><li>It removes duplicate records from the combined result set.</li><li>In other words, it returns only distinct values.</li></ul><pre>SELECT col1, col2 FROM table1<br>UNION<br>SELECT col, col2 FROM table2;</pre><p><strong>UNINON ALL</strong> The UNION ALL operator also combines the result sets of two or more SELECT statements.</p><ul><li>However, unlike UNION, it retains all records, including duplicates.</li><li>It does not remove duplicate rows; it simply concatenates the results.</li></ul><pre>SELECT col1, col2 FROM table1<br>UNION ALL<br>SELECT col1, col2 FROM table2;</pre><p><strong>Use Cases</strong>:</p><ul><li>Use UNION when you want to eliminate duplicate rows and combine distinct values.</li><li>Use UNION ALL when you want to include all records, even if they are duplicates.</li></ul><h4>INTERSECT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*BeV9fI5MCRN_v0NJe6KWoA.jpeg" /></figure><p>The INTERSECT operator is a powerful tool for finding common data between two or more result sets.</p><ul><li>The INTERSECT operator returns distinct rows that appear in both the left and right input queries.</li><li>It inherently removes duplicates, ensuring that only unique common values are included.</li></ul><pre>SELECT col1, col2<br>FROM table1<br>INTERSECT<br>SELECT col1, col2<br>FROM table2;</pre><p><strong>Use Cases:</strong></p><ul><li>Identify overlapping data between multiple tables or queries.</li><li>Find records that exist in both sets simultaneously.</li></ul><h4>EXCEPT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*HSApp_HSO8UErNroftuukg.jpeg" /></figure><p>The EXCEPT operator returns distinct rows from the left query that are not present in the right query.</p><ul><li>In other words, it subtracts the common rows between the two sets, returning only the unique rows from the left set.</li><li>Allows us to identify the records that are represent in one table but not the other</li></ul><pre>SELECT col1, col2<br>FROM table1<br>EXCEPT<br>SELECT col1, col2<br>FROM table2;<br></pre><p>So, when you need to compare datasets and find what’s unique, think of EXCEPT as your data detective! 🕵️‍♂️🔍</p><p>Important notes on set theory:</p><ul><li>The number and order of columns must be the same in both queries.</li><li>Data types must be compatible for comparison.</li><li>NULL values are considered equal when determining distinct rows.</li><li>Field name retained from the left table even when aliased</li></ul><h3>JOINING DATA IN SQL<br>_______________________</h3><p>In SQL, a join is used to combine data from two or more tables into a single result set. It allows you to work with related data as if it were stored in a single table.</p><ul><li>Imagine you have data distributed across different tables (one table for customers and another for orders).</li><li>Joins allow you to retrieve relevant information from both tables based on a common column (usually an ID or key).</li></ul><h4>Defining Relationships</h4><p>One-to-One Relationship:</p><ul><li>In a one-to-one relationship, each record in Table A is associated with one and only one record in Table B, and vice versa.</li><li>Example: Consider tables users and user_profiles, where each user has a single corresponding profile.</li></ul><p>One-to-Many Relationship:</p><ul><li>In a one-to-many relationship, each record in Table A can be associated with multiple records in Table B, but each record in Table B is associated with only one record in Table A.</li><li>Example: Tables Writer and his Books, where each Writer can have multiple Books, but each book belongs to one writer.</li></ul><p>Many-to-Many Relationship:</p><ul><li>In a many-to-many relationship, each record in Table A can be associated with multiple records in Table B, and vice versa.</li><li>Example: Tables students and courses, where each student can enroll in multiple courses, and each course can have multiple students.</li></ul><h4>Types of Joins</h4><ol><li>Inner Join</li><li>Multiple Joins: (Outer Join, Cross Join, Self-Join)</li></ol><p><strong>Outer Join</strong> Including (Left Outer Join, Right Outer Join, Full Outer Join)</p><p>_________________________________________________________________</p><p><strong>. INNER JOIN</strong></p><p>Suppose you have two tables, let’s call them Table A and Table B.<br>For each row in Table A, the INNER JOIN clause finds the matching rows in Table B based on a specified condition (usually a shared column).<br>If a row is matched, it’s included in the final result set.</p><p>We use ON keyword as a matching criterion. We can also use USING command followed by the shared column name in ()<br>NOTE: The table.column format must be used when selecting columns that exist in both tables to avoid SQL error</p><p>Aliases can be used in the table.column_name syntax in SELECT and ON clauses and that’s because of order of execution.</p><pre>SELECT common_col1 AS col1, common_col2 AS col2<br>FROM TableA<br>INNER JOIN TableB ON TableA.col1 = TableB.col2;</pre><p>Order of execution</p><p>It means how computer executes the commands in our code by order. Understanding it will give you a complete overview on the code and make a well-defined view of your code when start writing it.</p><pre>FROM // execute first then <br>INNER JOIN<br>THEN ON or Using keyword<br>Lastly our SELECT</pre><h3>Multiple joins</h3><h4>__________________________________________________________</h4><h4>Outer joins</h4><p>LEFT and RIGHT, FULL JOINs</p><p>LEFT OUTER JOIN (or LEFT JOIN):<br>In a left outer join, all rows from the left (or first) table are included, along with matching rows from the right (or second) table.<br>If there are no matching rows in the right table, the result will still include the left table’s rows, with NULL values for the right table’s columns.<br>It keeps all data from the left table and only the matching data from the right table.</p><p>RIGHT OUTER JOIN (or RIGHT JOIN):<br>The right outer join is similar to the left outer join but reversed.<br>All rows from the right table are included, along with matching rows from the left table.<br>If there are no matching rows in the left table, the result will still include the right table’s rows, with NULL values for the left table’s columns.<br>It keeps all data from the right table and only the matching data from the left table.</p><p>FULL OUTER JOIN (or FULL JOIN):<br>A full outer join combines both left and right outer joins.<br>It includes all rows from both tables, matching rows where they exist, and NULL values where there are no matches.<br>Essentially, it gives you the union of the left and right tables.</p><p><strong>Here’s a brief summary</strong>:</p><p><strong>LEFT JOIN</strong>: Keeps all data from the left table and matching data from the right table.</p><p><strong>RIGHT JOIN</strong>: Keeps all data from the right table and matching data from the left table.</p><p><strong>FULL JOIN</strong>: Includes all data from both tables, with NULLs where no match occurs.</p><p>Example: We have two tables countries and economies. We want to combine both and see the average GDP per capita in each region and we’re only interested in results from the year 2010 only and want it from highest to lowest and want to see highest 10 regions?</p><pre>SELECT region, AVG(gdp_percapita) AS avg_gdp<br>FROM countries AS c<br>LEFT JOIN economies AS e<br>USING(code) -- our matching criteria<br>WHERE year = 2010<br>GROUP BY region<br>-- Order by descending avg_gdp<br>ORDER BY avg_gdp DESC<br>-- Return only first 10 records<br>LIMIT 10;</pre><p><strong>CROSS JOIN</strong><br>Creates all possible combinations of two tables</p><p>A CROSS JOIN (also known as a Cartesian join) is an operation that combines rows from two or more tables without any specific relationship between them. Unlike other types of joins (such as INNER JOIN, LEFT JOIN, or FULL OUTER JOIN), the CROSS JOIN doesn’t require a common column for matching — it simply produces the Cartesian product of the joined tables.</p><p>The result of a CROSS JOIN between A and B will have n × m rows, where n is the number of rows in table A and m is the number of rows in table B.</p><p>Let’s illustrate this with an example. Suppose we have two tables: sales_organization and sales_channel. The sales_organization table stores different sales organizations (e.g., Domestic and Export), while the sales_channel table contains various sales channels (e.g., Wholesale, Retail, eCommerce, and TV Shopping).</p><pre>SELECT so.sales_org, sc.channel<br>FROM sales_organization AS so<br>CROSS JOIN sales_channel AS sc;</pre><p>The result will include all possible combinations of sales organizations and sales channels. For example:</p><pre>| sales_org | channel |<br>| - - - - -| - - - - -|<br>| Domestic | Wholesale|<br>| Domestic | Retail   |<br>| Domestic | eCommerce|<br>| Domestic |TV Shopping|<br>| Export | Wholesale  |<br>| Export | Retail     |<br>| Export | eCommerce  |<br>| Export |TV Shopping|</pre><p><strong>SELF JOIN</strong></p><p>A self-join (also known as a self-referential join) occurs when you join a table with itself. In other words, you create a relationship between rows within the same table. It’s like looking at the table from two different perspectives simultaneously. But why would we do this? Well, self joins are useful when you want to relate rows within the same table based on some common criteria.</p><p>Employee Hierarchy: Who Reports to Whom? Suppose you have an employees table with columns like employee_id, employee_name, and manager_id. The manager_id column specifies which employee is the manager of another employee. To find out who reports to whom, you can use a self join:</p><pre>SELECT e1.employee_name AS employee, e2.employee_name AS manager<br>FROM employees AS e1 --table when filtering for the employees<br>JOIN employees AS e2 --self-join the table and this one will be for managers<br>ON e1.manager_id = e2.employee_id; --here we match if the e1.manger_id is matching<br>-- another employee_id in e2 so that means he&#39;s the manager of the first one</pre><p>Leet-Code problem:</p><p>Let’s solve an easy SQL problem from Leet-Code and walkthrough the solution logic and code.</p><p>Table: Prices</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| product_id    | int     |<br>| start_date    | date    |<br>| end_date      | date    |<br>| price         | int     |<br>+---------------+---------+<br>(product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table.<br>Each row of this table indicates the price of the product_id in the period from start_date to end_date.<br>For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.</pre><p>Table: UnitsSold</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| product_id    | int     |<br>| purchase_date | date    |<br>| units         | int     |<br>+---------------+---------+<br>This table may contain duplicate rows.<br>Each row of this table indicates the date, units, and product_id of each product sold.</pre><p>Write a solution to find the average selling price for each product. average_price should be <strong>rounded to 2 decimal places</strong>.</p><p>Return the result table in <strong>any order</strong>.</p><p>Average selling price = Total Price of Product / Number of products sold.<br>Average selling price for product 1 = ((100 * 5) + (15 * 20)) / 115 = 6.96</p><h4>My solution logic approach:</h4><p>When trying to approach the solution start thinking before coding.</p><p>The statement needs from us to return avg selling price for each product for example product 1 have 100 units and the selling price is like 20 so the equation will be SUM(units sold* price) / # of units sold.</p><p>We should keep in mind the purchase date in the second table as it should be in the duration of the first table coulmns, start_date and end_date price purchase_date falls within the range defined by start_date and end_date.</p><p>We also should keep in mind that some products won’t be sold right?</p><p>So, our code should take the product that haven’t sold units and place Null instead of zero to avoid division by zero errors., Then we use the built in function Coalesce Specifically, it ensures that if the average price is NULL, it is replaced with zero (0).</p><p>The entire expression is then rounded to two decimal places using ROUND.</p><p>An important <strong>note</strong> when starting coding my solution I don’t go upside down. Instead, I start writing <strong>FROM </strong>clause first then the <strong>JOIN </strong>and <strong>GROUPING </strong>and in the end focusing on the <strong>SELECT</strong> statement to ensure my calculations is right and the selection matching the problem statement, and it’s okay to <strong><em>fail</em></strong> I’ve submitted this query like 6 times it succussed in the case in the problem and always fail in the case 15 from 17 each time because of the zero units sold and each time I try different approach until I reached to this solution.</p><p><strong>Code:</strong></p><pre>SELECT p.product_id,<br>       COALESCE(ROUND(SUM(u.units * p.price) / NULLIF(SUM(u.units), 0), 2), 0) AS average_price<br>FROM Prices AS p<br>LEFT JOIN UnitsSold AS u ON p.product_id = u.product_id <br>   AND u.purchase_date BETWEEN p.start_date AND p.end_date<br>GROUP BY p.product_id;</pre><p><em>Problem Link</em>: <a href="https://leetcode.com/problems/average-selling-price/">Average Selling Price — LeetCode</a></p><h4>Summary:</h4><p>So, in this article we walked through different types of set theory and how each one is different from another and take examples on each. Then we explore the different relationships and then the order of execution. Ending it with the different types of Joins and what difference in each one and how to use it, solve some leet-code example problems and my solution for it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6798d9dba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards Model Evaluation Metrics]]></title>
            <link>https://medium.com/@abdullah.hosam13/towards-model-evaluation-metrics-f45b0b8c84e3?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f45b0b8c84e3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 20:29:45 GMT</pubDate>
            <atom:updated>2024-03-28T20:29:45.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fkeTENFKIa6CY1OV" /><figcaption>Photo by <a href="https://unsplash.com/@dilucidus?utm_source=medium&amp;utm_medium=referral">Kai Dahms</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Classification Metrics</h3><p>Classification is the process of categorizing data or objects based on their traits or properties into specified groupings or categories. Classification is a type of supervised learning approach in machine learning in which an algorithm is trained on a labelled dataset to predict the class or category of fresh, unseen data. The primary goal of classification is to create a model capable of properly assigning a label or category to a new observation based on its properties.</p><p>To check the accuracy of classifications, we use the different-different metrics. Some of them are discussed below:</p><ul><li>Accuracy, Precision, Recall</li><li>F1-Score</li><li>ROC-AUC</li><li>PR-AUC</li><li>Log Loss</li></ul><h4>Accuracy</h4><ul><li>Definition: Accuracy is a metric that measures the overall correctness of a model’s predictions by comparing the number of correct predictions to the total number of predictions.</li></ul><blockquote>Accuracy is commonly used when the class distribution in the dataset is balanced and there is an equal importance placed on correctly predicting both positive and negative instances.</blockquote><ul><li>Advantages: It is a simple and intuitive metric that provides a general overview of the model’s performance.</li><li>Disadvantages: Accuracy can be misleading when the dataset is imbalanced, meaning the classes are not represented equally. In such cases, a high accuracy value can be achieved by simply predicting the majority class.</li></ul><h4>Precision</h4><ul><li>Definition: Precision is a metric that calculates the proportion of correctly predicted positive instances (true positives) out of all instances predicted as positive (true positives + false positives).</li></ul><blockquote>Precision is useful when the focus is on minimizing false positives. It is important in scenarios where the cost of false positives is high, such as medical diagnoses or spam detection.</blockquote><ul><li>Advantages: Precision provides information about the model’s ability to avoid false positives, making it useful in situations where false positives are costly or undesirable.</li><li>Disadvantages: Precision alone may not give a complete picture of the model’s performance, as it does not consider false negatives.</li></ul><h4><strong>Recall</strong></h4><ul><li>Definition: Recall, also known as sensitivity or true positive rate, measures the proportion of correctly predicted positive instances (true positives) out of all actual positive instances (true positives + false negatives).</li></ul><blockquote>Recall is valuable when the focus is on minimizing false negatives. It is important in scenarios where missing positive instances is more critical than having false positives, such as disease diagnosis or fraud detection.</blockquote><ul><li>Advantages: Recall provides information about the model’s ability to capture positive instances, making it useful when the cost of false negatives is high.</li><li>Disadvantages: Recall alone may not provide a complete assessment of the model’s performance, as it does not consider false positives.</li></ul><p>The simplest metrics are Accuracy/Precision/Recall. Here are the formulas:</p><p><strong>Accuracy</strong>: (True Positives + True Negatives)/Total Predictions</p><p><strong>Precision</strong>: True Positives/(True Positives + False Positives)</p><p><strong>Recall</strong>: True Positives/(True Positives + False Negatives)</p><pre>from sklearn.metrics import (<br>    accuracy_score,<br>    precision_score,<br>    recall_score<br>)<br><br><br>accuracy = accuracy_score(y_test, y_preds)<br>precision = precision_score(y_test, y_preds)<br>recall = recall_score(y_test, y_preds)<br><br><br>print(&quot;Accuracy: {0}&quot;.format(accuracy))<br>print(&quot;Precision: {0}&quot;.format(precision))<br>print(&quot;Recall: {0}&quot;.format(recall))</pre><p><strong>F1-Score</strong></p><ul><li>Definition: The F1-score is a metric that combines precision and recall into a single value by calculating the harmonic mean of the two. It provides a balanced measure of a model’s performance.</li></ul><blockquote>The F1-score is commonly used when there is an uneven class distribution and there is equal importance placed on precision and recall.</blockquote><ul><li>Advantages: The F1-score considers both precision and recall, providing a balanced assessment of the model’s performance.</li><li>Disadvantages: The F1-score might not be the best choice when the relative importance of precision and recall varies depending on the specific problem or domain.</li></ul><pre>from sklearn.metrics import f1_score<br>f1 = f1_score(y_test, y_preds)<br>print(&quot;F1: {0}&quot;.format(f1))</pre><p><strong>ROC-AUC</strong></p><ul><li>Definition: ROC-AUC (Receiver Operating Characteristic — Area Under the Curve) is a performance metric that measures the ability of a model to discriminate between classes, considering all possible classification thresholds.</li></ul><blockquote>ROC-AUC is particularly useful when the class distribution is imbalanced and the cost of false positives and false negatives is roughly equal. It is commonly used in binary classification problems.</blockquote><ul><li>Advantages: ROC-AUC provides a comprehensive evaluation of a model’s performance across all possible classification thresholds, making it robust to imbalanced datasets.</li><li>Disadvantages: ROC-AUC does not directly provide information about the optimal classification threshold or the trade-off between precision and recall.</li></ul><pre>from sklearn.metrics import (<br>    roc_auc_score)<br><br>roc_auc = roc_auc_score(y_test, y_preds)</pre><p><strong>PR-AUC</strong></p><ul><li>Definition: PR-AUC (Precision-Recall Area Under the Curve) is a performance metric that measures the trade-off between precision and recall at different classification thresholds.</li></ul><blockquote>PR-AUC is particularly useful when the class distribution is imbalanced and there is a significant difference in the cost of false positives and false negatives. It is commonly used in binary classification problems.</blockquote><ul><li>Advantages: PR-AUC focuses on precision and recall, providing insights into the model’s performance at different classification thresholds, especially when dealing with imbalanced datasets.</li><li>Disadvantages: PR-AUC may not be as interpretable as ROC-AUC for some individuals, as it mainly focuses on precision and recall.</li></ul><pre>from sklearn.metrics import (<br>    average_precision_score<br>)<br><br>pr_auc = average_precision_score(y_test, y_preds)</pre><p><strong>Log Loss</strong></p><ul><li>Definition: Log Loss is a loss function that measures the performance of a classification model by penalizing incorrect predictions based on the predicted probabilities assigned to the classes.</li></ul><blockquote>Log Loss is commonly used as a loss function during the training of probabilistic models, such as logistic regression or neural networks, and is suitable for binary and multi-class classification tasks.</blockquote><ul><li>Advantages: Log Loss provides a continuous and differentiable measure of the model’s performance, encouraging the model to output well-calibrated probabilities.</li><li>Disadvantages: Log Loss may be sensitive to extreme probabilities and can be heavily influenced by outliers in the predicted probabilities. It is not as interpretable as other evaluation metrics like accuracy or precision.</li></ul><pre>from sklearn.metrics import (<br>    log_loss<br>)<br><br>log_loss = log_loss(y_test, y_preds)</pre><h3>Regression Metrics</h3><p>Regression metrics are quantitative measures used to evaluate the nice of a regression model. Scikit-analyze provides several metrics, each with its own strengths and boundaries, to assess how well a model suits the statistics.</p><p>we use different metrics. Some of them are discussed below:</p><ul><li>R2 Score</li><li>Adj R2 Score</li><li>Mean Absolute Error</li><li>Root Mean Squared Error</li></ul><h4>R2 Score (Coefficient of Determination):</h4><ul><li>Definition: The R2 score is a statistical measure that represents the proportion of the variance in the dependent variable that can be explained by the independent variables in a regression model. It indicates how well the regression model fits the observed data.</li></ul><blockquote>The R2 score is commonly used to evaluate the performance of regression models. It helps assess the goodness of fit and provides an indication of how well the model predicts the dependent variable.</blockquote><ul><li>Advantages: The R2 score provides a standardized measure of the model’s performance and can range from 0 to 1, with a higher value indicating a better fit. It is easy to interpret, with 1 representing a perfect fit.</li><li>Disadvantages: The R2 score can be misleading when used alone, as it doesn’t indicate whether the model’s predictions are unbiased or if the model is overfitting or underfitting the data.</li></ul><pre>def r2_score(y_test, y_preds):<br>    SS_reg = np.sum((y_test - y_preds)**2)<br>    SS_total = np.sum((y_test - np.mean(y_test))**2)<br>    r2 = 1-SS_reg/SS_total<br>    return r2</pre><h4>Adjusted R2 Score:</h4><ul><li>Definition: The adjusted R2 score is a modified version of the R2 score that takes into account the number of predictors in the regression model. It adjusts the R2 score to penalize the addition of irrelevant predictors.</li></ul><blockquote>The adjusted R2 score is useful when comparing models with different numbers of predictors. It helps prevent overfitting by accounting for the complexity of the model.</blockquote><ul><li>Advantages: The adjusted R2 score provides a more conservative estimate of the model’s performance by considering the number of predictors. It helps in selecting the most appropriate model among multiple options.</li><li>Disadvantages: The adjusted R2 score can decrease even if a new predictor is marginally useful, as it penalizes the addition of predictors. It may not always accurately reflect the true predictive power of the model.</li></ul><pre>def adj_r2_score(X, y_test, y_preds):<br>    SS_reg = np.sum((y_test - y_preds)**2)<br>    SS_total = np.sum((y_test - np.mean(y_test))**2)<br>    r2 = 1-SS_reg/SS_total<br>    <br>    N = len(X)<br>    p = len(X.columns)<br>    <br>    adj_r2 = 1-((1-r2)*(N-1))/(N-p-1)<br>    return adj_r2</pre><h4>Mean Absolute Error (MAE):</h4><ul><li>Definition: Mean Absolute Error is a metric that calculates the average absolute difference between the predicted and actual values in a regression model. It provides a measure of the average magnitude of errors.</li></ul><blockquote>MAE is commonly used to evaluate the performance of regression models, especially when the presence of outliers is a concern. It provides a robust measure of the model’s accuracy.</blockquote><ul><li>Advantages: MAE is easy to interpret and provides a straightforward measure of the model’s performance. It is less sensitive to outliers compared to other error metrics like RMSE.</li><li>Disadvantages: MAE treats all errors equally and does not differentiate between overestimation and underestimation. It may not capture the squared differences as effectively as RMSE.</li></ul><pre>def mean_absolute_error(y_test, y_preds):<br>    return np.sum(abs(y_preds - y_test))/len(y_preds)</pre><h4>Root Mean Squared Error (RMSE):</h4><ul><li>Definition: Root Mean Squared Error is a metric that calculates the square root of the average of the squared differences between the predicted and actual values in a regression model. It provides a measure of the standard deviation of the errors.</li></ul><blockquote>RMSE is commonly used to evaluate the performance of regression models. It gives higher weight to larger errors and is sensitive to the presence of outliers.</blockquote><ul><li>Advantages: RMSE penalizes large errors more than MAE, making it suitable when large errors have significant consequences. It provides a measure of the spread or dispersion of errors.</li><li>Disadvantages: RMSE is sensitive to outliers and can be heavily influenced by extreme values. It is not directly interpretable in the same unit as the target variable, as it squares the differences.</li></ul><pre>def mean_squared_error(y_test, y_preds):<br>    return np.sum((y_preds - y_test)**2)/len(y_preds)</pre><p><strong>Resources</strong>:</p><p><a href="https://www.geeksforgeeks.org/regression-metrics/">Regression Metrics</a></p><p><a href="https://www.geeksforgeeks.org/sklearn-classification-metrics/">Classification Metrics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f45b0b8c84e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensemble algorithms in Machine Learning]]></title>
            <link>https://medium.com/@abdullah.hosam13/ensemble-algorithms-in-machine-learning-97b6b284f9c6?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b6b284f9c6</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 16:50:52 GMT</pubDate>
            <atom:updated>2024-03-28T16:50:52.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*rNP17NMgUmMxiqt4.png" /><figcaption><a href="https://corporatefinanceinstitute.com/resources/data-science/ensemble-methods/"><strong>Ensemble Methods — Overview, Categories, Main Types</strong></a></figcaption></figure><p>Ensemble methods are <strong>machine learning and statistical techniques that combine multiple models to improve the accuracy and robustness of predictions</strong>. The purpose of ensemble methods is to reduce the risk of overfitting and increase the stability of predictions by aggregating the outputs of multiple models3. Ensemble methods create multiple models, called base estimators, and then combine them to produce improved results.</p><h4>Bagging:</h4><ul><li><strong>Definition</strong>: Bagging, short for <strong>bootstrap aggregating</strong>, is an ensemble learning technique that combines <strong>multiple </strong>models’ <strong>predictions </strong>to make a<strong> final prediction</strong>. It involves training several individual models on different subsets of the training data, obtained through <strong>bootstrapping</strong> (sampling with replacement). The models are trained independently, and their predictions are combined through majority voting or averaging <strong>aggregating</strong>.</li><li><strong>How it works</strong>: Bagging works by <strong>creating</strong> multiple subsets of the original training data through <strong>random sampling with replacement</strong>. Each subset is used to train a separate model, typically using the same learning algorithm. The models are then combined by <strong>aggregating</strong> their predictions, which can be done through <strong>majority voting</strong> (for classification problems) or <strong>averaging</strong> (for regression problems).</li></ul><p>Let’s look when we have a classification case where we tend to use majority voting.</p><pre>from sklearn.ensemble import VotingClassifier<br><br>dt_voting = DecisionTreeClassifier(**{&#39;criterion&#39;: &#39;entropy&#39;, &#39;max_depth&#39;: 44, &#39;max_features&#39;: None, &#39;min_samples_split&#39;: 2, &#39;splitter&#39;: &#39;random&#39;}) # ** allows you to pass in parameters as dict<br>knn_voting = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=1))<br>lr_voting = LogisticRegression(random_state=32, max_iter = 2000, class_weight = &#39;balanced&#39;)<br><br>ens = VotingClassifier(estimators = [(&#39;dt&#39;, dt_voting), (&#39;knn&#39;, knn_voting), (&#39;lr&#39;,lr_voting)], voting = &#39;hard&#39;)</pre><pre>ens = VotingClassifier(estimators = [(&#39;dt&#39;, dt_voting), (&#39;knn&#39;, knn_voting), (&#39;lr&#39;,lr_voting)], voting = &#39;soft&#39;)<br>voting_accuracy = cross_val_score(ens,X_train,y_train.values.ravel(), cv=3, scoring =&#39;accuracy&#39;)<br>voting_f1 = cross_val_score(ens,X_train,y_train.values.ravel(), cv=3, scoring =&#39;f1&#39;)<br><br>print(&#39;voting_accuracy: &#39; +str(voting_accuracy))<br>print(&#39;voting F1_Macro Score: &#39;+str(voting_f1))<br>print(&#39;voting_accuracy_avg: &#39; + str(voting_accuracy.mean()) +&#39;  |  voting_f1_avg: &#39;+str(voting_f1.mean()))</pre><p>To understand the parameters of VotingClassifier visit documentation <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.VotingClassifier.html">here</a>.</p><p><strong>Advantages</strong>:</p><ul><li>Bagging helps reduce the variance of the final prediction by combining multiple models.</li><li>It can improve the overall accuracy and generalization of the model.</li><li>Bagging is relatively simple to implement and parallelizable, allowing for efficient computation.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Bagging may not significantly reduce bias in the models.</li><li>It can be computationally expensive if the individual models require substantial computational resources.</li></ul><blockquote>When to use: Bagging is useful when dealing with high-variance models or when the dataset is prone to overfitting. It is commonly used with decision trees or random forests.</blockquote><ul><li><strong>Example</strong>: Random Forest is an example of a bagging ensemble algorithm. It combines multiple decision trees trained on different subsets of the data to make predictions.</li></ul><h4>Boosting:</h4><ul><li><strong>Definition</strong>: Boosting is an ensemble learning technique that iteratively trains weak models to create a strong predictive model. It focuses on sequentially improving the model’s performance by giving more weight to misclassified instances in the training data. Each subsequent weak model is trained to correct the mistakes made by the previous models.</li><li><strong>How it works</strong>: Boosting starts by training an initial weak model on the training data. The subsequent models are then trained by assigning higher <strong>weights </strong>to the <strong>misclassified </strong>instances in the training data. The models are <strong>combined </strong>by <strong>weighted voting or weighted averaging</strong>, where models with <strong>higher accuracy are given more weight</strong>.</li></ul><pre>from sklearn.ensemble import AdaBoostClassifier<br>from sklearn.datasets import make_classification<br>X, y = make_classification(n_samples=1000, n_features=4,<br>                            n_informative=2, n_redundant=0,<br>                            random_state=0, shuffle=False)<br><br>AdaBoostClassifier(algorithm=&#39;SAMME&#39;, n_estimators=100, random_state=0)</pre><p><strong>Advantages</strong>:</p><ul><li>Boosting can achieve higher accuracy compared to individual weak models.</li><li>It is effective in handling complex relationships in the data.</li><li>Boosting is less prone to overfitting than bagging.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Boosting is more computationally intensive than bagging.</li><li>It can be sensitive to noisy data and outliers.</li></ul><blockquote>When to use: Boosting is suitable when dealing with high-bias models or when the dataset suffers from underfitting. It is commonly used with algorithms like AdaBoost, Gradient Boosting Machines (GBM), or XGBoost.</blockquote><ul><li>Example: AdaBoost (Adaptive Boosting) is an example of a boosting algorithm. It combines weak models (e.g., decision stumps) and assigns higher weights to misclassified instances to improve the overall accuracy.</li></ul><h4>Stacking:</h4><ul><li><strong>Definition</strong>: Stacking, also known as stacked generalization, is an ensemble learning technique that combines multiple individual models by training a meta-model on their predictions. It involves training several diverse base models, whose predictions serve as input features for the meta-model. The meta-model learns to make the final prediction based on the outputs of the base models.</li><li><strong>How it works</strong>: Stacking consists of two main steps. First, multiple base models are trained on the training data. Then, a meta-model (also called a blender or a meta-learner) is trained on the predictions made by the base models. The base models’ predictions serve as input features for the meta-model, which learns how to combine them to make the final prediction.</li></ul><pre>from sklearn.ensemble import StackingClassifier<br><br>ens_stack = StackingClassifier(estimators = [(&#39;dt&#39;, dt_voting), (&#39;lr&#39;,lr_voting), (&#39;nb&#39;,GaussianNB())], final_estimator = GaussianNB())</pre><pre>stack_accuracy = cross_val_score(ens_stack,X_train,y_train.values.ravel(), cv=3, scoring =&#39;accuracy&#39;)<br>stack_f1 = cross_val_score(ens_stack,X_train,y_train.values.ravel(), cv=3, scoring =&#39;f1&#39;)<br><br>print(&#39;stacking_accuracy: &#39; +str(stack_accuracy))<br>print(&#39;stacking F1_Macro Score: &#39;+str(stack_f1))<br>print(&#39;stacking_accuracy_avg: &#39; + str(stack_accuracy.mean()) +&#39;  |  stack_f1_avg: &#39;+str(stack_f1.mean()))</pre><p><strong>Advantages</strong>:</p><ul><li>Stacking can capture complex relationships between the base models’ predictions and the target variable.</li><li>It can provide better generalization and improve predictive performance.</li><li>Stacking is flexible, allowing various combinations of base models and meta-models.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Stacking can be more complex to implement and computationally expensive.</li><li>It may be prone to overfitting if not properly regularized.</li></ul><blockquote>When to use: Stacking is beneficial when combining diverse models or when seeking higher predictive accuracy. It is commonly used in machine learning competitions or scenarios where performance is critical.</blockquote><ul><li>Example: A typical stacking approach may involve training multiple base models such as random forests, support vector machines (SVM), and neural networks. The predictions made by these models are then used as input features for a meta-model, such as a logistic regression model, which learns to combine them and make the final prediction.</li></ul><p>In the end you can build bagging and boosting and stacking algorithm using each of the below examples:</p><p>Bagging:</p><ul><li>Random Forest: The scikit-learn library in Python provides the RandomForestClassifier class for classification tasks and RandomForestRegressor class for regression tasks.</li></ul><p>Boosting:</p><ul><li>AdaBoost: The AdaBoostClassifier and AdaBoostRegressor classes are available in scikit-learn for implementing AdaBoost.</li><li>Gradient Boosting: The GradientBoostingClassifier and GradientBoostingRegressor classes in scikit-learn can be used for gradient boosting. Additionally, libraries like XGBoost and LightGBM provide their own implementations of gradient boosting, which offer additional features and optimizations.</li></ul><p>Stacking:</p><ul><li>Scikit-learn: Scikit-learn provides the StackingClassifier and StackingRegressor classes for implementing stacking. These classes allow you to specify the base models, meta-model, and stacking strategy.</li><li>mlxtend: The mlxtend library in Python offers the StackingClassifier and StackingRegressor classes, which provide more advanced stacking functionalities and options compared to scikit-learn.</li></ul><p><strong>Resources</strong>:</p><p><a href="https://www.youtube.com/watch?v=sN5ZcJLDMaE">Ensemble (Boosting, Bagging, and Stacking) in Machine Learning: Easy Explanation for Data Scientists</a></p><p><a href="https://www.youtube.com/watch?v=Xz0x-8-cgaQ">Bootstrapping Main Ideas!!!</a></p><p><a href="https://www.youtube.com/watch?v=KIOeZ5cFZ50">Tutorial 42 — Ensemble: What is Bagging (Bootstrap Aggregation)?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b6b284f9c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Guide to Hyperparameter Tunining]]></title>
            <link>https://medium.com/@abdullah.hosam13/a-complete-guide-to-hyperparameter-tunining-098a16dc0c60?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/098a16dc0c60</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 13:39:12 GMT</pubDate>
            <atom:updated>2024-03-28T13:39:12.254Z</atom:updated>
            <content:encoded><![CDATA[<p>Helloz Everyone “Younis” is here and today we will have an important topic about hyperparameter tuning. <strong>Hyperparameter tuning</strong> is an essential concept in the world of machine learning and deep learning. For the beginners it seems hard at the first to get the idea and intuition behind it, but I promise in today’s article I will vanish this problem so let’s start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A2wMl5Pb2OEhdt-D" /><figcaption>Photo by <a href="https://unsplash.com/@adigold1?utm_source=medium&amp;utm_medium=referral">Adi Goldstein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>First let’s explore the types of parameters and what’s the difference between each of them.</p><h4>What is a Model Parameter?</h4><p>A model parameter is a configuration variable that is internal to the model and whose value can be estimated from data through the training.</p><ul><li>They are required by the model when making predictions.</li><li>They values define the skill of the model on your problem.</li><li>They are estimated or learned from data.</li><li>They are often not set manually by the practitioner.</li><li>They are often saved as part of the learned model.</li></ul><p>Parameters are key to machine learning algorithms. They are the part of the model that is learned from historical training data.</p><p>In classical machine learning literature, we may think of the model as the hypothesis and the parameters as the tailoring of the hypothesis to a specific set of data.</p><p>Often model parameters are estimated using an optimization algorithm, which is a type of efficient search through possible parameter values.</p><ul><li><strong>Statistics</strong>: In statistics, you may assume a distribution for a variable, such as a Gaussian distribution. Two parameters of the Gaussian distribution are the mean (<em>mu</em>) and the standard deviation (<em>sigma</em>). This holds in machine learning, where these parameters may be estimated from data and used as part of a predictive model.</li><li><strong>Programming</strong>: In programming, you may pass a parameter to a function. In this case, a parameter is a function argument that could have one of a range of values. In machine learning, the specific model you are using is the function and requires parameters in order to make a prediction on new data.</li></ul><p>Whether a model has a fixed number of parameters or variable number of parameters determines whether it may be referred to as “<em>parametric</em>” or “<em>nonparametric</em>“.</p><p>Some examples of model parameters include:</p><ul><li>The weights in an artificial neural network.</li><li>The support vectors in a support vector machine.</li><li>The coefficients in a linear regression or logistic regression.</li></ul><h4>What is a Model Hyperparameter?</h4><p>A model hyperparameter is a configuration that is external to the model and whose value cannot be estimated from data.</p><ul><li>They are often used in processes to help estimate model parameters.</li><li>They are often specified by the practitioner.</li><li>They can often be set using heuristics.</li><li>They are often tuned for a given predictive modeling problem.</li></ul><p>We cannot know the best value for a model hyperparameter on a given problem. We may use rules of thumb, copy values used on other problems, or search for the best value by trial and error.</p><p>When a machine learning algorithm is tuned for a specific problem, such as when you are using a grid search or a random search, then you are tuning the hyperparameters of the model or order to discover the parameters of the model that result in the most skillful predictions.</p><p>Model hyperparameters are often referred to as model parameters which can make things confusing. A good rule of thumb to overcome this confusion is as follows:</p><blockquote><strong>If you have to specify a model parameter manually then<br>it is probably a model hyperparameter.</strong></blockquote><p>Some examples of model hyperparameters include:</p><ul><li>The learning rate for training a neural network.</li><li>The C and sigma hyperparameters for support vector machines.</li><li>The k in k-nearest neighbors.</li></ul><p>So, at the end of this section, we conclude the difference between a parameter and a hyperparameter.</p><blockquote>A <strong>parameter</strong>: is the parameter of the model that can be determined by training data, these can be considered as internal parameters.</blockquote><blockquote>Example: (Weights, Bias)</blockquote><blockquote>A<strong> Hyperparameter</strong>: are parameters whose value control the learning process. These are adjustable parameters used to obtain an optimal model and can be considered as external parameters.</blockquote><blockquote>Example: (Learning rate, Number of epochs)</blockquote><p>What is hyperparameter tuning?</p><p>Hyperparameter tuning is an essential step in machine learning and is used to optimize the performance of a model by finding the best values for the hyperparameters. Hyperparameters are parameters that are not learned from the data but are set before training the model. They control the behavior and performance of the model, such as the learning rate, the number of hidden layers in a neural network, or the regularization strength.</p><p>Hyperparameter tuning is typically performed after selecting a model architecture and before training the model. It helps in finding the hyperparameter values that result in the best performance on the task at hand. The goal is to strike a balance between underfitting (model too simple, not capturing the complexities of the data) and overfitting (model too complex, fitting noise in the data).</p><p><strong>Steps and considerations for hyperparameter tuning:</strong></p><ol><li>Define the search space: Determine the hyperparameters that need tuning and specify the range or distribution of values to explore for each hyperparameter. The search space can be predefined or customized based on prior knowledge or experimentation.</li><li>Select a tuning method: Choose an appropriate hyperparameter tuning method based on the available computational resources, search space size, and desired exploration strategy. Some common methods include random search, grid search, Bayesian optimization, or more advanced techniques like genetic algorithms or particle swarm optimization.</li><li>Set evaluation criteria: Define the metric or metrics to evaluate the model’s performance. This could be accuracy, precision, recall, F1 score, or any other suitable metric depending on the specific task and goals.</li><li>Perform hyperparameter search: Execute the chosen hyperparameter tuning method to explore the search space and evaluate the model’s performance for each hyperparameter configuration. This typically involves training and evaluating the model multiple times using different hyperparameter combinations.</li><li>Evaluate and compare results: Analyze the performance of the model for each hyperparameter configuration and select the best-performing combination based on the evaluation criteria. It’s <strong>crucial</strong> to consider both the <strong>training </strong>and <strong>validation</strong> <strong>performance</strong> to <strong>avoid </strong>overfitting to the training data.</li><li>Validate the selected configuration: Once the best hyperparameter configuration is identified, it’s essential to <strong>validate</strong> its performance on an independent test set. This provides a more accurate estimation of how the model will perform on unseen data.</li><li>Iterative refinement: Hyperparameter tuning is an iterative process. If the initial results are not satisfactory, you can refine the search space or try different tuning methods to further improve the model’s performance.</li></ol><p>Types of Hyperparameter Tuning methods we will discuss.</p><ol><li>Randomized Parameter Tuning</li><li>GridsearchCV (Exhaustive Parameter Tuning)</li><li>Bayesian Optimization</li></ol><h4><strong>Randomized Parameter Tuning</strong></h4><p><strong>How it works</strong>: Randomized Parameter Tuning is a method where hyperparameters are randomly sampled from specified ranges or distributions. It performs a predefined number of iterations and evaluates the performance of the model for each hyperparameter combination.</p><p>let’s explore the decision tree. Decision trees have a lot more features we can tune. We can tweak the following:</p><ul><li>criterion {gini, entropy, log loss}</li><li>splitter {best, random}</li><li>max depth {int, None}</li><li>min_samples_split {int, None}</li><li>min_samples_leave {int, None}</li><li>min_weight_fraction_leaf {float}</li><li>max_features {int, auto, sqrt, log2, None}</li><li>max_leaf_nodes {int, None}</li><li>min_impurity_decrease {float}</li><li>class_weight {dict, balanced, None}</li><li>ccp_alpha {float}</li></ul><p>There are a lot of parameters to tune! If there are just 2 options for each one that would be 2¹¹, which is 2048 total configurations. In theory, there are infinite numbers of parameter configurations. How do we even get close to finding the best one?</p><p>The answer here is randomized search. We through in all the parameters that we are interested in searching, and the model will randomly select a subset and return the one that produces the best results.</p><p>Still, let’s manually select a few parameters we want to evaluate on and then use randomized search:</p><ul><li>criterion</li><li>split strategy</li><li>max depth</li><li>min_samples_split</li><li>max features</li></ul><pre>from sklearn.model_selection import RandomizedSearchCV<br><br>dt = DecisionTreeClassifier(random_state = 42)<br><br>features = {&#39;criterion&#39;: [&#39;gini&#39;,&#39;entropy&#39;],<br>            &#39;splitter&#39;: [&#39;best&#39;,&#39;random&#39;],<br>           &#39;max_depth&#39;: [2,5,10,20,40,None],<br>           &#39;min_samples_split&#39;: [2,5,10,15],<br>           &#39;max_features&#39;: [&#39;auto&#39;,&#39;sqrt&#39;,&#39;log2&#39;,None]}<br><br>rs_dt = RandomizedSearchCV(estimator = dt, param_distributions =features, <br>                           n_iter =100, cv = 3, <br>                           random_state = 42, scoring =&#39;f1&#39;)<br><br>rs_dt.fit(X_train,y_train)</pre><p><strong>Advantages</strong>:</p><ul><li>Efficient in terms of time and computational resources since it explores a smaller subset of the hyperparameter space compared to exhaustive methods.</li><li>Can quickly discover good hyperparameter configurations, especially when the search space is large, and the number of iterations is limited.</li><li>Helps avoid getting stuck in local optima by introducing randomness.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>May miss the best hyperparameter combination if it occurs outside the sampled subset.</li><li>The randomness can lead to inconsistent results across different runs.</li><li>Limited control over the search process compared to exhaustive methods.</li></ul><blockquote><strong>When to use</strong>: Randomized Parameter Tuning is useful when the search space is large, computational resources are limited, and a quick exploration of hyperparameter configurations is desired.</blockquote><h4>GridsearchCV (Exhaustive Parameter Tuning)</h4><p><strong>How it works</strong>: GridsearchCV exhaustively searches all possible combinations of specified hyperparameters. It evaluates the performance of the model for each combination using cross-validation and selects the hyperparameter combination with the best performance.</p><p>This time let’s do an exhaustive search of a smaller number of features and see if we can improve our results even more.</p><pre>from sklearn.model_selection import GridSearchCV<br><br><br>features_gs = {&#39;criterion&#39;: [&#39;entropy&#39;],<br>            &#39;splitter&#39;: [&#39;random&#39;],<br>           &#39;max_depth&#39;: np.arange(30,50,1), <br>           &#39;min_samples_split&#39;: [2,3,4,5,6,7,8,9],<br>           &#39;max_features&#39;: [None]}<br><br>gs_dt = GridSearchCV(estimator = dt, param_grid =features_gs, <br>                     cv = 3, scoring =&#39;f1&#39;) <br>#we don&#39;t need random state because there isn&#39;t randomization like before<br>gs_dt.fit(X_train,y_train)</pre><p><strong>Advantages</strong>:</p><ul><li>Guarantees finding the best hyperparameter combination within the search space.</li><li>Provides a comprehensive exploration of the hyperparameter space.</li><li>Allows fine-grained control over the search process by specifying the exact values or ranges to explore.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Can be computationally expensive and time-consuming, especially for large search spaces and many hyperparameters.</li><li>Prone to overfitting the hyperparameter search to the specific dataset, leading to poor generalization.</li><li>Limited scalability when the search space is very large.</li></ul><blockquote><strong>When to use</strong>: GridsearchCV is suitable when the search space is small or moderate, computational resources are sufficient, and a thorough exploration of hyperparameter configurations is desired.</blockquote><h4>Bayesian Optimization</h4><p>I wonder if we can do better than the funnel approach that we took with random search and GridSearch. What if we used a slightly smarter algorithm to help evaluate our features. Maybe we could explore all of the variables from the previous examples and see if our model missed something. This is where Bayesian Optimization comes in. This is an iterative process where our model improves its understandings of the feature inputs as it goes.</p><p><strong>How it works</strong>: Bayesian Optimization is an iterative method that builds a probabilistic model of the objective function based on the observed hyperparameter-performance pairs. It uses this model to guide the search towards promising regions of the hyperparameter space and explores it efficiently.</p><pre>from skopt import BayesSearchCV<br>from skopt.space import Real, Categorical, Integer<br>from sklearn.model_selection import StratifiedKFold</pre><pre># Choose cross validation method <br>cv = StratifiedKFold(n_splits = 3)<br><br><br>bs_lr = BayesSearchCV(<br>    dt,<br>    {&#39;criterion&#39;: Categorical([&#39;gini&#39;,&#39;entropy&#39;]),<br>            &#39;splitter&#39;: Categorical([&#39;best&#39;,&#39;random&#39;]),<br>           &#39;max_depth&#39;: Integer(10,50),<br>           &#39;min_samples_split&#39;: Integer(2,15),<br>           &#39;max_features&#39;: Categorical([&#39;auto&#39;,&#39;sqrt&#39;,&#39;log2&#39;,None])},<br>    random_state=42,<br>    n_iter= 100,<br>    cv= cv,<br>    scoring =&#39;f1&#39;)<br> <br>bs_lr.fit(X_train,y_train.values.ravel())</pre><p><strong>Advantages</strong>:</p><ul><li>Efficiently explores the hyperparameter space by leveraging the knowledge gained from previous evaluations.</li><li>Adapts the search process dynamically based on the observed performance, focusing on promising regions.</li><li>Handles non-linear and non-convex objective functions effectively.</li><li>Requires fewer evaluations compared to exhaustive methods, saving computational resources.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>The initial iterations may not provide accurate information, leading to suboptimal performance.</li><li>Choosing an appropriate surrogate model and acquisition function can be challenging.</li><li>Implementation and tuning of Bayesian Optimization can be more complex than other methods.</li></ul><blockquote><strong>When to use</strong>: Bayesian Optimization is recommended when the search space is large, the number of iterations is limited, and efficient exploration of the hyperparameter space is crucial. It is particularly useful when the objective function is expensive to evaluate, such as in deep learning or complex simulations.</blockquote><p>At the end of today’s topic, I hope you found it useful to you and don’t forget to practice it as with the different situations and problems the information you gained will enhance your memory.</p><p><strong>Resources</strong>:</p><p><a href="http://Hyperparameter Tuning - GridSearchCV and RandomizedSearchCV">Hyperparameter Tuning — GridSearchCV and RandomizedSearchCV</a></p><p><a href="https://machinelearningmastery.com/difference-between-a-parameter-and-a-hyperparameter/">What is the Difference Between a Parameter and a Hyperparameter?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=098a16dc0c60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Support Vector Machines (SVMs)]]></title>
            <link>https://medium.com/@abdullah.hosam13/a-comprehensive-guide-to-support-vector-machines-svms-e8d5584434eb?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8d5584434eb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 14:53:04 GMT</pubDate>
            <atom:updated>2024-03-15T14:53:04.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlvYMP7NS2GcD5eY3JB7YA.png" /></figure><p>When I studied SVM for the first time I didn’t get a word from what I’ve read, so it’s totally normal to not get the idea of it in the beginning and with the continuous study of it at the end you will get the full picture. Also, important note that this article doesn’t contain a practical it’s more towards the theoretical part but at the end it will give you complete overview.</p><p>Support Vector Machine (SVM) is indeed a powerful supervised machine learning algorithm that finds applications in both classification and regression tasks.</p><blockquote>Table of contents</blockquote><blockquote>Fundamentals of SVMs</blockquote><blockquote>SVM Classification</blockquote><blockquote>SVM Regression</blockquote><blockquote>Linear SVM</blockquote><blockquote>Non-linear SVM</blockquote><blockquote>Basic Concepts</blockquote><blockquote>Kernel Functions</blockquote><h4>o. Fundamentals of SVMs</h4><blockquote>The underlying principle of Support Vector Machines (SVMs) involves finding an optimal hyperplane that separates data points into different classes or predicts a continuous target variable. The hyperplane is determined by maximizing the margin, which is the distance between the hyperplane and the nearest data points from each class. By maximizing the margin, SVMs aim to achieve better generalization and improve the algorithm’s ability to classify new, unseen data accurately.</blockquote><p>Certainly! Support Vector Machine (SVM) is indeed a powerful supervised machine learning algorithm that finds applications in both classification and regression tasks. Let’s delve into the details.</p><p>SVMs offer several key 🚀advantages that make them popular in machine learning🤖:</p><ul><li>Ability to handle high-dimensional data: SVMs perform well even when the number of features is much greater than the number of samples, making them suitable for complex datasets.</li><li>Handling non-linear decision boundaries: SVMs can efficiently handle non-linear relationships through the use of kernel functions. These functions transform the data into a higher-dimensional space, where a linear hyperplane can separate the classes.</li><li>Robustness against overfitting: SVMs have a regularizing effect due to the margin maximization, making them less prone to overfitting. They focus on correctly classifying the most challenging data points, known as support vectors, rather than considering the entire dataset.</li></ul><blockquote>Disadvantages</blockquote><ul><li>Sensitive to overfitting, regularization is crucial.</li><li>Choosing a “good” kernel function can be difficult.</li><li>Computationally expensive for big data due to high training complexity.</li><li>Performs poorly if the data is noisy (target classes overlap).</li></ul><h4><strong>Classification </strong>with SVM</h4><ul><li>SVMs are adept at <strong>linear and nonlinear classification</strong>. They work by identifying an optimal hyperplane in a high-dimensional space that effectively separates data points belonging to different classes.</li><li>The primary objective of SVM is to maximize the margin between the closest points of different classes. This margin represents the distance from the hyperplane to the nearest data points on each side.</li><li>SVMs are robust to outliers and can handle high-dimensional data efficiently.</li></ul><p><strong>Applications of SVM include.</strong></p><ul><li><strong>Text classification</strong>: For tasks like spam detection or sentiment analysis.</li><li><strong>Image classification</strong>: Identifying objects, faces, or patterns.</li><li><strong>Handwriting identification</strong>: Recognizing handwritten characters.</li><li><strong>Gene expression analysis</strong>: Identifying genes associated with specific conditions.</li><li><strong>Anomaly detection</strong>: Detecting unusual patterns in data.</li></ul><h4><strong>Regression </strong>with SVM</h4><p>In SVM regression, the goal is to find a hyperplane that captures as many data points as possible within a specified margin. Rather than aiming for a strict separation, SVM regression allows data points to fall within a certain margin, defined by a parameter called epsilon. The objective is to minimize the errors (differences between the predicted and actual values) while maximizing the margin. SVM regression can handle both linear and non-linear relationships by using appropriate kernel functions.</p><ul><li>While SVMs are primarily known for classification, they can also be used for regression tasks.</li><li>In regression, SVM aims to find a hyperplane that best fits the data points, minimizing the error between predicted and actual values.</li><li>SVM regression works by finding a hyperplane that maximizes the margin while allowing some data points to lie within a specified tolerance (known as the “epsilon-insensitive tube”).</li><li>The choice of kernel (linear, polynomial, or radial basis function) influences the flexibility of the regression model.</li></ul><h4>epsilon</h4><p>The <strong>epsilon-insensitive</strong> loss function is a key concept in SVM regression. It defines a margin of tolerance (epsilon) within which errors are considered insignificant. Data points falling within this margin do not contribute to the loss function. Only data points outside the margin or with errors greater than epsilon are penalized. The choice of epsilon affects the trade-off between model complexity and accuracy. Smaller epsilon values result in a more complex model that fits the data closely, whereas larger epsilon values lead to a simpler model with potentially less accuracy.</p><p>SVMs are versatile and effective tools for solving a wide range of problems, from classifying text to predicting numerical values. Their ability to handle complex data distributions and outliers makes them a valuable addition to the machine learning toolbox. 🚀🤖</p><p>SVM classifiers can be broadly classified into two types:</p><ul><li><strong>Linear SVMs</strong>: These classifiers use a linear hyperplane to separate the classes. They work well when the data is linearly separable, and the classes can be distinguished by a straight line or plane.</li><li><strong>Non-linear SVMs</strong> using kernel functions: These classifiers employ kernel functions to transform the data into a higher-dimensional feature space, where a linear hyperplane can separate the classes. This technique allows SVMs to handle complex, non-linear decision boundaries efficiently. Popular kernel functions include linear, polynomial, Gaussian (RBF), and sigmoid kernels.</li></ul><h4>Linear SVM</h4><ul><li><strong>Linear SVM</strong> is adept at dealing with data that can be separated by a straight line (or hyperplane) in the feature space.</li><li>When the data points are <strong>linearly separable</strong>, SVM aims to find the optimal hyperplane that maximizes the margin between different classes.</li><li>The margin represents the distance between the closest points of different classes. The goal is to maximize this margin while ensuring correct classification.</li><li>Linear SVM works well for tasks like <strong>text classification</strong>, <strong>image classification</strong>, <strong>spam detection</strong>, and more.</li><li>Imagine a scenario where we have two independent variables, x1 and x2, and our goal is to classify data points into blue circles or red circles. Linear SVM can find the best line (hyperplane) to segregate these data points.</li></ul><h4>Nonlinear SVM</h4><ul><li><strong>Nonlinear SVM</strong> extends its capabilities beyond linear separability.</li><li>In cases where data cannot be separated by a straight line, SVM employs <strong>kernel functions</strong> to transform the feature space into a higher-dimensional space.</li><li>These kernel functions allow SVM to handle <strong>nonlinear relationships</strong> between features.</li><li>Examples of kernel functions include the <strong>polynomial kernel</strong>, <strong>radial basis function (RBF) kernel</strong>, and <strong>sigmoid kernel</strong>.</li><li>By using these kernels, SVM can find an optimal hyperplane or decision boundary that maximizes the margin even when the data is not linearly separable.</li><li>Nonlinear SVM is robust to outliers and can handle complex data distributions.</li></ul><h4>Basic Concept</h4><p>First thing first I’m going to introduce some terminologies that will help us in the journey to learn SVM.</p><p><strong>Support vectors </strong>are the data points closest to the decision boundary determined by the SVM. These points play a crucial role in defining the optimal hyperplane. Support vectors lie on or within the margin, and their positions influence the positioning and orientation of the hyperplane. SVMs only consider support vectors when making predictions, disregarding the other data points. This characteristic makes SVMs memory-efficient and effective even in high-dimensional spaces.</p><p><strong>Margin</strong> is the shortest distance between the observation and the threshold.</p><p><strong>Soft margin </strong>is a type of SVM that <strong>tolerates a few misclassified data points</strong>. It tries to balance the trade-off between finding a line that maximizes the margin and minimizes the misclassification when we allow misclassification the distance between the observations and the threshold.</p><p><strong>Maximal margin classifier </strong>is a hyperplane defined in the rare case where two classes are linearly separable. The maximal margin hyperplane is the hyperplane for which the margin is maximized. We can classify a test observation based on which side of the maximal margin hyperplane it lies on, and this is known as the maximal margin classifier. It’s much sensitive to the outliers in the training data and makes them pretty lame.</p><blockquote>We use <strong><em>cross-validation</em></strong> to determine how many misclassifications and observations to allow inside of the soft margin to get the best classification.</blockquote><blockquote>When we use a soft margin to determine the location of threshold then we’re using soft margin classifier aka a<strong> Support vector classifier</strong> to classify observations <br>the name support vector classifier comes from the fact that the observations on the edge and within the soft margin are called support vector.</blockquote><blockquote>The intuition behind SVM is that if the classifier performs well on the <strong>most challenging comparisons</strong> (i.e., support vectors close to each other), it will perform even better on <strong>easier comparisons</strong> (support vectors far apart).</blockquote><blockquote>Widening the margin ensures robustness and better generalization.</blockquote><blockquote><strong>Finding the biggest margin, is the same thing as finding the optimal hyperplane.</strong></blockquote><h4>Kernel functions</h4><p>Kernel functions are fundamental to SVMs as they transform the input data from the original feature space into a higher-dimensional space, where linear separation is possible. Kernel functions perform this transformation efficiently without explicitly calculating the coordinates in the higher-dimensional space. Popular kernel functions include:</p><ul><li><strong>Linear kernel</strong>: It represents a linear transformation and is suitable for linearly separable data.</li><li><strong>Polynomial kernel</strong>: It maps the data into a polynomial feature space and can capture relationships of higher degree.</li><li><strong>Gaussian (RBF) kernel</strong>: It transforms the data into an infinite-dimensional space using a Gaussian distribution. It is effective in capturing complex, non-linear relationships.</li><li><strong>Sigmoid kernel</strong>: It maps the data into a feature space using a sigmoid function. It is commonly used in binary classification problems.</li></ul><p>Let’s define how these concepts we discussed work with each other:</p><ul><li>The fundamentals of SVMs lay the foundation for understanding the goals and principles of SVM algorithms.</li><li>SVM classification builds upon the fundamentals and introduces the concept of linear SVMs, where a linear hyperplane separates classes.</li><li>Non-linear SVM classification extends SVMs by incorporating kernel functions, enabling the handling of non-linear decision boundaries.</li><li>SVM regression utilizes the same principles as SVM classification but focuses on predicting continuous target variables instead of class labels.</li><li>Kernel functions play a crucial role in both classification and regression tasks, allowing SVMs to model complex relationships in the data.</li><li>The epsilon-insensitive loss function in SVM regression helps strike a balance between model complexity and accuracy.</li></ul><h4>Additional Resources:</h4><p><a href="https://youtu.be/efR1C6CvhmE?si=Ixzp4R4kA7Mzvv4r">Support Vector Machines Part 1 (of 3): Main Ideas!!!</a></p><p><a href="https://youtu.be/Toet3EiSFcM?si=LrNk8XTp9NxjC-JC">Support Vector Machines Part 2: The Polynomial Kernel (Part 2 of 3)</a></p><p><a href="https://youtu.be/Qc5IyLW_hns?si=JjdFElHJv9EJ_Pg3">Support Vector Machines Part 3: The Radial (RBF) Kernel (Part 3 of 3)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8d5584434eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about linear regression]]></title>
            <link>https://medium.com/@abdullah.hosam13/all-about-linear-regression-97f3eecd8e56?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/97f3eecd8e56</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-ana-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 13:53:49 GMT</pubDate>
            <atom:updated>2024-03-01T13:53:49.362Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I’m trying to walk you through the underlying concepts behind linear regression and how interpret them. This will be the first step and my second step are when I publish my GitHub repo about linear regression as I love the practical more than the theoretical one it’s important but no doubt that practical coding is more fun and informative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zC6AiU-ga5Un5H0Q4nNAug.png" /></figure><h3>1-Introduction to Linear Regression.</h3><ul><li>Linear regression is a family of algorithms used in <strong>supervised machine learning</strong> tasks.</li><li>It’s employed when the target variable is <strong>numerical and continuous</strong> (e.g., predicting house prices based on features like square meters, location, etc.).</li><li>Linear regression aims to find a <strong>straight line</strong> that best fits the data points.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*ORlWdy67Fb2YgLqDXh6bGQ.png" /></figure><h4><strong>First what is linear regression stands for?</strong></h4><p>Linear regression, in statistics, is a process for determining a line that best represents the general trend of a data set.</p><p>The simplest form of linear regression involves two variables: <em>y</em> being the dependent variable and <em>x</em> being the independent variable. The equation developed is of the form <em>y</em> = <em>mx</em> + <em>b</em>, where <em>m</em> is the slope of the regression line (or the regression coefficient), and <em>b</em> is where the line intersects the <em>y</em>-axis.</p><p>The equation for the regression line can be found using the least squares method, where <em>m</em> = (<em>n</em>(Σ<em>xy</em>) − Σ<em>x</em>Σ<em>y</em>)/(<em>n</em>Σ<em>x</em>2 − (Σ<em>x</em>)2) and <em>b</em> = (Σ<em>y</em> − <em>m</em>Σ<em>x</em>)/<em>n</em>.</p><p>The symbol Σ indicates a summation of all values, and <em>n</em> is the number of data points.</p><p>When a linear correlation exists in the data, a regression line can be found that will represent the line of best fit for the data. This equation can then be used to predict values not collected in the original data set.</p><p>Ordinary Least Squares (OLS) is a statistical method used in linear regression.</p><ul><li>OLS is an optimization strategy used in linear regression.</li><li>Its goal is to find a straight line (or linear function) that closely approximates the relationship between the independent variable(s) and the dependent variable.</li><li>The principle of least squares is applied: minimize the sum of the squares of the differences between the observed dependent variable values and the predicted values from the linear function.</li><li>In other words, OLS finds the line that minimizes the overall error (residuals) between the actual data points and the predicted values.</li></ul><p>Mathematical Representation:</p><ul><li>y=α+βx+εi​</li><li>(y) represents the dependent variable (e.g., house price).</li><li>(x) represents the independent variable (e.g., square meters).</li><li>(alpha) and (beta) are the parameters of the regression (intercept and slope).</li><li>(epsilon) represents the error term.</li></ul><p><strong>Advantages of OLS</strong>:</p><p>OLS provides <strong>unbiased real value estimates</strong> for the intercept ((\alpha)) and slope ((\beta)).</p><p>It’s widely used because of its simplicity and effectiveness in linear regression modeling.</p><p>Remember, OLS helps us find that straight line that best fits our data, making it a fundamental technique in statistics and machine learning! 📈</p><h4><strong>What is the importance of linear regression in data analysis field?</strong></h4><p>Linear regression is used in data analysis to:</p><ul><li>Predict future outcomes or identify missing data.</li><li>Correct or spot likely errors in a dataset, identifying or estimating the correct values.</li><li>Predict values not collected in the original data set.</li><li>Help organizations use large amounts of raw data to better manage reality.</li><li>Define the relationship between two variables by estimating the coefficients of the linear equation.</li></ul><h4>Assumptions of Linear Regression.</h4><p><strong>Linear regression</strong> is an analysis that assesses whether one or more predictor variables explain the dependent (criterion) variable. The regression has five key assumptions:</p><blockquote><strong>Linear relationship.</strong></blockquote><p>linear regression needs the relationship between the independent and dependent variables to be linear. It is also important to check for outliers since linear regression is sensitive to outlier effects. The linearity assumption can best be tested with scatter plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3AfDyTqzddUt43LvYqf-Q.png" /></figure><blockquote><strong>Multivariate normality.</strong></blockquote><p>the linear regression analysis requires all variables to be multivariate normal. This assumption can best be checked with a histogram or a Q-Q-Plot. Normality can be checked with a goodness of fit test, e.g., the Kolmogorov-Smirnov test. When the data is not normally distributed a non-linear transformation (e.g., log-transformation) might fix this issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhVj7JglotIL-uMWXoUfkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tz39SvVhqn_yPCe50t3SsQ.png" /></figure><blockquote><strong>No or little multicollinearity.</strong></blockquote><p>linear regression assumes that there is little or no multicollinearity in the data. Multicollinearity occurs when the independent variables are too highly correlated with each other.</p><p>Multicollinearity may be tested with three central criteria:</p><p>1) Correlation matrix — when computing the matrix of Pearson’s Bivariate Correlation among all independent variables the correlation coefficients need to be smaller than 1.</p><p>2) Tolerance — the tolerance measures the influence of one independent variable on all other independent variables; the tolerance is calculated with an initial linear regression analysis. Tolerance is defined as T = 1 — R² for these first step regression analysis. With T &lt; 0.1 there might be multicollinearity in the data and with T &lt; 0.01 there certainly is.</p><p>3) Variance Inflation Factor (VIF) — the variance inflation factor of the linear regression is defined as VIF = 1/T. With VIF &gt; 5 there is an indication that multicollinearity may be present; with VIF &gt; 10 there is certainly multicollinearity among the variables.</p><p>If multicollinearity is found in the data, centering the data (that is deducting the mean of the variable from each score) might help to solve the problem. However, the simplest way to address the problem is to remove independent variables with high VIF values.</p><p>4) Condition Index — the condition index is calculated using a factor analysis on the independent variables. Values of 10–30 indicate a mediocre multicollinearity in the linear regression variables, values &gt; 30 indicate strong multicollinearity.</p><p>If multicollinearity is found in the data centering the data, that is deducting the mean score might help to solve the problem. Other alternatives to tackle the problems is conducting a factor analysis and rotating the factors to insure independence of the factors in the linear regression analysis.</p><blockquote><strong>No autocorrelation.</strong></blockquote><p>linear regression analysis requires that there is little or no autocorrelation in the data. Autocorrelation occurs when the residuals are not independent from each other. In other words when the value of y(x+1) is not independent from the value of y(x).</p><p>While a scatterplot allows you to check for autocorrelations, you can test the linear regression model for autocorrelation with the Durbin-Watson test. Durbin-Watson’s d tests the null hypothesis that the residuals are not linearly auto-correlated. While d can assume values between 0 and 4, values around 2 indicate no autocorrelation. As a rule of thumb values of 1.5 &lt; d &lt; 2.5 show that there is no autocorrelation in the data. However, the Durbin-Watson test only analyses linear autocorrelation and only between direct neighbors, which are first order effects.</p><blockquote><strong>Homoscedasticity.</strong></blockquote><p>The last assumption of the linear regression analysis is homoscedasticity(heteroscedastic). The scatter plot is good way to check whether the data are homoscedastic (meaning the residuals are equal across the regression line).</p><p>The Goldfeld-Quandt Test can also be used to test for heteroscedasticity. The test splits the data into two groups and tests to see if the variances of the residuals are similar across the groups. If homoscedasticity is present, a non-linear correction might fix the problem.</p><h3>2-Simple Linear Regression</h3><p><strong>Simple linear regression</strong> is used to estimate the relationship between<strong> two quantitative variables</strong>.</p><p>You can use simple linear regression when you want to know:</p><ol><li>How strong the relationship is between two variables (e.g., the relationship between rainfall and soil erosion).</li><li>The value of the dependent variable at a certain value of the independent variable (e.g., the amount of soil erosion at a certain level of rainfall).</li></ol><h4>Simple linear regression formula</h4><p>The formula for a simple linear regression is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*TETOCRIUSDZnCJUhlG6GlQ.png" /></figure><ul><li><strong>y</strong> is the predicted value of the dependent variable (<strong>y</strong>) for any given value of the independent variable (<strong>x</strong>).</li><li><strong>B0</strong> is the <strong>intercept</strong> (<strong>Bias)</strong>, the predicted value of <strong>y</strong> when the <strong>x</strong> is 0.</li><li><strong>B1</strong> is the regression <strong>coefficient </strong>(<strong>Slope</strong>)— how much we expect <strong>y</strong> to change as <strong>x</strong> increases.</li><li><strong>x</strong> is the independent variable (the variable we expect is influencing <strong>y</strong>).</li><li><strong>e</strong> is the <strong>error</strong> of the estimate, or how much variation there is in our estimate of the regression coefficient.</li></ul><p>Linear regression finds the line of best fit line through your data by searching for the regression coefficient (B1) that minimizes the total error (e) of the model.</p><h3>3-Multiple Linear Regression</h3><p><strong>Multiple linear regression</strong> is used to estimate the relationship between <strong>two or more independent variables </strong>and<strong> one dependent variable</strong>. You can use multiple linear regression when you want to know:</p><ol><li>How strong the relationship is between two or more independent variables and one dependent variable (e.g. how rainfall, temperature, and amount of fertilizer added affect crop growth).</li><li>The value of the dependent variable at a certain value of the independent variables (e.g. the expected yield of a crop at certain levels of rainfall, temperature, and fertilizer addition).</li></ol><h4>The formula for a multiple linear regression is:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*mWTH2fEkwOJQlsVx6kXbAA.png" /></figure><ul><li>y = the predicted value of the dependent variable</li><li>B0 = the y-intercept (value of y when all other parameters are set to 0)</li><li>B1, X1= the regression coefficient (B1) of the first independent variable (X1) (a.k.a. the effect that increasing the value of the independent variable has on the predicted y value)</li><li>… = do the same for however many independent variables you are testing</li><li>Bn, Xn= the regression coefficient of the last independent variable</li><li>e = model error (a.k.a. how much variation there is in our estimate of</li></ul><p>To find the best-fit line for each independent variable, multiple linear regression calculates three things:</p><ul><li>The <strong>regression coefficients</strong> that lead to the smallest overall model error.</li><li>The<em> </em><strong><em>t-</em>statistic</strong> of the overall model.</li><li>The associated <strong><em>p </em>value</strong> (how likely it is that the <em>t</em> statistic would have occurred by chance if the null hypothesis of no relationship between the independent and dependent variables was true).</li></ul><p>It then calculates the <em>t </em>statistic and <em>p </em>value for each regression coefficient in the model.</p><h3>4-Model Evaluation and Interpretation</h3><p>There are three error metrics that are commonly used for evaluating and reporting the performance of a regression model.</p><blockquote><strong>Mean Squared Error (MSE)</strong></blockquote><p>Mean Squared Error, or MSE for short, is a popular error metric for regression problems.</p><p>It is also an important loss function for algorithms fit or optimized using the least squares framing of a regression problem. Here “<em>least squares</em>” refers to minimizing the mean squared error between predictions and expected values.</p><p>The MSE is calculated as the mean or average of the squared differences between predicted and expected target values in a dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGqkoGqQZKoXXhpkQ28yGQ.jpeg" /></figure><p>Where <em>y_i</em> is the i’th expected value in the dataset and <em>yhat_i</em> is the i’th predicted value. The difference between these two values is squared, which has the effect of removing the sign, resulting in a positive error value.</p><p>The squaring also has the effect of inflating or magnifying large errors. That is, the larger the difference between the predicted and expected values, the larger the resulting squared positive error. This has the effect of “<em>punishing</em>” models more for larger errors when MSE is used as a loss function. It also has the effect of “<em>punishing</em>” models by inflating the average error score when used as a metric.</p><p>We can create a plot to get a feeling for how the change in prediction error impacts the squared error.</p><blockquote><strong>Root Mean Squared Error (RMSE).</strong></blockquote><p>The Root Mean Squared Error, or RMSE, is an extension of the mean squared error.</p><p>Importantly, the square root of the error is calculated, which means that the units of the RMSE are the same as the original units of the target value that is being predicted.</p><p>For example, if your target variable has the units “<em>dollars</em>,” then the RMSE error score will also have the unit “<em>dollars</em>” and not “<em>squared dollars</em>” like the MSE.</p><p>As such, it may be common to use MSE loss to train a regression predictive model, and to use RMSE to evaluate and report its performance.</p><p>The RMSE can be calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*pQR9id8CtnsdKljm8KODuw.png" /></figure><p>Where <em>y_i</em> is the i’th expected value in the dataset, <em>yhat_i</em> is the i’th predicted value.</p><p>We can restate the RMSE in terms of the MSE as:</p><ul><li>RMSE = sqrt (MSE)</li></ul><blockquote><strong>Mean Absolute Error (MAE)</strong></blockquote><p><a href="https://en.wikipedia.org/wiki/Mean_absolute_error">Mean Absolute Error</a>, or MAE, is a popular metric because, like RMSE, the units of the error score match the units of the target value that is being predicted.</p><p>Unlike the RMSE, the changes in MAE are linear and therefore intuitive.</p><p>That is, MSE and RMSE punish larger errors more than smaller errors, inflating or magnifying the mean error score. This is due to the square of the error value. The MAE does not give more or less weight to different types of errors and instead the scores increase linearly with increases in error.</p><p>As its name suggests, the MAE score is calculated as the average of the absolute error values. Absolute or <em>abs()</em> is a mathematical function that simply makes a number positive. Therefore, the difference between an expected and predicted value may be positive or negative and is forced to be positive when calculating the MAE.</p><p>The MAE can be calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*lF0sPg4yatOlAFrLT8M6-w.jpeg" /></figure><p>Where <em>y_i</em> is the i’th expected value in the dataset, <em>yhat_i</em> is the i’th predicted value and <em>abs()</em> is the absolute function.</p><p>There are many other metrics for regression, although these are the most commonly used.</p><p>This’s the end of our article for today about Linear Regression algorithms and soon I’ll publish a GitHub-Repo covering more topics like how to handle missing values and dealing with nonlinear relationships in a project case. Hope you found it useful explanation and have a great data science journey.</p><p><strong>Additional Resources</strong>:</p><p><a href="https://www.youtube.com/watch?v=PaFPbb66DxQ">The Main Ideas of Fitting a Line to Data (The Main Ideas of Least Squares and Linear Regression.)</a></p><p><a href="https://www.youtube.com/watch?v=nk2CQITm_eo&amp;t=192s">Linear Regression, Clearly Explained!!!</a></p><blockquote>Clearly, I love StatQuest and josh starmer songs, yes Double Baaaaaaaaaaam :)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97f3eecd8e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Statistics for Data Scientists Ch3(Statistical Experiments and Significance Testing)]]></title>
            <link>https://medium.com/@abdullah.hosam13/practical-statistics-for-data-scientists-ch3-statistical-experiments-and-significance-testing-14ec7cd7fe0c?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ec7cd7fe0c</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 19:41:22 GMT</pubDate>
            <atom:updated>2024-01-04T19:41:22.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iXCeGiR4C_eMEROh" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this chapter the authors are giving us a complete overview of what’s an a/b testing, how to perform a hypothesis test, different statistical testing, and different cases where we can perform an a/b test.</p><h3><strong>Chapter Contents</strong></h3><ol><li><em>A/B Testing</em></li><li><em>Hypothesis Tests</em></li><li><em>Resampling</em></li><li><em>Statistical Significance and p-values</em></li><li><em>t-Tests</em></li><li><em>ANOVA</em></li><li><em>Chi-Square test</em></li><li><em>Multi-Arm Bandit Algorithm</em></li></ol><h3>A/B Testing</h3><h4><strong>what’s an a/b test?</strong></h4><p>It is a statistical hypothesis testing process whereby a hypothesis is made about the relationship between two data sets and those data sets are then compared against each other to determine if there is a statistically significant relationship or not. A/B tests allow you to compare 2 versions of something to learn which is more effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wfxy-BaXMcMc7m4q" /><figcaption>Photo by <a href="https://unsplash.com/@joelfilip?utm_source=medium&amp;utm_medium=referral">Joel Filipe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Why having a control group?</strong></h4><p>Without a control group, there is no assurance that “all other things are equal” and that any difference is really due to the treatment (or to chance). When you have a control group, it is subject to the same conditions (except for the treatment of interest) as the treatment group. If you simply make a comparison to “baseline” or prior experience, other factors, besides the treatment, might differ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DMMB-RC4t89AC9mB" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Hypothesis Tests</h3><p>Hypothesis testing is a process that involves the following steps1:</p><ul><li>Observe the situation, define a problem, and ask a question.</li><li>Formulate a hypothesis (a proposed solution or explanation)</li><li>Test the hypothesis with experiments.</li><li>Collect and analyze the results.</li><li>Interpret the results and keep testing until you’re satisfied with the solution.</li></ul><p>A/B testing is a version of a two-sample hypothesis testing for a randomized controlled experiment with two groups, control and treatment.</p><p>Null hypothesis is a <strong>statement that there is no relationship or difference between two sets of data or variables</strong>. It is often denoted by H0 and is used in scientific research and statistical testing. The null hypothesis is the default position that can be rejected or disproved in favor of an alternative hypothesis, which is the claim of interest. The null hypothesis assumes that any observed effect is due to chance alone and not due to a systematic cause.</p><p>Alternative hypothesis is <strong>one of the proposed propositions in the hypothesis test</strong>. In general, the goal of hypothesis test is to demonstrate that in the given condition, there is sufficient evidence supporting the credibility of alternative hypothesis instead of the exclusive proposition in the test (null hypothesis). It is usually consistent with the research hypothesis because it is constructed from literature review, previous studies, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rPjdAdiK8EZ8dkhB" /><figcaption>Photo by <a href="https://unsplash.com/@bdchu614?utm_source=medium&amp;utm_medium=referral">Brendan Church</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>One-way Versus Two-way Hypothesis tests?</strong></h4><p>let’s discuss the difference between one-way and two-way hypothesis tests:</p><ol><li>Null Hypothesis (H₀): It represents the default or the “no effect” assumption. It assumes that there is no significant difference or relationship between variables.</li><li>Alternative Hypothesis (H₁): It represents the research hypothesis or the claim you are trying to investigate. It assumes that there is a significant difference or relationship between variables.</li></ol><h4>One-Way Hypothesis Test</h4><ul><li>In a one-way test, the alternative hypothesis (H₁) specifies the direction of the effect or relationship.</li><li>The test is focused on determining whether the observed sample data significantly supports the claim made in the alternative hypothesis in one specific direction.</li><li>For example, if you are testing whether a new drug improves patient recovery time, the alternative hypothesis for a one-way test could be “The new drug reduces recovery time compared to the standard treatment.”</li><li>The statistical significance is evaluated in only one direction (e.g., the new drug is better than the standard treatment).</li></ul><h4>Two-Way Hypothesis Test</h4><ul><li>In a two-way test, the alternative hypothesis (H₁) does not specify the direction of the effect or relationship.</li><li>The test is focused on determining whether the observed sample data significantly supports the claim made in the alternative hypothesis in either direction.</li><li>For example, if you are testing whether a new teaching method improves test scores, the alternative hypothesis for a two-way test could be “The new teaching method has a different effect on test scores compared to the traditional teaching method.”</li><li>The statistical significance is evaluated in both directions (e.g., the new teaching method has a different effect, either higher or lower, on test scores compared to the traditional teaching method).</li></ul><p>The choice between a one-way or two-way hypothesis test depends on the <strong>research question</strong> and the <strong>specific hypotheses</strong> you want to test. If you have a specific direction in mind and want to test the effect in that particular direction, a <strong>one-way test </strong>is appropriate. On the other hand, if you want to test whether there is any significant difference or relationship without specifying a direction, a <strong>two-way test</strong> is more suitable.</p><p>Remember, the choice between one-way and two-way tests should be made based on the research question and the specific hypotheses being tested.</p><p>For more research about it. I recommend watching this video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFsa-5_XdIMs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFsa-5_XdIMs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFsa-5_XdIMs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/743d1043cae5cc9b54dcb1bb51fd321f/href">https://medium.com/media/743d1043cae5cc9b54dcb1bb51fd321f/href</a></iframe><h3>Resampling</h3><p>In statistics, <strong>resampling</strong> is the creation of new samples based on one observed sample. Resampling methods are:</p><ol><li>Permutation tests (also re-randomization tests)</li><li>Bootstrapping (we discussed it in the previous chapter)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ByoPUuzCvtnvNcLG" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Permutation tests</h4><p>Permutation tests rely on resampling the original data assuming the null hypothesis. Based on the resampled data it can be concluded how likely the original data is to occur under the null hypothesis.</p><p>To perform a permutation test, you need to follow these steps:</p><ol><li>Combine the results from the different groups into a single data set.</li><li>Shuffle the combined data and then randomly draw (without replacement) a resample of the same size as group A</li><li>From the remaining data, randomly draw (without replacement) a resample of the same size as group B.</li><li>Do the same for groups C, D and so on. You have now collected one set of resamples that mirror the sizes of the original samples.</li><li>Whatever the statistic or estimate was calculated for the original samples, calculate it now for the resamples, and record, this constitutes one permutation.</li><li>Repeat the previous steps R times to yield a permutation distribution of the test statistic.</li><li>Now go back to the observed differences between groups and compare it to the set of permuted differences, if the observed differences lie well within the set of permuted differences, then we have not proven anything — the observed difference is within the range of what chance might produce. If the observed difference lies outside most of the permutation distribution, then we conclude that chance is not responsible in technical terms the difference is statistically significant.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrJ3AZCQuiLw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrJ3AZCQuiLw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrJ3AZCQuiLw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/33bbd8581b58f7f01d0ecff478f3acfa/href">https://medium.com/media/33bbd8581b58f7f01d0ecff478f3acfa/href</a></iframe><h3>Statistical Significance and P-values</h3><h4>P-value</h4><p>the <strong><em>p </em>value</strong> is a number, calculated from a statistical test, that describes how likely you are to have found a particular set of observations if the null hypothesis were true.</p><p><em>P </em>values are used in hypothesis testing to help decide whether to reject the null hypothesis. The smaller the <em>p </em>value, the more likely you are to reject the null hypothesis.</p><p><strong>The difference between type I and type II errors in hypothesis testing are</strong>:</p><ul><li>Type I error is a false positive conclusion, rejecting a true null hypothesis.</li><li>Type II error is a false negative conclusion, accepting a false null hypothesis.</li></ul><p>Type I error is denoted by the Greek letter alpha (α), while type II error is denoted by the Greek letter beta (β).</p><p>Type I error is related to the alternative hypothesis, while type II error is related to the null hypothesis.</p><h4>P values and statistical significance</h4><p><em>P </em>values are most often used by researchers to say whether a certain pattern they have measured is statistically significant.</p><p><strong>Statistical significance</strong> is another way of saying that the <em>p </em>value of a statistical test is small enough to reject the null hypothesis of the test.</p><p>How small is small enough? The most common threshold is <em>p &lt;</em> 0.05; that is, when you would expect to find a test statistic as extreme as the one calculated by your test only 5% of the time.</p><p>The threshold value for determining statistical significance is also known as the <strong>alpha </strong>value.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvemZtEM63GY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvemZtEM63GY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvemZtEM63GY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec2f4dfe354238ffef8a6576e0a552f/href">https://medium.com/media/bec2f4dfe354238ffef8a6576e0a552f/href</a></iframe><h3>t-Tests</h3><p>A t-<strong>test</strong> is a statistical test that is used to compare the means of two groups. It is often used in hypothesis testing to determine whether a process or treatment actually has an effect on the population of interest, or whether two groups are different from one another.</p><h4>When to use a t test</h4><p>A <em>t</em> test can only be used when comparing the means of two groups (a.k.a. pairwise comparison). If you want to compare more than two groups, or if you want to do multiple pairwise comparisons, use an ANOVA test or a post-hoc test.</p><p>The <em>t</em> test is a parametric test of difference, meaning that it makes the same assumptions about your data as other parametric tests. The <em>t</em> test assumes your data:</p><ol><li>are independent.</li><li>are (approximately) normally distributed.</li><li>have a similar amount of variance within each group being compared (a.k.a. homogeneity</li></ol><h4>One-sample, two-sample, or paired t test?</h4><ul><li>If the groups come from a single population (measuring before and after an experimental treatment), perform a <strong>paired <em>t</em> test</strong>. This is a within-subjects design.</li><li>If the groups come from two different populations (two different species, or people from two separate cities), perform a <strong>two-sample <em>t</em> test </strong>(a.k.a. <strong>independent <em>t </em>test</strong>). This is a between-subjects design.</li><li>If there is one group being compared against a standard value (comparing the acidity of a liquid to a neutral pH of 7), perform a <strong>one-sample <em>t</em> test</strong>.</li></ul><h4>One-tailed or two-tailed t test?</h4><ul><li>If you only care whether the two populations are different from one another, perform a <strong>two-tailed <em>t</em> test</strong>.</li><li>If you want to know whether one population mean is greater than or less than the other, perform a <strong>one-tailed <em>t</em> test.</strong></li></ul><p>The t-test is used to determine if there is a significant difference between the means of two groups. The t-value is calculated by dividing the difference between the means of the two sample sets by the variation that exists within the sample sets1. The t-value is then compared against a value obtained from a critical value table called the T-distribution table1. The t-distribution is a probability distribution that is used to estimate the mean of a population when the sample size is small.</p><h3>ANOVA</h3><h4>What Is Analysis of Variance (ANOVA)?</h4><p>Analysis of variance (ANOVA) is an analysis tool used in statistics that splits an observed aggregate variability found inside a data set into two parts: systematic factors and random factors. The systematic factors have a statistical influence on the given data set, while the random factors do not. Analysts use the ANOVA test to determine the influence that independent variables have on the dependent variable in a regression study.</p><h4>The Formula for ANOVA is:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*cOovi6T6wkBs-8TlefoUhQ.png" /></figure><h4>One-Way ANOVA Versus Two-Way ANOVA</h4><p>One-way or two-way refers to the number of independent variables in your analysis of variance test. A one-way ANOVA evaluates the impact of a sole factor on a sole response variable. It determines whether all the samples are the same. The one-way ANOVA is used to determine whether there are any statistically significant differences between the means of three or more independent (unrelated) groups.</p><p>A two-way ANOVA is an extension of the one-way ANOVA. With a one-way, you have one independent variable affecting a dependent variable. With a two-way ANOVA, there are two independents. For example, a two-way ANOVA allows a company to compare worker productivity based on two independent variables, such as salary and skill set. It is utilized to observe the interaction between the two factors and tests the effect of two factors at the same time.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEFdlFoHI_0I%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEFdlFoHI_0I&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEFdlFoHI_0I%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a60d376edc5221846d6d6240059b22/href">https://medium.com/media/d8a60d376edc5221846d6d6240059b22/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fj9ZPMlVHJVs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dj9ZPMlVHJVs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fj9ZPMlVHJVs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2fc64a7b9e3fa11a9116b457cd452b2/href">https://medium.com/media/b2fc64a7b9e3fa11a9116b457cd452b2/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXg8_iSkJpAE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXg8_iSkJpAE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXg8_iSkJpAE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad1b5f0a72a72452655bc99bc633d6b8/href">https://medium.com/media/ad1b5f0a72a72452655bc99bc633d6b8/href</a></iframe><h3>Chi-Square test</h3><p>Pearson’s<strong> chi-square</strong> (Χ2) tests, often referred to simply as<strong> chi-square</strong> tests, are<strong> among the most common nonparametric tests.</strong> Nonparametric tests are used for data that don’t follow the assumptions of parametric tests, especially the assumption of a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*aLNxnbsrwdxZ2ucml8oG8A.png" /></figure><p>Where:</p><ul><li>Χ2 is the chi-square test statistic.</li><li><em>O</em> is the observed frequency</li><li><em>E</em> is the expected frequency</li></ul><h3>Multi-Arm Bandit Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5OEiCVOQk1X34gr5" /><figcaption>Photo by <a href="https://unsplash.com/@possessedphotography?utm_source=medium&amp;utm_medium=referral">Possessed Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What is the multi-armed bandit problem?</h4><p>In marketing terms, a multi-armed bandit solution is a ‘smarter’ or more complex version of A/B testing that uses machine learning algorithms to dynamically allocate traffic to variations that are performing well, while allocating less traffic to variations that are underperforming.</p><p>The term “multi-armed bandit” comes from a hypothetical experiment where a person must choose between multiple actions (i.e., slot machines, the “one-armed bandits”), each with an unknown payout. The goal is to determine the best or most profitable outcome through a series of choices. At the beginning of the experiment, when odds and payouts are unknown, the gambler must determine which machine to pull, in which order and how many times. This is the “multi-armed bandit problem.”</p><h4>Multi-armed bandit examples</h4><p>One real-world example of a multi-armed bandit problem is when a news website has to make a decision about which articles to display to a visitor. With no information about the visitor, all click outcomes are unknown. The first question is, which articles will get the most clicks? And in which order should they appear? The website’s goal is to maximize engagement, but they have many pieces of content from which to choose, and they lack data that would help them to pursue a specific strategy.</p><p>The news website has a similar problem in choosing which ads to display to its visitors. In this case, they want to maximize advertising revenue, but they may be lacking enough information about the visitor to pursue a specific advertising strategy. Similar to the issue with news articles, they typically have a large number of ads from which to choose. Which ads will drive maximum revenue for their news site?</p><p>The website needs to make a series of decisions, each with unknown outcome and ‘payout.’</p><h4>Multi-armed bandit solutions</h4><p>There are many different solutions that computer scientists have developed to tackle the multi-armed bandit problem. Below is a list of some of the most commonly used multi-armed bandit solutions:</p><p><strong>Epsilon-greedy</strong></p><p>This is an algorithm for continuously balancing exploration with exploitation. (In ‘greedy’ experiments, the lever with highest known payout is always pulled except when a random action is taken). A randomly chosen arm is pulled a fraction ε of the time. The other 1-ε of the time, the arm with highest known payout is pulled.</p><p><strong>Upper confidence bound</strong></p><p>This strategy is based on the Optimism in the Face of Uncertainty principle and assumes that the unknown mean payoffs of each arm will be as high as possible, based on observable data.</p><p><strong>Thompson Sampling (Bayesian)</strong></p><p>With this randomized probability matching strategy, the number of pulls for a given lever should match its actual probability of being the optimal lever.</p><p>By the end of this chapter, you have an overview on how statistical tests used in hypothesis testing, and the basics of hypothesis alpha, p-value. For sure it requires more searching and studying to have a complete overview about the topic you’re studying, some recommendation is to see the different types of ANOVA and their formulas and when to use each and so on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ec7cd7fe0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Statistics for Data Scientists Ch2(Data and Sampling Distributions).]]></title>
            <link>https://medium.com/@abdullah.hosam13/practical-statistics-for-data-scientists-ch2-data-and-sampling-distributions-8eaf3ed1b1b8?source=rss-e9311f2995fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eaf3ed1b1b8</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abdullah Younis]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 12:21:56 GMT</pubDate>
            <atom:updated>2023-12-21T12:21:56.519Z</atom:updated>
            <content:encoded><![CDATA[<p>In this chapter authors are giving an introduction to the different distribution&#39;s methods and the basics of it, this will benefit the reader to correlate with other concepts in the upcoming chapters.</p><blockquote><strong>Chapter contents</strong></blockquote><ol><li>Random sampling and sample bias</li><li>Selection bias</li><li>Sampling distribution of a statistic</li><li>The bootstrap</li><li>Confidence Intervals</li><li>Normal distribution</li><li>Long tailed distribution</li><li>Student’s t-Distribution</li><li>Binomial distribution</li><li>Chi-square distribution</li><li>F-distribution</li><li>Poisson and related distributions</li></ol><blockquote>Random sampling and sample bias</blockquote><p>Bias: Bias implies that the data selection may have been skewed by the collection criteria. Other forms of human-based bias emerge in data collection as well such as response bias, in which participants give inaccurate responses to a question. Bias does not preclude the existence of any other mistakes.</p><p>Random selection: Random selection is the method of selecting a sample from the population to participate in a study. Basically, random selection is the way a researcher chooses the participants in a study. This requires the researcher to identify the population and the sample. A population is all members of a specified group.</p><blockquote>Selection bias</blockquote><p>Selection bias: occurs if a data set’s examples are chosen in a way that is not reflective of their real-world distribution. Selection bias can take many different forms: Coverage bias: Data is not selected in a representative fashion.</p><p>Regression to the mean: (RTM) is a statistical phenomenon describing how variables much higher or lower than the mean are often much closer to the mean when measured a second time. Regression to the mean is due to natural variation or chance. It can be observed in <a href="https://www.scribbr.com/commonly-confused-words/everyday-vs-every-day/">everyday</a> life, particularly in research that intentionally focuses on the most extreme cases or events. It is sometimes also called <strong>regression </strong><a href="https://www.scribbr.com/us-vs-uk/toward-or-towards/"><strong>toward</strong></a><strong> the mean</strong>.</p><blockquote>Sampling distribution of a statistic</blockquote><p>Standard error: Standard error is the approximate standard deviation of a statistical sample population. The standard error describes the variation between the calculated mean of the population and one which is considered known or accepted as accurate.</p><p>Note: Standard error and standard deviation are both measures of variability: The standard deviation describes variability within a single sample. The standard error estimates the variability across multiple samples of a population.</p><blockquote>The bootstrap</blockquote><p>“Bootstrapping is a statistical procedure that resamples a single data set to create many simulated samples. This process allows for the calculation of standard errors, confidence intervals, and hypothesis testing,” according to a post on bootstrapping statistics from statistician Jim Frost.</p><p>How to do bootstrapping?</p><ol><li>Draw a sample value, record it, and then replace it.</li><li>Repeat n times.</li><li>Record the mean of the n resampled values.</li><li>Repeat steps 1–3 R times.</li><li>use the R results to:</li></ol><p>a. Calculate their standard deviation.</p><p>b. Produce a histogram or boxplot.</p><p>c. Find a confidence interval.</p><blockquote>Confidence Intervals</blockquote><p>A confidence interval is the mean of your estimate plus and minus the variation in that estimate. This is the range of values you expect your estimate to fall between if you redo your test, within a certain level of confidence. Confidence, in statistics, is another way to describe probability.</p><p>The bootstrap is an effective way to construct confidence interval.</p><ol><li>Draw a random sample of size n with replacement from the data (a resample)</li><li>Record the statistic of interest for the resample.</li><li>Repeat steps 1–2 many (R) times.</li><li>For an x% confidence interval, trim [(100-x)/2] % of the R resample results from either end of the distribution.</li><li>The trim points are the endpoints of an x% bootstrap confidence interval.</li></ol><blockquote>Normal Distribution</blockquote><p>In a normal distribution, data are symmetrically distributed with no skew. Most values cluster around a central region, with values tapering off as they go further away from the center. The measures of central tendency (mean, mode, and median) are exactly the same in a normal distribution.</p><p>The two main parameters of a (normal) distribution are the mean and standard deviation. The parameters determine the shape and probabilities of the distribution. The shape of the distribution changes as the parameter values changes.</p><p>For a random variable x, with mean “μ” and standard deviation “σ”, the normal distribution formula is given by f(x) = (1/√(2πσ2)) (e[-(x-μ)²]/2σ²).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*2c5M2VdUaR8ZisWvC1eMKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cX2cIO_UNPDIQDelCLVDnA.jpeg" /></figure><blockquote>Long-Tailed Distribution</blockquote><p>In statistics and business, a long tail of some distributions of numbers is the portion of the distribution having many occurrences far from the “head” or central part of the distribution. The distribution could involve popularities, random numbers of occurrences of events with various probabilities, etc.</p><p>In “long-tailed” distributions a high-frequency or high-amplitude population is followed by a low-frequency or low-amplitude population which gradually “tails off” asymptotically. The events at the far end of the tail have a very low probability of occurrence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t77SCcLiS5jHTZqe6WAY-Q.jpeg" /></figure><blockquote>Student’s t-distribution</blockquote><p>The t-distribution, also known as the student’s t-distribution, is a type of probability distribution that is similar to the normal distribution with its bell shape but has heavier tails. It is used for estimating population parameters for small sample sizes or unknown variances.</p><p>The t-distribution becomes increasingly closer in resemblance to the normal distribution as the value for the degrees of freedom increases. Once the degrees of freedom are close to 30, provided there is not significant skew or kurtosis in the population, the t-distribution should appear to be normally distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVQIzG34u94g2sE1mG0vUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*rX5dCRQPgLl5JGMvZYXKHA.png" /></figure><blockquote>Binomial Distribution</blockquote><p>Binomial distribution is a statistical distribution that summarizes the probability that a value will take one of two independent values under a given set of parameters or assumptions. Binomial distribution is calculated by multiplying the probability of success raised to the power of the number of successes and the probability of failure raised to the power of the difference between the number of successes and the number of trials.</p><p>Factors of binomial distribution</p><ul><li>The number of observations n is fixed.</li><li>Each observation is independent.</li><li>Each observation represents one of two outcomes (“success” or “failure”).</li><li>The probability of “success” p is the same for each outcome.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*oMh1XYrkNDQxg8WWe8W_cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*fTZI0q24V_t881FGhKCmog.png" /></figure><blockquote><strong>Chi-Square Distribution</strong></blockquote><p>A chi-square distribution is a continuous distribution with k degrees of freedom. It is used to describe the distribution of a sum of squared random variables.</p><p><strong>The probability density function (PDF)</strong> of the chi-square distribution with k degrees of freedom is given by:</p><p>f(x) = (1 / (2^(k/2) * Γ(k/2))) * (x^(k/2–1) * e^(-x/2))</p><p>where:</p><ul><li>x is the random variable.</li><li>k is the degrees of freedom.</li><li>Γ(k/2) is the gamma function evaluated at k/2.</li></ul><p>In this formula, e represents the base of the natural logarithm (approximately 2.71828) and Γ(k/2) denotes the gamma function, which is a generalization of the factorial function for non-integer values.</p><p><strong>The cumulative distribution function (CDF) </strong>of the chi-square distribution can be obtained by integrating the PDF from 0 to a given value:</p><p>F(x) = ∫[0,x] f(t) dt</p><p>Note that there is no closed-form expression for the inverse of the CDF. However, it can be calculated using numerical methods or by referring to chi-square distribution tables.</p><p>It’s worth mentioning that the chi-square distribution is defined only for non-negative values of x and is skewed to the right. The mean of the distribution is equal to k, and the variance is 2k.</p><p><strong>The probability density function (PDF)</strong> is a statistical expression that defines the probability that some outcome will occur. In this function, the probability is the percentage of a dataset’s distribution that falls between two criteria.</p><p><strong>The cumulative distribution function (CDF) </strong>gives the probability that the random variable X is less than or equal to x and is usually denoted F(x).</p><p>The PDF is used for continuous random variables, where the probability is distributed over an infinite range of values. The CDF applies to discrete and continuous random variables, as it accumulates probabilities for all possible values of the random variable.</p><blockquote><strong>F-Distribution</strong></blockquote><p>The F-distribution, also known Fisher-Snedecor distribution, is extensively used to test for equality of variances from two normal populations. F-distribution got its name after R.A. Fisher, who initially developed this concept in the 1920s. It is a probability distribution of an F-Statistic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*7Bgx8EEe3ACZqaBnCOjm6A.png" /></figure><p>F-Distribution Formula</p><p>The formula to calculate the F-statistic, or F-value, is F = σ 1 σ 2, or Variance 1/Variance 2. In order to accommodate the skewed right shape of the F-distribution, the larger variance is placed in the numerator and the smaller variance is used in the denominator.</p><blockquote><strong>Poisson Distribution</strong></blockquote><p>A Poisson distribution is a discrete probability distribution. It gives the probability of an event happening a certain number of times (k) within a given interval of time or space. The Poisson distribution has only one parameter, λ (lambda), which is the mean number of events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*JbzdakVs6yXjnJfDIopfuw.gif" /></figure><p>Assume that we conduct a Poisson experiment, in which the average number of successes within a given range is taken as λ. In Poisson distribution, the mean of the distribution is represented by λ and e is constant, which is approximately equal to 2.71828. Then, the Poisson probability is P(x, λ ) = (e– λ λx)/x!</p><blockquote><strong>Exponential Distribution</strong></blockquote><p>In Probability theory and statistics, the exponential distribution is a continuous probability distribution that often concerns the amount of time until some specific event happens. It is a process in which events happen continuously and independently at a constant average rate.</p><p>The formula for the exponential distribution: P ( X = x ) = m e — m x = 1 μ e — 1 μ x P ( X = x ) = m e — m x = 1 μ e — 1 μ x Where m = the rate parameter, or μ = average time between occurrences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*aRwHG-51fNwrZjDa8mfrPQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkkmdZovlJNb9mO4-7AHEg.png" /></figure><blockquote><strong>Weibull Distribution</strong></blockquote><p>The Weibull distribution function is commonly used in fracture mechanics to describe the relation between the probability of failure, Pf, and an effective surface area, Aeff, by using two (or more) parameters: the Weibull modulus, m, and a normalization constant, σo(2)Pf=1−e−Aeff(σmaxσo)m.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*strTwLSey05u0Ixqd51xUg.png" /></figure><p>In the end of this chapter, you should have an entire overview for different types of distributions which will going to benefit you later in the next chapters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eaf3ed1b1b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>