<?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 Tanya Verma on Medium]]></title>
        <description><![CDATA[Stories by Tanya Verma on Medium]]></description>
        <link>https://medium.com/@tanya.dav5301?source=rss-a77910cdac9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*x4M7ia7xLa372LpA</url>
            <title>Stories by Tanya Verma on Medium</title>
            <link>https://medium.com/@tanya.dav5301?source=rss-a77910cdac9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:03:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanya.dav5301/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[K-Nearest Neighbor(KNN) Algorithm]]></title>
            <link>https://medium.com/@tanya.dav5301/k-nearest-neighbor-knn-algorithm-8007315dfe2a?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8007315dfe2a</guid>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 05:31:04 GMT</pubDate>
            <atom:updated>2026-01-07T05:31:04.768Z</atom:updated>
            <content:encoded><![CDATA[<p>K-Nearest Neighbor(KNN) Algorithm</p><p>K-Nearest Neighbors (KNN) is a supervised machine learning algorithm generally used for classification but can also be used for regression tasks. It works by finding the &quot;k&quot; closest data points (neighbors) to a given input and makes a predictions based on the majority class (for classification) or the average value (for regression). Since KNN makes no assumptions about the underlying data distribution it makes it a non-parametric and instance-based learning method.</p><p>K-Nearest Neighbors is also called as a lazy learner algorithm because it does not learn from the training set immediately instead it stores the entire dataset and performs computations only at the time of classification.</p><p>For example, consider the following table of data points containing two features:</p><p>The new point is classified as Category 2 because most of its closest neighbors are blue squares. KNN assigns the category based on the majority of nearby points. The image shows how KNN predicts the category of a new data point based on its closest neighbours.</p><p>The red diamonds represent Category 1 and the blue squares represent Category 2.</p><p>The new data point checks its closest neighbors (circled points).</p><p>Since the majority of its closest neighbors are blue squares (Category 2) KNN predicts the new data point belongs to Category 2.</p><p>KNN Algorithm working visualization</p><p>KNN works by using proximity and majority voting to make predictions.</p><p>What is &#39;K&#39; in K Nearest Neighbour?</p><p>In the k-Nearest Neighbours algorithm k is just a number that tells the algorithm how many nearby points or neighbors to look at when it makes a decision.</p><p>Example: Imagine you&#39;re deciding which fruit it is based on its shape and size. You compare it to fruits you already know.</p><p>If k = 3, the algorithm looks at the 3 closest fruits to the new one.</p><p>If 2 of those 3 fruits are apples and 1 is a banana, the algorithm says the new fruit is an apple because most of its neighbors are apples.</p><p>How to choose the value of k for KNN Algorithm?</p><p>The value of k in KNN decides how many neighbors the algorithm looks at when making a prediction.</p><p>Choosing the right k is important for good results.</p><p>If the data has lots of noise or outliers, using a larger k can make the predictions more stable.</p><p>But if k is too large the model may become too simple and miss important patterns and this is called underfitting.</p><p>So k should be picked carefully based on the data.</p><p>Statistical Methods for Selecting k</p><p>Cross-Validation: <a href="https://www.geeksforgeeks.org/machine-learning/cross-validation-machine-learning/%22/%20target=/">Cross-Validation </a>is a good way to find the best value of k is by using k-fold cross-validation. This means dividing the dataset into k parts. The model is trained on some of these parts and tested on the remaining ones. This process is repeated for each part. The k value that gives the highest average accuracy during these tests is usually the best one to use.</p><p>Elbow Method: In <a href="https://www.geeksforgeeks.org/machine-learning/elbow-method-for-optimal-value-of-k-in-kmeans/%22%20target=/">Elbow Method</a> we draw a graph showing the error rate or accuracy for different k values. As k increases the error usually drops at first. But after a certain point error stops decreasing quickly. The point where the curve changes direction and looks like an &quot;elbow&quot; is usually the best choice for k.</p><p>Odd Values for k: It’s a good idea to use an odd number for k especially in classification problems. This helps avoid ties when deciding which class is the most common among the neighbors.</p><p>Distance Metrics Used in KNN Algorithm</p><p>KNN uses distance metrics to identify nearest neighbor, these neighbors are used for classification and regression task. To identify nearest neighbor we use below distance metrics:</p><p>1. Euclidean Distance</p><p>Euclidean distance is defined as the straight-line distance between two points in a plane or space. You can think of it like the shortest path you would walk if you were to go directly from one point to another.</p><p>distance(x,Xi)=∑j=1d(xj−Xij)2]distance(x,Xi​)=∑j=1d​(xj​−Xij​​)2​]</p><p>2. Manhattan Distance</p><p>This is the total distance you would travel if you could only move along horizontal and vertical lines like a grid or city streets. It’s also called &quot;taxicab distance&quot; because a taxi can only drive along the grid-like streets of a city.</p><p>d(x,y)=∑i=1n∣xi−yi∣d(x,y)=∑i=1n​∣xi​−yi​∣</p><p>3. Minkowski Distance</p><p>Minkowski distance is like a family of distances, which includes both Euclidean and Manhattan distances as special cases.</p><p>d(x,y)=(∑i=1n(xi−yi)p)1pd(x,y)=(∑i=1n​(xi​−yi​)p)p1​</p><p>From the formula above, when p=2, it becomes the same as the Euclidean distance formula and when p=1, it turns into the Manhattan distance formula. Minkowski distance is essentially a flexible formula that can represent either Euclidean or Manhattan distance depending on the value of p.</p><p>Working of KNN algorithm</p><p>Thе K-Nearest Neighbors (KNN) algorithm operates on the principle of similarity where it predicts the label or value of a new data point by considering the labels or values of its K nearest neighbors in the training dataset.</p><p>Step 1: Selecting the optimal value of K</p><p>K represents the number of nearest neighbors that needs to be considered while making prediction.</p><p>Step 2: Calculating distance</p><p>To measure the similarity between target and training data points Euclidean distance is widely used. Distance is calculated between data points in the dataset and target point.</p><p>Step 3: Finding Nearest Neighbors</p><p>The k data points with the smallest distances to the target point are nearest neighbors.</p><p>Step 4: Voting for Classification or Taking Average for Regression</p><p>When you want to classify a data point into a category like spam or not spam, the KNN algorithm looks at the K closest points in the dataset. These closest points are called neighbors. The algorithm then looks at which category the neighbors belong to and picks the one that appears the most. This is called majority voting.</p><p>In regression, the algorithm still looks for the K closest points. But instead of voting for a class in classification, it takes the average of the values of those K neighbors. This average is the predicted value for the new point for the algorithm.</p><p>It shows how a test point is classified based on its nearest neighbors. As the test point moves the algorithm identifies the closest &#39;k&#39; data points i.e. 5 in this case and assigns test point the majority class label that is grey label class here.</p><p>Implementing KNN from Scratch in Python</p><p>1. Importing Libraries</p><p><a href="https://www.geeksforgeeks.org/python/counters-in-python-set-1/%22%20target=/">Counter </a>is used to count the occurrences of elements in a list or iterable. In KNN after finding the k nearest neighbor labels Counter helps count how many times each label appears.</p><p>import numpy as np</p><p>from collections import Counter</p><p>2. Defining the Euclidean Distance Function</p><p>euclidean_distance is to calculate euclidean distance between points.</p><p>def euclidean_distance(point1, point2):</p><p>return np.sqrt(np.sum((np.array(point1) - np.array(point2))**2))</p><p>3. KNN Prediction Function</p><p>distances.append saves how far each training point is from the test point, along with its label.</p><p>distances.sort is used to sorts the list so the nearest points come first.</p><p>k_nearest_labels picks the labels of the k closest points.</p><p>Uses Counter to find which label appears most among those k labels that becomes the prediction.</p><p>def knn_predict(training_data, training_labels, test_point, k):</p><p>distances = [] for i in range(len(training_data)): dist = euclidean_distance(test_point, training_data[i]) distances.append((dist, training_labels[i])) distances.sort(key=lambda x: x[0]) k_nearest_labels = [label for _, label in distances[:k]] return Counter(k_nearest_labels).most_common(1)[0][0]</p><p>4. Training Data, Labels and Test Point</p><p>training_data = [[1, 2], [2, 3], [3, 4], [6, 7], [7, 8]]</p><p>training_labels = [&#39;A&#39;, &#39;A&#39;, &#39;A&#39;, &#39;B&#39;, &#39;B&#39;]test_point = [4, 5]k = 3</p><p>5. Prediction</p><p>prediction = knn_predict(training_data, training_labels, test_point, k)</p><p>print(prediction)</p><p>Output:</p><p>A</p><p>The algorithm calculates the distances of the test point [4, 5] to all training points selects the 3 closest points as k = 3 and determines their labels. Since the majority of the closest points are labelled &#39;A&#39; the test point is classified as &#39;A&#39;.</p><p>In machine learning we can also use Scikit Learn python library which has in built functions to perform KNN machine learning model and for that you refer to <a href="https://www.geeksforgeeks.org/machine-learning/ml-implementation-of-knn-classifier-using-sklearn/%22/%20target=/">Implementation of KNN classifier using Sklearn.</a></p><p>Applications of KNN</p><p>Recommendation Systems: Suggests items like movies or products by finding users with similar preferences.</p><p>Spam Detection: Identifies spam emails by comparing new emails to known spam and non-spam examples.</p><p>Customer Segmentation: Groups customers by comparing their shopping behavior to others.</p><p>Speech Recognition: Matches spoken words to known patterns to convert them into text.</p><p>Advantages of KNN</p><p>Simple to use: Easy to understand and implement.</p><p>No training step: No need to train as it just stores the data and uses it during prediction.</p><p>Few parameters: Only needs to set the number of neighbors (k) and a distance method.</p><p>Versatile: Works for both classification and regression problems.</p><p>Disadvantages of KNN</p><p>Slow with large data: Needs to compare every point during prediction.</p><p>Struggles with many features: Accuracy drops when data has too many features.</p><p>Can Overfit: It can overfit especially when the data is high-dimensional or not clean.</p><p>Also Check for more understanding:</p><p><a href="https://www.geeksforgeeks.org/machine-learning/k-nearest-neighbor-algorithm-in-python/%22%20rel=/">K Nearest Neighbors with Python | ML</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/implementation-of-k-nearest-neighbors-from-scratch-using-python/%22%20rel=/">Implementation of K-Nearest Neighbors from Scratch using Python</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/mathematical-explanation-of-k-nearest-neighbour/%22/%20rel=/">Mathematical explanation of K-Nearest Neighbour</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/weighted-k-nn/%22/%20rel=/">Weighted K-NN</a></p><p>Suggested Quiz</p><p>6 Questions</p><p>What is the main idea behind the K-Nearest Neighbors (KNN) algorithm?</p><p>A</p><p>It uses probability to classify data</p><p>B</p><p>It classifies a data point based on the majority class of its nearest neighbors</p><p>C</p><p>It builds decision trees to classify data</p><p>D</p><p>It uses gradient descent to update weights</p><p>Which distance metric is commonly used in KNN to find the nearest neighbors?</p><p>A</p><p>Manhattan Distance</p><p>B</p><p>Cosine Similarity</p><p>C</p><p>Jaccard Distance</p><p>D</p><p>Euclidean Distance</p><p>What is the effect of increasing the value of K in KNN?</p><p>A</p><p>Increases model complexity</p><p>B</p><p>Reduces the influence of noise</p><p>C</p><p>Makes the model overfit</p><p>D</p><p>Reduces accuracy</p><p>What happens when K is set to a very small value like 1?</p><p>A</p><p>The model generalizes better</p><p>B</p><p>The model becomes too simple</p><p>C</p><p>The model ignores noise</p><p>D</p><p>The model is prone to overfitting</p><p>In KNN, how do k and the distance metric affect model performance?</p><p>A</p><p>Small k high variance, large k underfitting, distance metric affects neighbor selection</p><p>B</p><p>Increasing k only reduces computation time</p><p>C</p><p>k doesn’t matter if Manhattan distance is used</p><p>D</p><p>Small k always improves accuracy</p><p>Why is feature scaling important for KNN?</p><p>A</p><p>To balance feature influence</p><p>B</p><p>To reduce training time</p><p>C</p><p>To avoid overfitting</p><p>D</p><p>To optimize loss</p><p>Quiz Completed Successfully</p><p>Your Score : 0/6</p><p>Accuracy : 0%</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8007315dfe2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Linear Regression Actually Does?]]></title>
            <link>https://medium.com/@tanya.dav5301/what-linear-regression-actually-does-951c6c38416c?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/951c6c38416c</guid>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 05:22:18 GMT</pubDate>
            <atom:updated>2026-01-07T05:22:18.742Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem: Predict Y (house price) from X (size in sq ft)</h3><p>Input: 1500 sq ft apartment<br>Output: ₹75 Lakhs price (predicted)</p><p>Math: Price = m × Size + c<br>Where m = slope, c = intercept</p><h3>Visual: See the Magic</h3><p>X-axis: Apartment Size (sq ft)<br>Y-axis: Price (₹Lakhs) <br>Red line = Your model’s prediction</p><h3>🔥 Step-by-Step Code (Copy-Paste Ready)</h3><p>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.linear_model import LinearRegression</p><p># Step 1: Your exam data (size → price)<br>X = np.array([[1000], [1500], [2000], [2500], [3000]]) # sq ft<br>y = np.array([50, 75, 100, 125, 150]) # ₹Lakhs</p><p># Step 2: Train model (1 line!)<br>model = LinearRegression()<br>model.fit(X, y)</p><p># Step 3: Predict new apartment<br>new_size = np.array([[2200]]) # New 2200 sq ft flat<br>price = model.predict(new_size)<br>print(f”2200 sq ft → ₹{price[0]:.0f} Lakhs”) # ₹110 Lakhs!</p><p># Step 4: Check accuracy<br>print(f”R² Score: {model.score(X, y):.2%}”) # 100% perfect fit</p><p>2200 sq ft → ₹110 Lakhs<br>R² Score: 100.00%</p><h3>🎓 Real Exam Question Example</h3><p>Data: <br>0 yrs → ₹3L<br>2 yrs → ₹6L <br>5 yrs → ₹12L</p><p>X_exp = np.array([[0], [2], [5]])<br>y_salary = np.array([3, 6, 12])</p><p>model.fit(X_exp, y_salary)<br>salary_3yrs = model.predict([[3]]) # ₹9L predicted!</p><p>Interview Answer: “Salary = 1.8 × Experience + 3L”</p><h3>📈 Graph Your Own Model</h3><p>plt.scatter(X, y, color=’blue’, s=100, label=’Actual Prices’)<br>plt.plot(X, model.predict(X), color=’red’, linewidth=3, label=’Prediction’)<br>plt.xlabel(‘Size (sq ft)’)<br>plt.ylabel(‘Price (₹Lakhs)’)<br>plt.title(‘Linear Regression: House Price Predictor’)<br>plt.legend()<br>plt.grid(True, alpha=0.3)<br>plt.savefig(‘house_price_model.png’, dpi=300)<br>plt.show()</p><p>Visual Output: Perfect red line through blue dots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qs4GuW3wL0-RP3fj.png" /></figure><h3>Mastering Data Visualization: Essential Charts for ML Practitioners</h3><p>Data visualization transforms raw numbers into actionable insights, serving as the foundation for effective machine learning workflows. This hands-on guide walks through creating histograms, bar charts, pie charts, and scatter plots using Python’s Pandas and Matplotlib libraries — exactly as implemented in a recent ML lab experiment.Lab1.ipynb​</p><h3>Generating Realistic Datasets</h3><p>Start by creating a synthetic dataset mimicking real-world demographics: 100 samples with ages (20–60), genders (Male/Female), and incomes ($20K-$100K). Use random.randint() and random.choice() to populate lists, then convert to a Pandas DataFrame and save as CSV:</p><pre>python</pre><pre>import random<br>import pandas as pd</pre><pre>data = {<br>    &#39;age&#39;: [random.randint(20, 60) for _ in range(100)],<br>    &#39;gender&#39;: [random.choice([&#39;Male&#39;, &#39;Female&#39;]) for _ in range(100)],<br>    &#39;income&#39;: [random.randint(20000, 100000) for _ in range(100)]<br>}<br>df = pd.DataFrame(data)<br>df.to_csv(&#39;data.csv&#39;, index=False)</pre><p>Load with pd.read_csv(&#39;data.csv&#39;) for analysis. This mirrors preprocessing steps before feeding data into models like regression.Lab1.ipynb​</p><h3>Histogram: Distribution Analysis</h3><p>Histograms reveal numerical data distributions, crucial for spotting outliers or skewness in features like age. Basic plot:</p><pre>python</pre><pre>import matplotlib.pyplot as plt<br>plt.hist(df[&#39;age&#39;], color=&#39;green&#39;)<br>plt.xlabel(&#39;Age&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.title(&#39;Age Distribution&#39;)<br>plt.show()</pre><p>Enhance with custom bins, colors, and gender splits for deeper insights — green for all ages, black/red for males/females (20 bins). Ideal for preprocessing decisions in ML pipelines.Lab1.ipynb​</p><h3>Bar &amp; Pie Charts: Categorical Comparisons</h3><p>Bar charts compare categories like gender counts:</p><pre>python</pre><pre>plt.bar(df[&#39;gender&#39;].unique(), df[&#39;gender&#39;].value_counts())<br>plt.xlabel(&#39;Gender&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Gender Comparison&#39;)<br>plt.show()</pre><p>Pie charts show proportions with percentages:</p><pre>python</pre><pre>plt.pie(df[&#39;gender&#39;].value_counts(), labels=df[&#39;gender&#39;].unique(), autopct=&#39;%1.1f%%&#39;)<br>plt.title(&#39;Gender Proportion&#39;)<br>plt.show()</pre><p>These visuals quickly highlight imbalances, informing sampling strategies for balanced datasets.Lab1.ipynb​</p><h3>Scatter Plots: Correlation Exploration</h3><p>Scatter plots uncover relationships between variables, like age vs. income:</p><pre>python</pre><pre>plt.scatter(df[&#39;age&#39;], df[&#39;income&#39;], color=&#39;red&#39;, edgecolor=&#39;black&#39;, s=100)<br>plt.xlabel(&#39;Age&#39;)<br>plt.ylabel(&#39;Income&#39;)<br>plt.title(&#39;Age vs Income&#39;)<br>plt.show()</pre><p>Custom markers reveal trends at a glance, essential for feature selection in regression tasks.Lab1.ipynb​</p><p>These techniques build intuition before advanced ML — perfect for students tackling BTech labs or early-career engineers. Fork the notebook, experiment, and share your variants! Code available on GitHub.Lab1.ipynb​</p><ol><li><a href="https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/72238498/b9f62794-0c15-451c-93e3-b395b34b2785/Lab1.ipynb">https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/72238498/b9f62794-0c15-451c-93e3-b395b34b2785/Lab1.ipynb</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951c6c38416c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers revolutionized AI by ditching RNNs for parallelizable attention mechanisms.]]></title>
            <link>https://medium.com/@tanya.dav5301/transformers-revolutionized-ai-by-ditching-rnns-for-parallelizable-attention-mechanisms-d9d50ae4f534?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9d50ae4f534</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[ux-design]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 15:19:09 GMT</pubDate>
            <atom:updated>2025-12-30T15:19:09.699Z</atom:updated>
            <content:encoded><![CDATA[<p>Transformers revolutionized AI by ditching RNNs for parallelizable attention mechanisms. This LinkedIn post breaks down the core architecture with PyTorch code you can copy-paste and run.</p><p>Core Idea<br>The Transformer from &quot;Attention is All You Need&quot; (2017) uses stacked encoder-decoder blocks to process sequences like text. Encoders build input representations; decoders generate outputs autoregressively. Key innovation: self-attention lets every token &quot;attend&quot; to others, capturing long-range dependencies efficiently.</p><p>-Embeddings + Positional Encoding: Convert tokens to vectors, add sine/cosine position info since attention ignores order.</p><p>- Multi-Head Self-Attention: Computes Query/Key/Value projections, scales dot-products, and softmax for context weights across 8+ heads.</p><p>- Feed-Forward &amp; Residuals: Per-token MLPs with layer norm and skip connections for stable deep training.</p><p>- Masks: Prevent decoder from peeking at future tokens.</p><p>## Simplified PyTorch Code<br>Here’s a runnable Multi-Head Attention block (core of encoders/decoders). Scale up with full Transformer via GitHub repos.</p><p>```python<br>import torch<br>import torch.nn as nn<br>import math</p><p>class MultiHeadAttentionBlock(nn.Module):<br> def __init__(self, d_model: int, num_head: int, dropout: float) -&gt; None:<br> super().__init__()<br> self.d_model = d_model<br> self.num_head = num_head<br> assert d_model % num_head == 0<br> self.d_k = d_model // num_head<br> self.w_q = nn.Linear(d_model, d_model)<br> self.w_k = nn.Linear(d_model, d_model)<br> self.w_v = nn.Linear(d_model, d_model)<br> self.w_o = nn.Linear(d_model, d_model)<br> self.dropout = nn.Dropout(dropout)</p><p>@staticmethod<br> def attention(query, key, value, mask, dropout: nn.Dropout):<br> d_k = query.shape[-1]<br> scores = (query @ key.transpose(-2, -1)) / math.sqrt(d_k)<br> if mask is not None:<br> scores.masked_fill_(mask == 0, -1e9)<br> scores = scores.softmax(dim=-1)<br> if dropout is not None:<br> scores = dropout(scores)<br> return (scores @ value), scores</p><p>def forward(self, q, k, v, mask):<br> query = self.w_q(q).view(q.shape[0], q.shape[1], self.num_head, self.d_k).transpose(1, 2)<br> key = self.w_k(k).view(k.shape[0], k.shape[1], self.num_head, self.d_k).transpose(1, 2)<br> value = self.w_v(v).view(v.shape[0], v.shape[1], self.num_head, self.d_k).transpose(1, 2)<br> x, self.attention_score = self.attention(query, key, value, mask, self.dropout)<br> return self.w_o(x.transpose(1, 2).contiguous().view(x.shape[0], -1, self.d_model))<br>```</p><p>Test it: `attention = MultiHeadAttentionBlock(512, 8, 0.1); out = attention(x, x, x, mask)`</p><p>## Build Yours<br>Stack 6 encoders (self-attn + FFN) and decoders (masked self-attn + cross-attn + FFN). Train on translation data. Full impl: https://github.com/SirawitC/Transformer_from_scratch_pytorch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9d50ae4f534" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random Forest Algorithm in Machine Learning]]></title>
            <link>https://medium.com/@tanya.dav5301/random-forest-algorithm-in-machine-learning-237d3e4cce38?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/237d3e4cce38</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 04:23:13 GMT</pubDate>
            <atom:updated>2025-12-28T04:23:13.230Z</atom:updated>
            <content:encoded><![CDATA[<p>Random Forest Algorithm in Machine Learning</p><p>Random Forest is a machine learning algorithm that uses many decision trees to make better predictions. Each tree looks at different random parts of the data and their results are combined by voting for classification or averaging for regression which makes it as ensemble learning technique. This helps in improving accuracy and reducing errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HB3qyMwpYq0D9LKQubmFrQ.webp" /></figure><p><a href="https://www.geeksforgeeks.org/machine-learning/python-for-machine-learning/">Python for Machine Learning</a></p><p><a href="https://www.geeksforgeeks.org/r-machine-learning/introduction-to-machine-learning-in-r/">Machine Learning with R</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/machine-learning-algorithms/">Machine Learning Algorithms</a></p><p><a href="https://www.geeksforgeeks.org/data-analysis/what-is-exploratory-data-analysis/">EDA</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/machine-learning-mathematics/">Math for Machine Learning</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/machine-learning-interview-questions/">Machine Learning Interview Questions</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/machine-learning-projects/">ML Projects</a></p><p><a href="https://www.geeksforgeeks.org/deep-learning/deep-learning-tutorial/">Deep Learning</a></p><p><a href="https://www.geeksforgeeks.org/nlp/natural-language-processing-nlp-tutorial/">NLP</a></p><p><a href="https://www.geeksforgeeks.org/computer-vision/computer-vision/">Computer vision</a></p><p>Random Forest Algorithm in Machine Learning</p><p>Last Updated : 23 Dec, 2025</p><p>Random Forest is a machine learning algorithm that uses many decision trees to make better predictions. Each tree looks at different random parts of the data and their results are combined by voting for classification or averaging for regression which makes it as ensemble learning technique. This helps in improving accuracy and reducing errors.</p><p>Working of Random Forest Algorithm</p><p>Create Many Decision Trees: The algorithm makes many <a href="https://www.geeksforgeeks.org/machine-learning/decision-tree/">decision trees</a> each using a random part of the data. So every tree is a bit different.</p><p>Pick Random Features: When building each tree it doesn’t look at all the features (columns) at once. It picks a few at random to decide how to split the data. This helps the trees stay different from each other.</p><p>Each Tree Makes a Prediction: Every tree gives its own answer or prediction based on what it learned from its part of the data.</p><p>Combine the Predictions: For classification we choose a category as the final answer is the one that most trees agree on i.e majority voting and for regression we predict a number as the final answer is the average of all the trees predictions.</p><p>Why It Works Well: Using random data and features for each tree helps avoid overfitting and makes the overall prediction more accurate and trustworthy.</p><p>Key Features of Random Forest</p><p>Handles Missing Data: It can work even if some data is missing so you don’t always need to fill in the gaps yourself.</p><p>Shows Feature Importance: It tells you which features (columns) are most useful for making predictions which helps you understand your data better.</p><p>Works Well with Big and Complex Data: It can handle large datasets with many features without slowing down or losing accuracy.</p><p>Used for Different Tasks: You can use it for both classification like predicting types or labels and regression like predicting numbers or amounts.</p><p>Assumptions of Random Forest</p><p>Each tree makes its own decisions: Every tree in the forest makes its own predictions without relying on others.</p><p>Random parts of the data are used: Each tree is built using random samples and features to reduce mistakes.</p><p>Enough data is needed: Sufficient data ensures the trees are different and learn unique patterns and variety.</p><p>Different predictions improve accuracy: Combining the predictions from different trees leads to a more accurate final result.</p><p>Implementing Random Forest for Classification Tasks</p><p>Here we will predict survival rate of a person in titanic.</p><p>You can download dataset from <a href="https://media.geeksforgeeks.org/wp-content/uploads/20250901164440637128/titanic.csv">here</a>.</p><p>Import libraries like <a href="https://www.geeksforgeeks.org/pandas/introduction-to-pandas-in-python/">pandas </a>and <a href="https://www.geeksforgeeks.org/machine-learning/learning-model-building-scikit-learn-python-machine-learning-library/">scikit learn</a>.</p><p>Load the Titanic dataset.</p><p>Remove rows with missing target values (&#39;Survived&#39;).</p><p>Select features like class, sex, age, etc and convert &#39;Sex&#39; to numbers.</p><p>Fill missing age values with the median.</p><p>Split the data into training and testing sets, then train a Random Forest model.</p><p>Predict on test data, check accuracy and print a sample prediction result.</p><p>import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, classification_report import warnings warnings.filterwarnings(&#39;ignore&#39;) titanic_data = pd.read_csv(&#39;titanic.csv&#39;) titanic_data = titanic_data.dropna(subset=[&#39;Survived&#39;]) X = titanic_data[[&#39;Pclass&#39;, &#39;Sex&#39;, &#39;Age&#39;, &#39;SibSp&#39;, &#39;Parch&#39;, &#39;Fare&#39;]] y = titanic_data[&#39;Survived&#39;] X[&#39;Sex&#39;] = X[&#39;Sex&#39;].map({&#39;female&#39;: 0, &#39;male&#39;: 1}) X[&#39;Age&#39;] = X[&#39;Age&#39;].fillna(X[&#39;Age&#39;].median()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42) rf_classifier.fit(X_train, y_train) y_pred = rf_classifier.predict(X_test) accuracy = accuracy_score(y_test, y_pred) classification_rep = classification_report(y_test, y_pred) print(f&quot;Accuracy: {accuracy:.2f}&quot;) print(&quot;\nClassification Report:\n&quot;, classification_rep) sample = X_test.iloc[0:1] prediction = rf_classifier.predict(sample) sample_dict = sample.iloc[0].to_dict() print(f&quot;\nSample Passenger: {sample_dict}&quot;) print(f&quot;Predicted Survival: {&#39;Survived&#39; if prediction[0] == 1 else &#39;Did Not Survive&#39;}&quot;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*oZ22ehPyMwQOP6RHWadYqQ.webp" /></figure><p>We evaluated model&#39;s performance using a classification report to see how well it predicts the outcomes and used a random sample to check model prediction.</p><p>Implementing Random Forest for Regression Tasks</p><p>We will do house price prediction here.</p><p>Load the California housing dataset and create a DataFrame with features and target.</p><p>Separate the features and the target variable.</p><p>Split the data into training and testing sets (80% train, 20% test).</p><p>Initialize and train a Random Forest Regressor using the training data.</p><p>Predict house values on test data and evaluate using MSE and R² score.</p><p>Print a sample prediction and compare it with the actual value.</p><p>import pandas as pd from sklearn.datasets import fetch_california_housing from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error, r2_score california_housing = fetch_california_housing() california_data = pd.DataFrame(california_housing.data, columns=california_housing.feature_names) california_data[&#39;MEDV&#39;] = california_housing.target X = california_data.drop(&#39;MEDV&#39;, axis=1) y = california_data[&#39;MEDV&#39;] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) rf_regressor = RandomForestRegressor(n_estimators=100, random_state=42) rf_regressor.fit(X_train, y_train) y_pred = rf_regressor.predict(X_test) mse = mean_squared_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) single_data = X_test.iloc[0].values.reshape(1, -1) predicted_value = rf_regressor.predict(single_data) print(f&quot;Predicted Value: {predicted_value[0]:.2f}&quot;) print(f&quot;Actual Value: {y_test.iloc[0]:.2f}&quot;) print(f&quot;Mean Squared Error: {mse:.2f}&quot;) print(f&quot;R-squared Score: {r2:.2f}&quot;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*dRQRmDzb3y47ws7PsW91ug.webp" /></figure><p>We evaluated the model&#39;s performance using <a href="https://www.geeksforgeeks.org/maths/mean-squared-error/">Mean Squared Error</a> and<a href="https://www.geeksforgeeks.org/machine-learning/ml-r-squared-in-regression-analysis/"> R-squared Score</a> which show how accurate the predictions are and used a random sample to check model prediction.</p><p>Advantages of Random Forest</p><p>Random Forest provides very accurate predictions even with large datasets.</p><p>Random Forest can handle missing data well without compromising with accuracy.</p><p>It doesn’t require normalization or standardization on dataset.</p><p>When we combine multiple decision trees it reduces the risk of overfitting of the model.</p><p>Limitations of Random Forest</p><p>It can be computationally expensive especially with a large number of trees.</p><p>It’s harder to interpret the model compared to simpler models like decision trees.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=237d3e4cce38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Support Vector Machine (SVM) Algorithm]]></title>
            <link>https://medium.com/@tanya.dav5301/support-vector-machine-svm-algorithm-338e782b012c?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/338e782b012c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 04:13:06 GMT</pubDate>
            <atom:updated>2025-12-28T04:13:06.169Z</atom:updated>
            <content:encoded><![CDATA[<p>Support Vector Machine (SVM) Algorithm</p><p>Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or cat vs. dog.</p><p>The main goal of SVM is to maximize the margin between the two classes. The larger the margin the better the model performs on new and unseen data.</p><p>Key Concepts of Support Vector Machine</p><p>Hyperplane: A decision boundary separating different classes in feature space and is represented by the equation wx + b = 0 in linear classification.</p><p>Support Vectors: The closest data points to the hyperplane, crucial for determining the hyperplane and margin in SVM.</p><p>Margin: The distance between the hyperplane and the support vectors. SVM aims to maximize this margin for better classification performance.</p><p>Kernel: A function that maps data to a higher-dimensional space enabling SVM to handle non-linearly separable data.</p><p>Hard Margin: A maximum-margin hyperplane that perfectly separates the data without misclassifications.</p><p>Soft Margin: Allows some misclassifications by introducing slack variables, balancing margin maximization and misclassification penalties when data is not perfectly separable.</p><p>C: A regularization term balancing margin maximization and misclassification penalties. A higher C value forces stricter penalty for misclassifications.</p><p>Hinge Loss: A loss function penalizing misclassified points or margin violations and is combined with regularization in SVM.</p><p>Dual Problem: Involves solving for Lagrange multipliers associated with support vectors, facilitating the kernel trick and efficient computation.</p><p>How does Support Vector Machine Algorithm Work?</p><p>The key idea behind the SVM algorithm is to find the hyperplane that best separates two classes by maximizing the margin between them. This margin is the distance from the hyperplane to the nearest data points (support vectors) on each side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Fq2C2SW53wIb2fEJ_ZsL7g.webp" /></figure><p>The best hyperplane also known as the &quot;hard margin&quot; is the one that maximizes the distance between the hyperplane and the nearest data points from both classes. This ensures a clear separation between the classes. So from the above figure, we choose L2 as hard margin. Let’s consider a scenario like shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Va4S1jDarcNaKkLM5BDNJw.webp" /></figure><p>Here, we have one blue ball in the boundary of the red ball.</p><p>How does SVM classify the data?</p><p>The blue ball in the boundary of red ones is an outlier of blue balls. The SVM algorithm has the characteristics to ignore the outlier and finds the best hyperplane that maximizes the margin. SVM is robust to outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*_WA86CH-U51WXTwtfipufw.webp" /></figure><p>A soft margin allows for some misclassifications or violations of the margin to improve generalization. The SVM optimizes the following equation to balance margin maximization and penalty minimization:</p><p>Objective Function=(1margin)+λ∑penalty Objective Function=(margin1​)+λ∑penalty</p><p>The penalty used for violations is often <a href="https://www.geeksforgeeks.org/machine-learning/hinge-loss-relationship-with-support-vector-machines/">hinge loss</a> which has the following behavior:</p><p>If a data point is correctly classified and within the margin there is no penalty (loss = 0).</p><p>If a point is incorrectly classified or violates the margin the hinge loss increases proportionally to the distance of the violation.</p><p>Till now we were talking about linearly separable data that seprates group of blue balls and red balls by a straight line/linear line.</p><p>What if data is not linearly separable?</p><p>When data is not linearly separable i.e it can&#39;t be divided by a straight line, SVM uses a technique called <a href="https://www.geeksforgeeks.org/machine-learning/major-kernel-functions-in-support-vector-machine-svm/">kernels</a> to map the data into a higher-dimensional space where it becomes separable. This transformation helps SVM find a decision boundary even for non-linear data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*SXb7QHikR1q468HwbpPfrg.webp" /></figure><p>A kernel is a function that maps data points into a higher-dimensional space without explicitly computing the coordinates in that space. This allows SVM to work efficiently with non-linear data by implicitly performing the mapping. For example consider data points that are not linearly separable. By applying a kernel function SVM transforms the data points into a higher-dimensional space where they become linearly separable.</p><p>Linear Kernel: For linear separability.</p><p>Polynomial Kernel: Maps data into a polynomial space.</p><p>Radial Basis Function (RBF) Kernel: Transforms data into a space based on distances between data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*W0OE94X8T34bPjPuhgOirw.webp" /></figure><p><a href="https://www.geeksforgeeks.org/machine-learning/python-for-machine-learning/">Python for Machine Learning</a></p><p><a href="https://www.geeksforgeeks.org/r-machine-learning/introduction-to-machine-learning-in-r/">Machine Learning with R</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/machine-learning-algorithms/">Machine Learning Algorithms</a></p><p><a href="https://www.geeksforgeeks.org/data-analysis/what-is-exploratory-data-analysis/">EDA</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/machine-learning-mathematics/">Math for Machine Learning</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/machine-learning-interview-questions/">Machine Learning Interview Questions</a></p><p><a href="https://www.geeksforgeeks.org/machine-learning/machine-learning-projects/">ML Projects</a></p><p><a href="https://www.geeksforgeeks.org/deep-learning/deep-learning-tutorial/">Deep Learning</a></p><p><a href="https://www.geeksforgeeks.org/nlp/natural-language-processing-nlp-tutorial/">NLP</a></p><p><a href="https://www.geeksforgeeks.org/computer-vision/computer-vision/">Computer vision</a></p><p>Support Vector Machine (SVM) Algorithm</p><p>Last Updated : 13 Nov, 2025</p><p>Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or cat vs. dog.</p><p>The main goal of SVM is to maximize the margin between the two classes. The larger the margin the better the model performs on new and unseen data.</p><p>Key Concepts of Support Vector Machine</p><p>Hyperplane: A decision boundary separating different classes in feature space and is represented by the equation wx + b = 0 in linear classification.</p><p>Support Vectors: The closest data points to the hyperplane, crucial for determining the hyperplane and margin in SVM.</p><p>Margin: The distance between the hyperplane and the support vectors. SVM aims to maximize this margin for better classification performance.</p><p>Kernel: A function that maps data to a higher-dimensional space enabling SVM to handle non-linearly separable data.</p><p>Hard Margin: A maximum-margin hyperplane that perfectly separates the data without misclassifications.</p><p>Soft Margin: Allows some misclassifications by introducing slack variables, balancing margin maximization and misclassification penalties when data is not perfectly separable.</p><p>C: A regularization term balancing margin maximization and misclassification penalties. A higher C value forces stricter penalty for misclassifications.</p><p>Hinge Loss: A loss function penalizing misclassified points or margin violations and is combined with regularization in SVM.</p><p>Dual Problem: Involves solving for Lagrange multipliers associated with support vectors, facilitating the kernel trick and efficient computation.</p><p>How does Support Vector Machine Algorithm Work?</p><p>The key idea behind the SVM algorithm is to find the hyperplane that best separates two classes by maximizing the margin between them. This margin is the distance from the hyperplane to the nearest data points (support vectors) on each side.</p><p>Multiple hyperplanes separate the data from two classes</p><p>The best hyperplane also known as the &quot;hard margin&quot; is the one that maximizes the distance between the hyperplane and the nearest data points from both classes. This ensures a clear separation between the classes. So from the above figure, we choose L2 as hard margin. Let&#39;s consider a scenario like shown below:</p><p>Selecting hyperplane for data with outlier</p><p>Here, we have one blue ball in the boundary of the red ball.</p><p>How does SVM classify the data?</p><p>The blue ball in the boundary of red ones is an outlier of blue balls. The SVM algorithm has the characteristics to ignore the outlier and finds the best hyperplane that maximizes the margin. SVM is robust to outliers.</p><p>Hyperplane which is the most optimized one</p><p>A soft margin allows for some misclassifications or violations of the margin to improve generalization. The SVM optimizes the following equation to balance margin maximization and penalty minimization:</p><p>Objective Function=(1margin)+λ∑penalty Objective Function=(margin1​)+λ∑penalty</p><p>The penalty used for violations is often <a href="https://www.geeksforgeeks.org/machine-learning/hinge-loss-relationship-with-support-vector-machines/">hinge loss</a> which has the following behavior:</p><p>If a data point is correctly classified and within the margin there is no penalty (loss = 0).</p><p>If a point is incorrectly classified or violates the margin the hinge loss increases proportionally to the distance of the violation.</p><p>Till now we were talking about linearly separable data that seprates group of blue balls and red balls by a straight line/linear line.</p><p>What if data is not linearly separable?</p><p>When data is not linearly separable i.e it can&#39;t be divided by a straight line, SVM uses a technique called <a href="https://www.geeksforgeeks.org/machine-learning/major-kernel-functions-in-support-vector-machine-svm/">kernels</a> to map the data into a higher-dimensional space where it becomes separable. This transformation helps SVM find a decision boundary even for non-linear data.</p><p>Original 1D dataset for classification</p><p>A kernel is a function that maps data points into a higher-dimensional space without explicitly computing the coordinates in that space. This allows SVM to work efficiently with non-linear data by implicitly performing the mapping. For example consider data points that are not linearly separable. By applying a kernel function SVM transforms the data points into a higher-dimensional space where they become linearly separable.</p><p>Linear Kernel: For linear separability.</p><p>Polynomial Kernel: Maps data into a polynomial space.</p><p>Radial Basis Function (RBF) Kernel: Transforms data into a space based on distances between data points.</p><p>Mapping 1D data to 2D to become able to separate the two classes</p><p>In this case the new variable y is created as a function of distance from the origin.</p><p>Mathematical Computation of SVM</p><p>Consider a binary classification problem with two classes, labeled as +1 and -1. We have a training dataset consisting of input feature vectors X and their corresponding class labels Y. The equation for the linear hyperplane can be written as:</p><p>wTx+b=0wTx+b=0</p><p>Where:</p><p>ww is the normal vector to the hyperplane (the direction perpendicular to it).</p><p>bb is the offset or bias term representing the distance of the hyperplane from the origin along the normal vector ww.</p><p>Distance from a Data Point to the Hyperplane</p><p>The distance between a data point xixi​and the decision boundary can be calculated as:</p><p>di=wTxi+b∣∣w∣∣di​=∣∣w∣∣wTxi​+b​</p><p>where ||w|| represents the Euclidean norm of the weight vector w.</p><p>Linear SVM Classifier</p><p>Distance from a Data Point to the Hyperplane:</p><p>y^={1: wTx+b≥0−1: wTx+b &lt;0y^​={1−1​: wTx+b≥0: wTx+b &lt;0​</p><p>Where y^y^​ is the predicted label of a data point.</p><p>Optimization Problem for SVM</p><p>For a linearly separable dataset the goal is to find the hyperplane that maximizes the margin between the two classes while ensuring that all data points are correctly classified. This leads to the following optimization problem:</p><p>minimizew,b12∥w∥2w,bminimize​21​∥w∥2</p><p>Subject to the constraint:</p><p>yi(wTxi+b)≥1fori=1,2,3,⋯,myi​(wTxi​+b)≥1fori=1,2,3,⋯,m</p><p>Where:</p><p>yiyi​​ is the class label (+1 or -1) for each training instance.</p><p>xixi​​ is the feature vector for the ii-th training instance.</p><p>mm is the total number of training instances.</p><p>The condition yi(wTxi+b)≥1yi​(wTxi​+b)≥1 ensures that each data point is correctly classified and lies outside the margin.</p><p>Soft Margin in Linear SVM Classifier</p><p>In the presence of outliers or non-separable data the SVM allows some misclassification by introducing slack variables ζiζi​​. The optimization problem is modified as:</p><p>minimize w,b12∥w∥2+C∑i=1mζiw,bminimize ​21​∥w∥2+C∑i=1m​ζi​</p><p>Subject to the constraints:</p><p>yi(wTxi+b)≥1−ζiandζi≥0for i=1,2,…,myi​(wTxi​+b)≥1−ζi​andζi​≥0for i=1,2,…,m</p><p>Where:</p><p>CC is a regularization parameter that controls the trade-off between margin maximization and penalty for misclassifications.</p><p>ζiζi​​ are slack variables that represent the degree of violation of the margin by each data point.</p><p>Dual Problem for SVM</p><p>The dual problem involves maximizing the Lagrange multipliers associated with the support vectors. This transformation allows solving the SVM optimization using kernel functions for non-linear classification.</p><p>The dual objective function is given by:</p><p>maximize α12∑i=1m∑j=1mαiαjtitjK(xi,xj)−∑i=1mαiαmaximize ​21​∑i=1m​∑j=1m​αi​αj​ti​tj​K(xi​,xj​)−∑i=1m​αi​</p><p>Where:</p><p>αiαi​​ are the Lagrange multipliers associated with the ithith training sample.</p><p>titi​​ is the class label for the ithith-th training sample.</p><p>K(xi,xj)K(xi​,xj​) is the kernel function that computes the similarity between data points xixi​​ and xjxj​​. The kernel allows SVM to handle non-linear classification problems by mapping data into a higher-dimensional space.</p><p>The dual formulation optimizes the Lagrange multipliers αiαi​​ and the support vectors are those training samples where αi&gt;0αi​&gt;0.</p><p>SVM Decision Boundary</p><p>Once the dual problem is solved, the decision boundary is given by:</p><p>w=∑i=1mαitiK(xi,x)+bw=∑i=1m​αi​ti​K(xi​,x)+b</p><p>Where ww is the weight vector, xx is the test data point and bb is the bias term. Finally the bias term bb is determined by the support vectors, which satisfy:</p><p>ti(wTxi−b)=1⇒b=wTxi−titi​(wTxi​−b)=1⇒b=wTxi​−ti​</p><p>Where xixi​​ is any support vector.</p><p>This completes the mathematical framework of the Support Vector Machine algorithm which allows for both linear and non-linear classification using the dual problem and kernel trick.</p><p>Types of Support Vector Machine</p><p>Based on the nature of the decision boundary, Support Vector Machines (SVM) can be divided into two main parts:</p><p>Linear SVM: Linear SVMs use a linear decision boundary to separate the data points of different classes. When the data can be precisely linearly separated, linear SVMs are very suitable. This means that a single straight line (in 2D) or a hyperplane (in higher dimensions) can entirely divide the data points into their respective classes. A hyperplane that maximizes the margin between the classes is the decision boundary.</p><p>Non-Linear SVM: <a href="https://www.geeksforgeeks.org/machine-learning/ml-non-linear-svm/">Non-Linear SVM</a> can be used to classify data when it cannot be separated into two classes by a straight line (in the case of 2D). By using kernel functions, nonlinear SVMs can handle nonlinearly separable data. The original input data is transformed by these kernel functions into a higher-dimensional feature space where the data points can be linearly separated. A linear SVM is used to locate a nonlinear decision boundary in this modified space.</p><p>Implementing SVM Algorithm Using Scikit-Learn</p><p>We will predict whether cancer is Benign or Malignant using historical data about patients diagnosed with cancer. This data includes independent attributes such as tumor size, texture, and others. To perform this classification, we will use an SVM (Support Vector Machine) classifier to differentiate between benign and malignant cases effectively.</p><p>load_breast_cancer(): Loads the breast cancer dataset (features and target labels).</p><p>SVC(kernel=&quot;linear&quot;, C=1): Creates a Support Vector Classifier with a linear kernel and regularization parameter C=1.</p><p>svm.fit(X, y): Trains the SVM model on the feature matrix X and target labels y.</p><p>DecisionBoundaryDisplay.from_estimator(): Visualizes the decision boundary of the trained model with a specified color map.</p><p>plt.scatter(): Creates a scatter plot of the data points, colored by their labels.</p><p>plt.show(): Displays the plot to the screen.</p><p>from sklearn.datasets import load_breast_cancer<br>import matplotlib.pyplot as plt<br>from sklearn.inspection import DecisionBoundaryDisplay<br>from sklearn.svm import SVC</p><p>cancer = load_breast_cancer()<br>X = cancer.data[:, :2]<br>y = cancer.target</p><p>svm = SVC(kernel=&quot;linear&quot;, C=1)<br>svm.fit(X, y)</p><p>DecisionBoundaryDisplay.from_estimator(<br> svm,<br> X,<br> response_method=&quot;predict&quot;,<br> alpha=0.8,<br> cmap=&quot;Pastel1&quot;,<br> xlabel=cancer.feature_names[0],<br> ylabel=cancer.feature_names[1],<br> )</p><p>plt.scatter(X[:, 0], X[:, 1], <br> c=y, <br> s=20, edgecolors=&quot;k&quot;)<br>plt.show()</p><p>Advantages of Support Vector Machine (SVM)</p><p>High-Dimensional Performance: SVM excels in high-dimensional spaces, making it suitable for image classification and gene expression analysis.</p><p>Nonlinear Capability: Utilizing kernel functions like RBF and polynomial SVM effectively handles nonlinear relationships.</p><p>Outlier Resilience: The soft margin feature allows SVM to ignore outliers, enhancing robustness in spam detection and anomaly detection.</p><p>Binary and Multiclass Support: SVM is effective for both binary classification and multiclass classification suitable for applications in text classification.</p><p>Memory Efficiency: It focuses on support vectors making it memory efficient compared to other algorithms.</p><p>Disadvantages of Support Vector Machine (SVM)</p><p>Slow Training: SVM can be slow for large datasets, affecting performance in SVM in data mining tasks.</p><p>Parameter Tuning Difficulty: Selecting the right kernel and adjusting parameters like C requires careful tuning, impacting SVM algorithms.</p><p>Noise Sensitivity: SVM struggles with noisy datasets and overlapping classes, limiting effectiveness in real-world scenarios.</p><p>Limited Interpretability: The complexity of the hyperplane in higher dimensions makes SVM less interpretable than other models.</p><p>Feature Scaling Sensitivity: Proper feature scaling is essential, otherwise SVM models may perform poorly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=338e782b012c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Confusion Matrix]]></title>
            <link>https://medium.com/@tanya.dav5301/confusion-matrix-79ab212be07a?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/79ab212be07a</guid>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[virtual-reality]]></category>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 23:58:14 GMT</pubDate>
            <atom:updated>2025-12-23T23:58:14.228Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a confusion matrix?</h3><p>The confusion matrix helps assess classification model performance in machine learning by comparing predicted values against actual values for a dataset.</p><p>A confusion matrix (or, error matrix) is a visualization method for classifier algorithm results. More specifically, it is a table that breaks down the number of ground truth instances of a specific class against the number of predicted class instances. Confusion matrices are one of several evaluation metrics measuring the performance of a classification model. They can be used to calculate a number of other model performance metrics, such as precision and recall, among others.</p><p>Confusion matrices can be used with any classifier algorithm, such as <a href="https://www.ibm.com/topics/naive-bayes">Naïve Bayes</a>, <a href="https://www.ibm.com/topics/logistic-regression">logistic regression</a> models, <a href="https://www.ibm.com/topics/decision-trees">decision trees</a>, and so forth. Because of their wide applicability in <a href="https://www.ibm.com/topics/data-science">data science</a> and <a href="https://www.ibm.com/topics/machine-learning">machine learning</a> models, many packages and libraries come preloaded with functions for creating confusion matrices, such Scikit-learn’s ,Sklearn.metrics module for Python.</p><h3>The confusion matrix layout</h3><p>In a confusion matrix, columns represent the predicted values of a given class while rows represent the actual values (i.e. ground truth) of a given class, or vice-versa. Note that the reverse also appears in research. This grid structure is a convenient tool for visualizing model classification accuracy by displaying the number of correct predictions and incorrect predictions for all classes alongside one another.</p><p>A standard confusion matrix template for a binary classifier may look like this:</p><p>The top-left box provides the number of true positives (TP), being the number of correct predictions for the positive class. The box beneath it is false positives (FP), those negative-class instances incorrectly identified as positive cases. These are also called type I errors in statistics. The top-right box is the number of false negatives (FN), the actual positive instances erroneously predicted negative. Finally, the bottom-right box displays the number of true negatives (TN), which are the actual negative class instances accurately predicted negative. Totaling up each of these values would provide the model’s total number of predictions.</p><p>Of course, this template is for a rudimentary binary classification problem. The confusion matrix can visualize results for multiclass classification problems as well. For example, imagine that we are developing a species classification model as part of a marine life conservation program. The model predicts fish species. A confusion matrix for such a multiclass classification problem may look like this:</p><p>The diagonal boxes all indicate true predicted positives. The other boxes provide quantities for false positives, false negatives, and true negatives depending on which class one chooses to focus.</p><h3>Using the confusion matrix for model evaluation</h3><p>Given its readily accessible visualization of classifier predictive results, the confusion matrix is useful for calculating other model evaluation metrics. Values can simply be pulled from the matrix and plugged into a number of equations for measuring model performance.</p><h3>Accuracy</h3><p>Model accuracy is not a wholly informative evaluation metric for classifiers. For instance, imagine we run a classifier on a data set of 100 instances. The model’s confusion matrix shows only one false negative and no false positives; the model correctly classifies every other data instance. Thus the model has an accuracy of 99%. Though ostensibly desirable, high accuracy is not in itself indicative of excellent model performance. For instance, say our model aims to classify highly contagious diseases. That 1% misclassification poses an enormous risk. Thus, other evaluation metrics can be used to provide a better picture of classification algorithm performance.</p><h3>Precision and recall</h3><p>Precision is the proportion of positive class predictions that actually belong to the class in question. Another way of understanding precision is that it measures the likelihood a randomly chosen instance belongs to a certain class.3 Precision may also be called <em>positive predicted value</em> (PPV). It is represented by the equation:</p><h3>F1 score</h3><p>Precision and recall can share an inverse relationship at times. As a model increases recall by returning more actual class instances (i.e. true positives), the model will inevitably misclassify non-instances (i.e. false positives) as well, thereby decreasing precision. The F1 score attempts to combine precision and recall to resolve this tradeoff.</p><p>The F1 score — also called <em>F-score</em>, <em>F-measure</em>, or the <em>harmonic mean of precision and recall</em> — combines precision and recall to represent a model’s total class-wise accuracy. Using these two values, one can calculate the F1 score with the equation, where P denotes precision (PPV) and R denotes recall (sensitivity):</p><p>The F1 score is particularly useful for imbalanced datasets, in which the precision-recall tradeoff can be most apparent. For example, say we have a classifier predicting the likelihood of a rare disease. A model that predicts no one in our test dataset has the disease may have perfect precision yet zero recall. Meanwhile, a model that predicts everyone in our dataset has the disease would return perfect recall but precision equal to the percentage of people who actually have the disease (e.g. 0.00001% if only one in every ten million have the disease). The F1 score is a means of balancing these two values to obtain a more holistic view of a classifier’s performance.7</p><p>Some researchers criticize the use of the F1 score as a performance metric. Such arguments typically claim that the F1 score gives equal weight to precision and recall, which may not be equally important performance metrics for all datasets.8 In response, researchers have proffered modified variants of the F1 score.9</p><h3>Conditional measures</h3><p>Conditional measures signify a model’s accuracy rate for detecting a certain class or non-class. Recall, also known as <em>true positive rate</em> (TPR) or <em>sensitivity</em>, is one such measure, indicating the ratio of positive class predictions out of all actual class instances. Specificity — or, <em>true negative rate</em> (TNR) — is the other conditional measure. It measures the proportion of correct negative predictions out of actual non-instances of a given class. One can compute specificity with the equation:10</p><h3>False positive rate</h3><p>Specificity helps calculate a model’s false positive rate (FPR). Other classifier evaluation visualizations, notably ROC curve and AUC, utilize FPR. FPR is the probability that a model will falsely classify a non-instance of a certain class as part of that class. Thus, per its name, it represents the rate at which a model returns false positives, known as <em>type I errors</em> in statistics.</p><p>While type I errors refer to false positives, type II errors denote false negatives, actual instances of a given class erroneously classified as not part of that class. Per its name, the false negative rate (FNR) denotes the probability a model erroneously classifies an actual class instance as not part of that class. Much as FPR corresponds to specificity, FNR corresponds to sensitivity:</p><p>Note that FNR is often not used in literature because it requires knowing the total number of actual instances for a given class, which can remain unknown in unseen test datasets.11</p><h3>Unconditional metrics</h3><p>Unconditional metrics are those that represent the chances of a specific class occurring or not occurring according to the model. Precision or, positive predicted value (PPV) is one unconditional metric. As mentioned, it measures the likelihood that a chosen instance belongs to a certain class. The other unconditional metric, negative predicted value (NPV), is the probability that a chosen instance will not belong to that class. Essentially, both unconditional metrics attempt to answer whether a randomly chosen instance will belong to a specific class or not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79ab212be07a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Tree in Machine Learning]]></title>
            <link>https://medium.com/@tanya.dav5301/decision-tree-in-machine-learning-4b2c24420f3a?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b2c24420f3a</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 14:13:27 GMT</pubDate>
            <atom:updated>2025-12-23T14:13:27.289Z</atom:updated>
            <content:encoded><![CDATA[<p>A decision tree is a supervised learning algorithm used for both classification and regression tasks. It has a hierarchical tree structure which consists of a root node, branches, internal nodes and leaf nodes. It works like a flowchart help to make decisions step by step where:</p><ul><li>Internal nodes represent attribute tests</li><li>Branches represent attribute values</li><li>Leaf nodes represent final decisions or predictions.</li></ul><h3>How Does a Decision Tree Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rgxi3J3uiUVfLN72.png" /></figure><p><strong>1. Root Node (Income)</strong></p><p><strong>First Question</strong>: <strong>“Is the person’s income greater than $50,000?”</strong></p><ul><li>If Yes, proceed to the next question.</li><li>If No, predict “No Purchase” (leaf node).</li></ul><p><strong>2. Internal Node (Age)</strong>:</p><p><strong>If the person’s income is greater than $50,000</strong>, ask: <strong>“Is the person’s age above 30?”</strong></p><ul><li>If Yes, proceed to the next question.</li><li>If No, predict “No Purchase” (leaf node).</li></ul><p><strong>3. Internal Node (Previous Purchases)</strong>:</p><ul><li>If the person is above 30 and has made previous purchases, predict “Purchase” (leaf node).</li><li>If the person is above 30 and has not made previous purchases, predict “No Purchase” (leaf node).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PCSR2CWVjehKW8Ae.png" /></figure><h3>Tree 1: Customer Demographics</h3><p>First tree asks two questions:</p><p>1. “Income &gt; $50,000?”</p><ul><li>If Yes, Proceed to the next question.</li><li>If No, “No Purchase”</li></ul><p>2. “Age &gt; 30?”</p><ul><li>Yes: “Purchase”</li><li>No: “No Purchase”</li></ul><h3>Tree 2: Previous Purchases</h3><p>“Previous Purchases &gt; 0?”</p><ul><li>Yes: “Purchase”</li><li>No: “No Purchase”</li></ul><p>Once we have predictions from both trees, we can combine the results to make a final prediction. If Tree 1 predicts “Purchase” and Tree 2 predicts “No Purchase”, the final prediction might be “Purchase” or “No Purchase” depending on the weight or confidence assigned to each tree. This can be decided based on the problem context.</p><h3>Information Gain and Gini Index in Decision Tree</h3><p>Till now we have discovered the basic intuition and approach of how decision tree works, so lets just move to the attribute selection measure of decision tree. We have two popular attribute selection measures used:</p><h3>1. Information Gain</h3><p>Information Gain tells us how useful a question (or feature) is for splitting data into groups. It measures how much the uncertainty decreases after the split. A good question will create clearer groups and the feature with the highest Information Gain is chosen to make the decision.</p><p>For example if we split a dataset of people into “Young” and “Old” based on age and all young people bought the product while all old people did not, the Information Gain would be high because the split perfectly separates the two groups with no uncertainty left</p><ul><li>Suppose S<em>S</em> is a set of instances A<em>A</em> is an attribute, Sv<em>Sv</em> is the subset of S<em>S, </em>v<em>v</em> represents an individual value that the attribute A<em>A</em> can take and Values (A<em>A</em>) is the set of all possible values of A<em>A</em> then</li></ul><blockquote><em>Gain(S,A)=Entropy(S)−∑vA∣Sv∣∣S∣.Entropy(Sv)</em>Gain<em>(</em>S<em>,</em>A<em>)=</em>Entropy<em>(</em>S<em>)−∑</em>vA<em>​∣</em>S<em>∣∣</em>Sv<em>​∣​.</em>Entropy<em>(</em>Sv<em>​)</em></blockquote><ul><li><strong>Entropy:</strong> is the measure of uncertainty of a random variable it characterizes the impurity of an arbitrary collection of examples. The higher the entropy more the information content.</li></ul><p>For example if a dataset has an equal number of “Yes” and “No” outcomes (like 3 people who bought a product and 3 who didn’t), the entropy is high because it’s uncertain which outcome to predict. But if all the outcomes are the same (all “Yes” or all “No”) the entropy is 0 meaning there is no uncertainty left in predicting the outcome</p><p>Suppose S<em>S</em> is a set of instances, A<em>A</em> is an attribute, Sv<em>Sv</em> is the subset of S<em>S</em> with A<em>A</em>= v<em>v</em> and Values (A<em>A</em>) is the set of all possible values of A<em>A</em>, then</p><blockquote><em>Gain(S,A)=Entropy(S)−∑vϵValues(A)∣Sv∣∣S∣.Entropy(Sv) </em>Gain<em>(</em>S<em>,</em>A<em>)=</em>Entropy<em>(</em>S<em>)−∑</em>vϵValues<em>(</em>A<em>)​∣</em>S<em>∣∣</em>Sv<em>​∣​.</em>Entropy<em>(</em>Sv<em>​)</em></blockquote><p><strong>Example:</strong></p><blockquote>For the set X = {a,a,a,b,b,b,b,b}<br>Total instances: 8<br>Instances of b: 5<br>Instances of a: 3</blockquote><blockquote><em>Entropy H(X)=[(38)log⁡238+(58)log⁡258]=−[0.375(−1.415)+0.625(−0.678)]=−(−0.53−0.424)=0.954Entropy </em>H<em>(</em>X<em>)​=[(83​)log2​83​+(85​)log2​85​]=−[0.375(−1.415)+0.625(−0.678)]=−(−0.53−0.424)=0.954​</em></blockquote><h3>Building Decision Tree using Information Gain the essentials</h3><ul><li>Start with all training instances associated with the root node</li><li>Use info gain to choose which attribute to label each node with</li><li>Recursively construct each subtree on the subset of training instances that would be classified down that path in the tree.</li><li>If all positive or all negative training instances remain, the label that node “yes” or “no” accordingly</li><li>If no attributes remain label with a majority vote of training instances left at that node</li><li>If no instances remain label with a majority vote of the parent’s training instances.</li></ul><p><strong>Example:</strong> Now let us draw a Decision Tree for the following data using Information gain. Training set: 3 features and 2 classes</p><p>XYZC111I110I001II100II</p><p>Here, we have 3 features and 2 output classes. To build a decision tree using Information gain. We will take each of the features and calculate the information for each feature.</p><p>From the above images we can see that the information gain is <strong>maximum</strong> when we make a split on feature Y. So, for the root node best-suited feature is feature Y. Now we can see that while splitting the dataset by feature Y, the child contains a pure subset of the target variable. So we don’t need to further split the dataset. The final tree for the above dataset would look like this:</p><h3>2. Gini Index</h3><p>Gini Index is a metric to measure how often a randomly chosen element would be incorrectly identified. It means an attribute with a lower Gini index should be preferred. Sklearn supports “Gini” criteria for Gini Index and by default it takes “gini” value.</p><p>For example if we have a group of people where all bought the product (100% “Yes”) the Gini Index is 0 indicate perfect purity. But if the group has an equal mix of “Yes” and “No” the Gini Index would be 0.5 show high impurity or uncertainty. Formula for Gini Index is given by :</p><blockquote><em>Gini=1−∑i=1npi2</em>Gini<em>=1−∑</em>i<em>=1</em>n<em>​</em>pi<em>2​</em></blockquote><h3>Some additional features of the Gini Index are:</h3><ol><li>It is calculated by summing the squared probabilities of each outcome in a distribution and subtracting the result from 1.</li><li>A lower Gini Index indicates a more homogeneous or pure distribution while a higher Gini Index indicates a more heterogeneous or impure distribution.</li><li>In decision trees the Gini Index is used to evaluate the quality of a split by measuring the difference between the impurity of the parent node and the weighted impurity of the child nodes.</li><li>Compared to other impurity measures like entropy, the Gini Index is faster to compute and more sensitive to changes in class probabilities.</li><li>One disadvantage of the Gini Index is that it tends to favour splits that create equally sized child nodes, even if they are not optimal for classification accuracy.</li><li>In practice the choice between using the Gini Index or other impurity measures depends on the specific problem and dataset and requires experimentation and tuning.</li></ol><h3>Understanding Decision Tree with Real life use case:</h3><p>Till now we have understand about the attributes and components of decision tree. Now lets jump to a real life use case in which how decision tree works step by step.</p><h3>Step 1. Start with the Whole Dataset</h3><p>We begin with all the data which is treated as the root node of the decision tree.</p><h3>Step 2. Choose the Best Question (Attribute)</h3><p>Pick the best question to divide the dataset. For example ask: <em>“What is the outlook?”</em></p><blockquote>Possible answers: Sunny, Cloudy or Rainy.</blockquote><h3>Step 3. Split the Data into Subsets</h3><p>Divide the dataset into groups based on the question:</p><ul><li>If Sunny go to one subset.</li><li>If Cloudy go to another subset.</li><li>If Rainy go to the last subset.</li></ul><h3>Step 4. Split Further if Needed (Recursive Splitting)</h3><p>For each subset ask another question to refine the groups. For example If the Sunny subset is mixed ask: <em>“Is the humidity high or normal?”</em></p><ul><li>High humidity → “Swimming”.</li><li>Normal humidity → “Hiking”.</li></ul><h3>Step 5. Assign Final Decisions (Leaf Nodes)</h3><p>When a subset contains only one activity, stop splitting and assign it a label:</p><ul><li>Cloudy → “Hiking”.</li><li>Rainy → “Stay Inside”.</li><li>Sunny + High Humidity → “Swimming”.</li><li>Sunny + Normal Humidity → “Hiking”.</li></ul><h3>Step 6. Use the Tree for Predictions</h3><p>To predict an activity follow the branches of the tree. Example: If the outlook is Sunny and the humidity is High follow the tree:</p><ul><li>Start at <em>Outlook</em>.</li><li>Take the branch for Sunny.</li><li>Then go to <em>Humidity</em> and take the branch for High Humidity.</li><li>Result: “Swimming”.</li></ul><p>A decision tree works by breaking down data step by step asking the best possible questions at each point and stopping once it reaches a clear decision. It’s an easy and understandable way to make choices. Because of their simple and clear structure decision trees are very helpful in machine learning for tasks like sorting data into categories or making predictions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b2c24420f3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Confusion Matrix in Machine Learning]]></title>
            <link>https://medium.com/@tanya.dav5301/understanding-the-confusion-matrix-in-machine-learning-a8bbb97243a4?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8bbb97243a4</guid>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[machine-learning-tools]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 03:07:24 GMT</pubDate>
            <atom:updated>2025-12-21T03:07:24.576Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Confusion matrix</strong> is a simple table used to measure how well a classification model is performing. It compares the predictions made by the model with the actual results and shows where the model was right or wrong. This helps you understand where the model is making mistakes so you can improve it. It breaks down the predictions into four categories:</p><ul><li><strong>True Positive (TP):</strong> The model correctly predicted a positive outcome i.e the actual outcome was positive.</li><li><strong>True Negative (TN):</strong> The model correctly predicted a negative outcome i.e the actual outcome was negative.</li><li><strong>False Positive (FP):</strong> The model incorrectly predicted a positive outcome i.e the actual outcome was negative. It is also known as a Type I error.</li><li><strong>False Negative (FN):</strong> The model incorrectly predicted a negative outcome i.e the actual outcome was positive. It is also known as a Type II error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*LxV7pOjbVeQuXHs5" /></figure><p>It also helps calculate key measures like <strong>accuracy</strong>, <strong>precision </strong>and <strong>recall</strong> which give a better idea of performance especially when the data is imbalanced.</p><h3>Metrics based on Confusion Matrix Data</h3><h3>1. Accuracy</h3><p><a href="https://www.geeksforgeeks.org/data-analysis/techniques-to-evaluate-accuracy-of-classifier-in-data-mining/">Accuracy</a> shows how many predictions the model got right out of all the predictions. It gives idea of overall performance but it can be misleading when one class is more dominant over the other. For example a model that predicts the majority class correctly most of the time might have high accuracy but still fail to capture important details about other classes. It can be calculated using the below formula:</p><p>Accuracy=<em>TP</em>+<em>TN / FP</em>+<em>FNTP</em>+<em>TN</em></p><h3>2. Precision</h3><p><a href="https://www.geeksforgeeks.org/machine-learning/precision-and-recall-in-machine-learning/">Precision</a> focus on the quality of the model’s positive predictions. It tells us how many of the “positive” predictions were actually correct. It is important in situations where false positives need to be minimized such as detecting spam emails or fraud. The formula of precision is:</p><p>Precision=<em>TP / FP+TP</em></p><h3>3. Recall</h3><p><a href="https://www.geeksforgeeks.org/machine-learning/precision-recall-curve-ml/">Recall</a> measures how how good the model is at predicting positives. It shows the proportion of true positives detected out of all the actual positive instances. High recall is essential when missing positive cases has significant consequences like in medical tests.</p><p>Recall=<em>TP / FNTP</em></p><h3>4. F1-Score</h3><p><a href="https://www.geeksforgeeks.org/r-language/precision-recall-and-f1-score-using-r/">F1-score </a>combines precision and recall into a single metric to balance their trade-off. It provides a better sense of a model’s overall performance particularly for imbalanced datasets. It is helpful when both false positives and false negatives are important though it assumes precision and recall are equally important but in some situations one might matter more than the other.</p><p>F1-Score=<em>Precision*Recall</em>2 / <em>Precision</em>⋅<em>Recall</em></p><h3>5. Specificity</h3><p><a href="https://www.geeksforgeeks.org/r-language/calculate-sensitivity-specificity-and-predictive-values-in-caret/">Specificity</a> is another important metric in the evaluation of classification models particularly in binary classification. It measures the ability of a model to correctly identify negative instances. Specificity is also known as the True Negative Rate Formula is given by:</p><p>Specificity=<em>TN / FP+TN</em></p><h3>6. Type 1 and Type 2 error</h3><h3><a href="https://www.geeksforgeeks.org/maths/type-i-and-type-ii-errors/">Type 1 and Type 2</a> error are:</h3><ul><li><strong>Type 1 error</strong>: It occurs when the model incorrectly predicts a positive instance but the actual instance is negative. This is also known as a <strong>false positive</strong>. Type 1 Errors affect the <strong>precision</strong> of a model which measures the accuracy of positive predictions.<br>Type 1 Error=FP+FP / TN Type 1 Error=FP/TN+FP​</li><li><strong>Type 2 error</strong>: This occurs when the model fails to predict a positive instance even though it is actually positive. This is also known as a <strong>false negative</strong>. Type 2 Errors impact the <strong>recall</strong> of a model which measures how well the model identifies all actual positive cases.<br>Type 2 Error=FN+TP / FN Type 2 Error=<em>TP</em>+<em>FNFN</em></li></ul><h3>Confusion Matrix For Binary Classification</h3><p>A 2x2 Confusion matrix is shown below for the image recognition having a Dog image or Not Dog image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*zKK8CRd2HQye-flv" /></figure><ul><li><strong>True Positive (TP):</strong> It is the total counts having both predicted and actual values are Rabbit.</li><li><strong>True Negative (TN): </strong>It is the total counts having both predicted and actual values are Not Rabbit.</li><li><strong>False Positive (FP): </strong>It is the total counts having prediction is Dog while actually Not Rabbit.</li><li><strong>False Negative (FN): </strong>It is the total counts having prediction is Not Dog while actually, it is Rabbit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZW5mkKsaSK0uzSC0.png" /></figure><ul><li>Actual Rabbit Counts = 6</li><li>Actual Not Rabbit Counts = 4</li><li>True Positive Counts = 5</li><li>False Positive Counts = 1</li><li>True Negative Counts = 3</li><li>False Negative Counts = 1</li></ul><h3>Implementation of Confusion Matrix for Binary classification using Python</h3><p><strong>Step 1: Import the necessary libraries</strong></p><p>import numpy as np<br>from sklearn.metrics import confusion_matrix,classification_report<br>import seaborn as sns<br>import matplotlib.pyplot as plt</p><p><strong>Step 2: Create the NumPy array for actual and predicted labels</strong></p><ul><li><strong>actual:</strong> represents the true labels or the actual classification of the items. In this case it’s a list of 10 items where each entry is either ‘Dog’ or ‘Not Dog’.</li><li><strong>predicted:</strong> represents the predicted labels or the classification made by the model.</li></ul><p>actual = np.array(<br> [‘Dog’,’Dog’,’Dog’,’Not Dog’,’Dog’,’Not Dog’,’Dog’,’Dog’,’Not Dog’,’Not Dog’])<br>predicted = np.array(<br> [‘Dog’,’Not Dog’,’Dog’,’Not Dog’,’Dog’,’Dog’,’Dog’,’Dog’,’Not Dog’,’Not Dog’])</p><p><strong>Step 3: Compute the confusion matrix</strong></p><ul><li><strong>confusion_matrix: </strong>This function from sklearn.metrics computes the confusion matrix which is a table used to evaluate the performance of a classification algorithm. It compares actual and predicted to generate a matrix</li></ul><p>cm = confusion_matrix(actual,predicted)</p><p><strong>Step 4: Plot the confusion matrix with the help of the seaborn heatmap</strong></p><ul><li><strong>sns.heatmap:</strong> This function from <a href="https://www.geeksforgeeks.org/python/introduction-to-seaborn-python/"><strong>Seaborn</strong> </a>is used to create a heatmap of the confusion matrix.</li><li><strong>annot=True:</strong> Display the numerical values in each cell of the heatmap.</li></ul><p>sns.heatmap(cm, <br> annot=True,<br> fmt=’g’, <br> xticklabels=[‘Dog’,’Not Dog’],<br> yticklabels=[‘Dog’,’Not Dog’])<br>plt.ylabel(‘Actual’, fontsize=13)<br>plt.title(‘Confusion Matrix’, fontsize=17, pad=20)<br>plt.gca().xaxis.set_label_position(‘top’) <br>plt.xlabel(‘Prediction’, fontsize=13)<br>plt.gca().xaxis.tick_top()</p><p>plt.gca().figure.subplots_adjust(bottom=0.2)<br>plt.gca().figure.text(0.5, 0.05, ‘Prediction’, ha=’center’, fontsize=13)<br>plt.show()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*k4TJ3wRdQgLAkyZw.PNG" /></figure><p><em>Visualizing the Confusion Matrix</em></p><p><strong>Step 5: Classifications Report based on Confusion Metrics</strong></p><p>print(classification_report(actual, predicted))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*VFEc5jTzCNbzetb1.png" /></figure><h3>Confusion Matrix For Multi-class Classification</h3><h3>Confusion Matrix For Multi-class Classification</h3><p>In <a href="https://www.geeksforgeeks.org/machine-learning/multiclass-classification-using-scikit-learn/"><strong>multi-class classification</strong></a> the confusion matrix is expanded to account for multiple classes.</p><ul><li><strong>Rows</strong> represent the actual classes (ground truth).</li><li><strong>Columns</strong> represent the predicted classes.</li><li>Each cell in the matrix shows how often a specific actual class was predicted as another class.</li></ul><p>For example in a 3-class problem the confusion matrix would be a 3x3 table where each row and column corresponds to one of the classes. It summarizes the model’s performance across all classes in a compact format. Lets consider the below example:</p><h3>Example: Confusion Matrix for Image Classification (Cat, Dog, Horse)</h3><p>The definitions of all the terms (TP, TN, FP and FN) are the same as described in the previous example.</p><p><strong>Example with Numbers:</strong></p><p>Let’s consider the scenario where the model processed 30 images:</p><p>In this scenario:</p><ul><li><strong>Cats:</strong> 8 were correctly identified, 1 was misidentified as a dog and 1 was misidentified as a horse.</li><li><strong>Dogs:</strong> 10 were correctly identified, 2 were misidentified as cats.</li><li><strong>Horses:</strong> 8 were correctly identified, 2 were misidentified as dogs.</li></ul><p>To calculate true negatives, we need to know the total number of images that were NOT cats, dogs or horses. Let’s assume there were 10 such images and the model correctly classified all of them as “not cat,” “not dog,” and “not horse.” Therefore:</p><ul><li><strong>True Negative (TN) Counts:</strong> 10 for each class as the model correctly identified each non-cat/dog/horse image as not belonging to that class</li></ul><h3>Implementation of Confusion Matrix for Multi-Class classification using Python</h3><p><strong>Step 1: Import the necessary libraries</strong></p><p>import numpy as np<br>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, classification_report<br>import matplotlib.pyplot as plt</p><p><strong>Step 2: Create the NumPy array for actual and predicted labels</strong></p><ul><li><strong>y_true:</strong> List of true labels.</li><li><strong>y_pred:</strong> List of predicted labels by the model.</li><li><strong>classes: </strong>A list of class names: ‘Cat’, ‘Dog’ and ‘Horse’</li></ul><p>y_true = [‘Cat’] * 10 + [‘Dog’] * 12 + [‘Horse’] * 10<br>y_pred = [‘Cat’] * 8 + [‘Dog’] + [‘Horse’] + [‘Cat’] * 2 + [‘Dog’] * 10 + [‘Horse’] * 8 + [‘Dog’] * 2<br>classes = [‘Cat’, ‘Dog’, ‘Horse’]</p><p><strong>Step 3: Generate and Visualize the Confusion Matrix</strong></p><ul><li><strong>ConfusionMatrixDisplay: </strong>Creates a display object for the confusion matrix.</li><li><strong>confusion_matrix=cm:</strong> Passes the confusion matrix (cm) to display.</li><li><strong>display_labels=classes:</strong> Sets the labels ([‘Cat’ , ‘Dog’ , ‘Horse’]) or the confusion matrix.</li></ul><p>cm = confusion_matrix(y_true, y_pred, labels=classes)<br>disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=classes)<br>disp.plot(cmap=plt.cm.Blues)<br>plt.title(‘Confusion Matrix’, fontsize=15, pad=20)<br>plt.xlabel(‘Prediction’, fontsize=11)<br>plt.ylabel(‘Actual’, fontsize=11)<br>plt.gca().xaxis.set_label_position(‘top’)<br>plt.gca().xaxis.tick_top()<br>plt.gca().figure.subplots_adjust(bottom=0.2)<br>plt.gca().figure.text(0.5, 0.05, ‘Prediction’, ha=’center’, fontsize=13)</p><p>plt.show()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*rbsejNs-SiMux9eT.PNG" /></figure><p><strong>Step 4: Print the Classification Report</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*EnPQlGdFnez8dQBu.png" /></figure><p>Confusion matrix provides clear insights into important metrics like accuracy, precision and recall by analyzing correct and incorrect predictions.</p><h3>​</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8bbb97243a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression]]></title>
            <link>https://medium.com/@tanya.dav5301/logistic-regression-07b61de3e52c?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/07b61de3e52c</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[machie-learning]]></category>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 01:33:05 GMT</pubDate>
            <atom:updated>2025-12-21T01:33:05.364Z</atom:updated>
            <content:encoded><![CDATA[<p>Logistic regression is <strong>a supervised machine learning algorithm that predicts the probability of a categorical outcome (like Yes/No, Spam/Not Spam, 0/1) by modeling the relationship between independent variables and a binary dependent variable, using the sigmoid function (S-curve) to map inputs to a probability between 0 and 1</strong>, making it ideal for classification problems. It determines how likely an event is to occur, unlike linear regression which predicts continuous values.</p><p><strong>Key Concepts</strong></p><ul><li><strong>Supervised Learning:</strong> Uses labeled data (input features and known outcomes) to learn patterns.</li><li><strong>Classification:</strong> Predicts which category an input belongs to, not a specific value.</li><li><strong>Binary Outcome:</strong> Most commonly predicts one of two classes (e.g., True/False, 0/1).</li><li><strong>Sigmoid Function:</strong> Transforms the linear combination of inputs into a probability, creating an S-shaped curve.</li><li><strong>Probability Output:</strong> Results in a value between 0 and 1, indicating the likelihood of the positive class.</li><li><strong>Decision Boundary:</strong> A threshold (often 0.5) is used to classify the outcome (e.g., &amp;gt;0.5 is “Yes”, &amp;lt;0.5 is “No”).</li></ul><p><strong>How it Works (Simplified)</strong></p><ul><li><strong>Input:</strong> Takes independent variables (features like age, income, etc.).</li><li><strong>Linear Combination:</strong> Calculates a weighted sum of these inputs.</li><li><strong>Sigmoid Transformation:</strong> Feeds this sum into the sigmoid function, squeezing the result into a probability.</li><li><strong>Prediction:</strong> Outputs the probability P(Y=1) (e.g., 70% chance of clicking “buy”).</li><li><strong>Classification:</strong> Based on a set threshold, it assigns the final category.</li></ul><p><strong>Applications</strong></p><ul><li>Spam detection (Spam/Not Spam)</li><li>Medical diagnosis (Disease/No Disease)</li><li>Credit risk assessment (Loan Approved/Denied)</li><li>Customer churn prediction (Will Churn/Won’t Churn)</li></ul><p>Logistic regression formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/0*8T8XyDeM2ANjS3OI.png" /></figure><p>Can logistic regression accurately classify Iris flower species using only the first two features (sepal length and width), and what accuracy can we expect on a test set? This tests model performance on a classic multiclass problem.</p><p>import numpy as np<br>from sklearn.datasets import load_iris<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score</p><p># Load dataset (multiclass: 3 species)<br>iris = load_iris()<br>X = iris.data[:, :2] # First two features for simplicity<br>y = iris.target</p><p># Split into train/test (80/20)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</p><p># Train model<br>model = LogisticRegression(random_state=42, max_iter=200)<br>model.fit(X_train, y_train)</p><p># Predict and evaluate<br>y_pred = model.predict(X_test)<br>accuracy = accuracy_score(y_test, y_pred)</p><p>print(“Accuracy:”, accuracy) # Output: 0.9 (90%)<br>print(“Predictions:”, y_pred)<br>print(“Actual:”, y_test)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*V5p_t1wC3ks8NCR4.png" /></figure><p>Running the code yields 90% accuracy on the test set. Predictions like [1 0 2 1 ...] correspond to Iris species (0=setosa, 1=versicolor, 2=virginica), matching most actual labels.</p><h3>Sigmoid function</h3><p>The sigmoid function, also called logistic function, gives an ‘S’ shaped curve that can take any real-valued number and map it into a value between 0 and 1. If the curve goes to positive infinity, y predicted will become 1, and if the curve goes to negative infinity, y predicted will become 0. If the output of the sigmoid function is more than 0.5, we can classify the outcome as 1 or YES, and if it is less than 0.5, we can classify it as 0 or NO. For example, if the output is 0.75, we can say in terms of the probability that there is a 75 percent chance that a patient will suffer from cancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*n4ywkSOjAq7n3oDJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*hF5VaQOLoa-GUZ2U.png" /></figure><h3>Types of Logistic Regression</h3><p>Types of Logistic Regression:</p><ul><li><strong>Binary Logistic Regression</strong>: The target variable has only two possible outcomes such as Spam or Not Spam, Cancer or No Cancer.</li><li><strong>Multinomial Logistic Regression</strong>: The target variable has three or more nominal categories, such as predicting the type of Wine.</li><li><strong>Ordinal Logistic Regression</strong>: the target variable has three or more ordinal categories, such as restaurant or product rating from 1 to 5.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07b61de3e52c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Comprehensive Data Preprocessing and Feature Engineering Workflow Using Pandas and Scikit-Learn”]]></title>
            <link>https://medium.com/@tanya.dav5301/comprehensive-data-preprocessing-and-feature-engineering-workflow-using-pandas-and-scikit-learn-3da2d68e8ce9?source=rss-a77910cdac9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3da2d68e8ce9</guid>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Tanya Verma]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 01:23:07 GMT</pubDate>
            <atom:updated>2025-12-18T01:37:28.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lo3n7nSpibat7D1J.png" /></figure><blockquote>Code:</blockquote><p>import pandas as pd</p><p>import numpy as np</p><p>from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler</p><p>from sklearn.preprocessing import LabelEncoder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G0ToLaEGuknAcFEt.png" /></figure><p><em># Generate random data</em></p><p>data = {</p><p>‘age’: [35,41,23,32,28,36,45,39,44,29],</p><p>‘income’: [‘70000’,’90000&#39;,’50000&#39;,’60000&#39;,’’,’75000&#39;,’100000&#39;,’80000&#39;,’95000&#39;,’55000&#39;],</p><p>‘date’:[‘2020–01–01’,’2020–01–02&#39;,’2020–01–03&#39;,’2020–01–04&#39;,’2020–01–05&#39;,’2020–01–06&#39;,’2020–01–07&#39;,’’,’2020–01–09&#39;,’2020–01–10&#39;],</p><p>‘marital_status’:[‘married’,’single’,’married’,’single’,’married’,’single’,’married’,’single’,’married’,’single’],</p><p>‘gender’:[‘female’,’male’,’male’,’female’,’female’,’male’,’female’,’male’,’male’,’female’]</p><p>}</p><p><em># Convert data to a pandas dataframe and save to CSV file</em></p><p>df = pd.DataFrame(data)</p><p>df.to_csv(‘data.csv’, index=False)</p><p>df = pd.read_csv(‘data.csv’)</p><p>print(df)</p><p>age income date marital_status gender<br>0 35 70000.0 2020–01–01 married female<br>1 41 90000.0 2020–01–02 single male<br>2 23 50000.0 2020–01–03 married male<br>3 32 60000.0 2020–01–04 single female<br>4 28 NaN 2020–01–05 married female<br>5 36 75000.0 2020–01–06 single male<br>6 45 100000.0 2020–01–07 married female<br>7 39 80000.0 NaN single male<br>8 44 95000.0 2020–01–09 married male<br>9 29 55000.0 2020–01–10 single female</p><p>print(df.columns)</p><p>print(df.isnull().sum())</p><p>print(df)</p><p>Index([‘age’, ‘income’, ‘date’, ‘marital_status’, ‘gender’], dtype=’object’)<br>age 0<br>income 1<br>date 1<br>marital_status 0<br>gender 0<br>dtype: int64</p><p>age income date marital_status gender<br>0 35 70000.0 2020–01–01 married female<br>1 41 90000.0 2020–01–02 single male<br>2 23 50000.0 2020–01–03 married male<br>3 32 60000.0 2020–01–04 single female<br>4 28 NaN 2020–01–05 married female<br>5 36 75000.0 2020–01–06 single male<br>6 45 100000.0 2020–01–07 married female<br>7 39 80000.0 NaN single male<br>8 44 95000.0 2020–01–09 married male<br>9 29 55000.0 2020–01–10 single female</p><p>df[‘income’].fillna(df[‘income’].mean(), inplace=True)</p><p>print(df)</p><p>age income date marital_status gender<br>0 35 70000.0 2020–01–01 married female<br>1 41 90000.0 2020–01–02 single male<br>2 23 50000.0 2020–01–03 married male<br>3 32 60000.0 2020–01–04 single female<br>4 28 75000.0 2020–01–05 married female<br>5 36 75000.0 2020–01–06 single male<br>6 45 100000.0 2020–01–07 married female<br>7 39 80000.0 NaN single male<br>8 44 95000.0 2020–01–09 married male<br>9 29 55000.0 2020–01–10 single female</p><p>df[‘date’].fillna(method=’ffill’, inplace=True)</p><p>print(df)</p><p>age income date marital_status gender<br>0 35 70000.0 2020–01–01 married female<br>1 41 90000.0 2020–01–02 single male<br>2 23 50000.0 2020–01–03 married male<br>3 32 60000.0 2020–01–04 single female<br>4 28 75000.0 2020–01–05 married female<br>5 36 75000.0 2020–01–06 single male<br>6 45 100000.0 2020–01–07 married female<br>7 39 80000.0 2020–01–07 single male<br>8 44 95000.0 2020–01–09 married male<br>9 29 55000.0 2020–01–10 single female</p><p>df.dropna(inplace=True)</p><p>print(df)</p><p>age income date marital_status gender<br>0 35 70000.0 2020–01–01 married female<br>1 41 90000.0 2020–01–02 single male<br>2 23 50000.0 2020–01–03 married male<br>3 32 60000.0 2020–01–04 single female<br>4 28 75000.0 2020–01–05 married female<br>5 36 75000.0 2020–01–06 single male<br>6 45 100000.0 2020–01–07 married female<br>7 39 80000.0 2020–01–07 single male<br>8 44 95000.0 2020–01–09 married male<br>9 29 55000.0 2020–01–10 single female</p><p>df1 = df.drop(‘gender’, axis=1)</p><p>print(df1)</p><p>age income date marital_status<br>0 35 70000.0 2020–01–01 married<br>1 41 90000.0 2020–01–02 single<br>2 23 50000.0 2020–01–03 married<br>3 32 60000.0 2020–01–04 single<br>4 28 75000.0 2020–01–05 married<br>5 36 75000.0 2020–01–06 single<br>6 45 100000.0 2020–01–07 married<br>7 39 80000.0 2020–01–07 single<br>8 44 95000.0 2020–01–09 married<br>9 29 55000.0 2020–01–10 single</p><p>df1 = df1.assign(age_squared=lambda x: x[‘age’]**2)</p><p>print(df1)</p><p>age income date marital_status age_squared<br>0 35 70000.0 2020–01–01 married 1225<br>1 41 90000.0 2020–01–02 single 1681<br>2 23 50000.0 2020–01–03 married 529<br>3 32 60000.0 2020–01–04 single 1024<br>4 28 75000.0 2020–01–05 married 784<br>5 36 75000.0 2020–01–06 single 1296<br>6 45 100000.0 2020–01–07 married 2025<br>7 39 80000.0 2020–01–07 single 1521<br>8 44 95000.0 2020–01–09 married 1936<br>9 29 55000.0 2020–01–10 single 841</p><p>df1 = df1.rename(columns={‘income’: ‘annual_income’})</p><p>print(df1.columns)</p><p>Index([‘age’, ‘annual_income’, ‘date’, ‘marital_status’, ‘age_squared’], dtype=’object’)</p><p>scaler = MinMaxScaler()</p><p>df1[‘age’] = scaler.fit_transform(df1[[‘age’]])</p><p>df1</p><p>scaler = StandardScaler()</p><p>df1[[‘annual_income’, ‘age_squared’]] = scaler.fit_transform(df1[[‘annual_income’, ‘age_squared’]])</p><p>df1</p><p>df = pd.get_dummies(df, columns=[‘age’])</p><p>df</p><p>le = LabelEncoder()</p><p>df[[‘marital_status’, ‘gender’]] = df[[‘marital_status’, ‘gender’]].apply(le.fit_transform)</p><p>df</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3da2d68e8ce9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>