<?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 Muhammad Ali Ahson on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Ali Ahson on Medium]]></description>
        <link>https://medium.com/@aliahson?source=rss-a0381c52edeb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nPohUByZik8uxrT7F6OqaA.jpeg</url>
            <title>Stories by Muhammad Ali Ahson on Medium</title>
            <link>https://medium.com/@aliahson?source=rss-a0381c52edeb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:13:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aliahson/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[Decision Tree Classifiers and the Titanic Dataset]]></title>
            <link>https://aliahson.medium.com/decision-tree-classifiers-and-the-titanic-dataset-d0e8a72fd48c?source=rss-a0381c52edeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0e8a72fd48c</guid>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree-classifier]]></category>
            <category><![CDATA[titanic-dataset]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Muhammad Ali Ahson]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 00:58:05 GMT</pubDate>
            <atom:updated>2024-03-31T14:06:12.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EdaEBTFFLFnhOUrF.png" /></figure><p><strong>Introduction:<br></strong> Today, we delve into this dataset with a tool as robust as the story it analyzes — the Decision Tree Classifier. This article aims to guide you through understanding, implementing, and interpreting Decision Tree Classifiers using the Titanic dataset as our vessel.</p><p><strong>Why Use a Decision Tree Classifier?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*zua8cLnn_aSwnyCl" /></figure><p>It’s like choosing between pizza toppings — sometimes it’s easy, sometimes it’s a tough call. Let’s slice through the advantages and drawbacks, keeping it as simple as a cheese slice.</p><h3><strong>Advantages and Disadvantages</strong></h3><p>A Decision Tree Classifier is akin to the branching decision-making process it represents — simple yet profoundly insightful. Here’s why it stands out:</p><p><strong>Advantages:</strong><br><strong>- Interpretability:</strong></p><p>Unlike many black-box models, decision trees are transparent. You can follow the path from root to leaf, understanding the rationale behind each prediction.<br><strong>- No Need for Scaling:</strong></p><p>These models don’t require feature scaling to perform well, making them straightforward to implement on raw data.<br><strong>- Handles Non-linear Relationships:</strong></p><p>They can capture non-linear relationships without needing transformations, a boon for complex datasets.<br>- <strong>Versatility:</strong></p><p>Capable of handling both numerical and categorical data, making them a versatile tool for diverse datasets.</p><p><strong>Disadvantages:</strong></p><p>- <strong>Overfitting:</strong></p><p>Without constraints, trees can grow complex and overfit the training data, capturing noise instead of signal.<br><strong>- Instability:</strong></p><p>Small changes in the data can lead to different splits, making the model sensitive to the training set.<br><strong>- Biased to Dominant Classes:</strong></p><p>They can create biased trees if some classes dominate.</p><h3><strong>Explain the Code:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/0*PY29hd-BlIRQSDON" /></figure><p>I may not be Andrew Ng, but I’ll channel my inner educator for you in this segment. Let’s unravel the process of applying a Decision Tree Classifier to the Titanic dataset. We’re aiming to predict survival using features like class, sex, age, and more. Here’s a straightforward breakdown of the steps:</p><p><strong>Data Preparation:</strong></p><p>Import necessary libraries (pandas, numpy, sklearn) and load the dataset. Clean the data by handling missing values and converting categorical variables into numerical ones.</p><p>It’s a visual Representation of the Nan values in the dataset in Age and Cabin Columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*GkjV9CchgyhtYZhgPz9Tcw.png" /></figure><p>Given the extensive presence of missing values in the Cabin column, attempting to impute them would likely lead to unreliable outcomes. Therefore, we’ll opt to drop this column and focus on addressing missing NaN values in the Age column instead.</p><p>To do this, we’ll explore the relationship within the data to infer missing Age values. Now, let’s delve into the correlation between Age and survival status, considering passenger class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*zBU6hjKLkdd4hFNxZAaOow.png" /></figure><p>Now we will fill in the missing value in the column. Using KNNImputer to get the nan and missing values in the Age Column.</p><pre>t_age = df[[&#39;Age&#39;]]<br>imputer = KNNImputer(n_neighbors=3)<br>After_imputation = imputer.fit_transform(t_age)<br>df[&#39;Age&#39;] = After_imputation</pre><p>After Dropping the Cabin Column and getting age values we are good to go:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*wGnUrFwxUQw4kzzaIr2Xmg.png" /></figure><p>To normalize the data, we’ll employ the MinMaxScaler. We opted for MinMaxScaler over StandardScaler because, in the DecisionTree Classifier, we’re not computing heuristic distances like Euclidean or Manhattan.</p><pre>MinMax_normalize = MinMaxScaler()<br>MinMax_y = df[&#39;Survived&#39;]<br>MinMax_X = MinMax_normalize.fit_transform(df.drop(&#39;Survived&#39;,axis=1))</pre><p>For better performance, we will use the GridSearchCV for Hyperparameter tuning.</p><pre>parameter = {<br>    &#39;criterion&#39; : [&#39;gini&#39;, &#39;entropy&#39;, &#39;log_loss&#39;],<br>    &#39;splitter&#39;  : [&#39;best&#39;, &#39;random&#39;],<br>    &#39;max_depth&#39; : [None, 5 , 10 , 15],<br>    &#39;min_samples_split&#39; : [2, 5, 10],<br>    &#39;max_features&#39; : [&#39;sqrt&#39;, &#39;log2&#39;]<br>}</pre><pre>clf = GridSearchCV(decision_tree,parameter,cv=5,scoring=&#39;accuracy&#39;)<br>clf.fit(X_train,y_train)</pre><p>To Get the Best Parameters for training the model.</p><pre>print(clf.best_params_)<br>print(clf.best_score_)<br><br>#Output<br>{&#39;criterion&#39;: &#39;log_loss&#39;, &#39;max_depth&#39;: 10, &#39;max_features&#39;: &#39;log2&#39;, &#39;min_samples_split&#39;: 10, &#39;splitter&#39;: &#39;best&#39;}<br>0.8227715946025805</pre><p>Training with Best Parameter</p><pre>best_decision_tree = DecisionTreeClassifier(**best_param)<br>best_decision_tree.fit(X_train,y_train)</pre><p><strong>Conclusion:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FctNZJgwm2_pE4-N.jpg" /></figure><p>Using Decision Tree Classifiers on the Titanic dataset teaches us not just technical skills but also empathy. This mix helps us predict outcomes better. Though the model has limits, its simplicity and clarity make it vital for data scientists.</p><p>Exploring the Titanic data with Decision Tree Classifiers isn’t just about learning; it’s about honoring those affected by the tragedy. This guide is your starting point in the world of machine learning. It shows that in data, like in life, the journey matters as much as the destination.</p><p>In the words of Ronald Fisher, <strong>“To call in the statistician after the experiment is done may be no more than asking him to perform a post-mortem examination: he may be able to say what the experiment died of.”</strong></p><p>Github Repo:<br><a href="https://github.com/MuhammadAliAhson/DecisionTree-on-Titanic-Dataset">https://github.com/MuhammadAliAhson/DecisionTree-on-Titanic-Dataset</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0e8a72fd48c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring SVM’s Potential with the Iris Dataset]]></title>
            <link>https://blog.devgenius.io/exploring-svms-potential-with-the-iris-dataset-359fc2de8962?source=rss-a0381c52edeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/359fc2de8962</guid>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[svm-algorithm]]></category>
            <category><![CDATA[svm-classifier]]></category>
            <dc:creator><![CDATA[Muhammad Ali Ahson]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 17:10:12 GMT</pubDate>
            <atom:updated>2024-03-10T16:41:35.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bnLKsChXq94QjtAiRn40w.png" /></figure><p>Welcome to the world of machine learning, where Support Vector Machines (SVM) emerge as steadfast allies in our quest for predictive excellence.</p><ol><li><strong>Introduction: Discovering the Essence of SVM</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*IBOCPFOd9vLmqAJGnAEkSw.png" /></figure><p>In the vast expanse of machine learning, Support Vector Machines (SVM) stand out for their robustness and adaptability. At their core, SVMs excel at classification tasks by identifying the optimal hyperplane that effectively separates different classes in the feature space. As we delve into the Iris dataset — a revered benchmark in the machine learning community — we gain invaluable insights into the workings of SVM and witness its transformative impact firsthand.</p><p><strong>2. Why Choose SVM? Pros and Cons</strong></p><p><strong>Advantages:</strong></p><p>- <strong>Robust Performance:</strong> SVMs exhibit exceptional performance, particularly in datasets with intricate decision boundaries, making them ideal for diverse applications ranging from image classification to financial forecasting.<br>- <strong>Versatility:</strong> SVMs offer flexibility through customizable kernel functions, empowering users to tailor the algorithm to diverse data types and problem domains.<br>- <strong>Resistance to Overfitting:</strong> By maximizing the margin between support vectors, SVMs demonstrate robust generalization capabilities, mitigating the risk of overfitting even in high-dimensional spaces.</p><p><strong>Disadvantages:</strong></p><p>- <strong>Sensitivity to Parameters:</strong> SVMs’ performance is sensitive to hyperparameters such as the choice of kernel and regularization parameter, necessitating careful tuning to achieve optimal results.<br>- <strong>Computational Complexity:</strong> Training SVMs on large datasets can be computationally intensive, particularly when employing complex kernel functions or dealing with high-dimensional feature spaces.<br>- <strong>Interpretability Challenges:</strong> While SVMs offer powerful predictive capabilities, interpreting the decision boundaries generated by the algorithm can pose challenges, limiting its explainability in certain scenarios.</p><p><strong>3. Understanding SVM Implementation</strong></p><p>Let’s dissect the provided code snippet, which encapsulates SVM implementation using the Iris dataset:</p><p>- <strong>Data Preparation:</strong> We begin by loading the Iris dataset and visually exploring its features using pair plots, gaining insights into data distribution and class separability.</p><pre><br>import pandas as pd<br>import numpy as np<br>from sklearn.model_selection import train_test_split<br>import seaborn as sns<br>df = pd.read_csv(&quot;/kaggle/input/iris/Iris.csv&quot;)<br>df.head()<br>sns.pairplot(data=df, hue=&#39;Species&#39;, palette=&#39;Set2&#39;)<br></pre><p>- <strong>Model Training: </strong>We define a custom SVM class and train the model on the training data, leveraging gradient descent to optimize model parameters and enhance class separation.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)<br>class SVM:<br> # Constructor and methods for training and prediction<br>svm_model = SVM()<br>svm_model.fit(X_train, y_train)</pre><ul><li><strong>SVM Algorithm in Python from Scratch</strong></li></ul><p><strong>Logic of Train function</strong></p><p>- Determine the number of samples and features in the dataset.<br>- Count the number of different categories in the target variable.<br>- Start with weights and bias set to zero.<br>- Ensure weights are in a format suitable for calculations.<br>- For each category to predict:<br> — Check each sample in the dataset.<br> — Adjust weights and biases if the prediction is incorrect, aiming to improve accuracy.<br> — Repeat this process multiple times to refine the model’s predictions.</p><pre>def fit(self, X, y):<br> n_samples, n_features = X.shape<br> n_classes = len(np.unique(y))<br> self.w = np.zeros((n_classes, n_features))<br> self.b = np.zeros(n_classes)<br> self.w = self.w.astype(np.float64)<br> for idx, y_val in enumerate(np.unique(y)):<br> y_transformed = np.where(y == y_val, 1, -1)<br> y_transformed = y_transformed.astype(np.float64)<br>for _ in range(self.n_iterations):<br> for i, x_i in enumerate(X):<br> x_i = x_i.astype(np.float64)<br> condition = y_transformed[i] * (np.dot(x_i, self.w[idx]) - self.b[idx]) &gt;= 1<br> if condition:<br> self.w[idx] -= self.lr * (2 * self.regularization_param * self.w[idx])<br> else:<br> self.w[idx] -= self.lr * (2 * self.regularization_param * self.w[idx] - np.dot(x_i, y_transformed[i]))<br> self.b[idx] -= self.lr * y_transformed[i]</pre><ul><li><strong>Model Evaluation:</strong> We evaluate the model’s performance by making predictions on the test data and calculating classification accuracy.</li></ul><pre><br>predictions = svm_model.predict(X_test)<br>print(&quot;SVM classification accuracy:&quot;, accuracy(y_test, predictions))</pre><p><strong>4. Conclusion: Embracing SVM’s Potential</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KFX6DDqhj5zS19YTNp-Wnw.jpeg" /></figure><p>In conclusion, Support Vector Machines (SVM) stand as stalwarts of machine learning, offering a compelling blend of robustness, versatility, and predictive power. Through our exploration of the Iris dataset, we’ve witnessed SVM’s transformative capabilities, illuminating a path toward accurate and reliable classification.</p><p>As we navigate the evolving landscape of machine learning, let us embrace the timeless wisdom encapsulated within SVM. With its ability to discern intricate patterns and navigate high-dimensional data, SVM remains an indispensable ally in our pursuit of knowledge and discovery.</p><p>Whether you’re a seasoned practitioner or an eager enthusiast, harness the potential of SVM and unlock new horizons in the realm of machine learning. With SVM by your side, the possibilities are limitless.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=359fc2de8962" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/exploring-svms-potential-with-the-iris-dataset-359fc2de8962">Exploring SVM’s Potential with the Iris Dataset</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Nearest Neighbors (KNN) Classifier on Handwritten Digits]]></title>
            <link>https://python.plainenglish.io/k-nearest-neighbors-knn-classifier-on-handwritten-digits-bc2c58b12f26?source=rss-a0381c52edeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc2c58b12f26</guid>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knn-classification]]></category>
            <category><![CDATA[mnist]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Muhammad Ali Ahson]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 12:04:52 GMT</pubDate>
            <atom:updated>2024-03-11T01:57:23.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*yWxYGmRvUyS9jQUA.jpeg" /></figure><p>Welcome to the world of machine learning, where algorithms work tirelessly to make sense of data and uncover patterns that escape the human eye. Today, we’re taking a closer look at one of the friendliest algorithms out there: <strong>K-Nearest Neighbors (KNN)</strong>. So grab your cup of coffee and join us on this journey through the fascinating realm of machine learning!</p><ol><li><strong>Let’s Keep It Simple: Getting to Know KNN</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lu7x4SDRQDnNWAQ9DoI5-A.jpeg" /></figure><p>In a world filled with complex algorithms, KNN stands out for its simplicity. Imagine this: instead of crunching numbers and fitting fancy curves, KNN simply looks at its neighbors and asks for their opinions. It’s like asking your neighbors for recommendations on where to eat — simple, right?</p><p><strong>2. Why Choose KNN? Pros and Cons, Just Like Us</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*DMrcJAv5mWLZsqNc.jpg" /></figure><p><strong>Pros:</strong></p><p>- <strong>Easy Peasy:</strong> KNN is like a friend who always explains things in a way you understand. It’s perfect for beginners dipping their toes into the world of machine learning.<br>- <strong>No Training Required:</strong> Unlike some algorithms that demand hours of training, KNN is ready to go right out of the box. No training is required — just jump right in!<br>- <strong>Goes With the Flow:</strong> KNN doesn’t care about fancy assumptions or complicated math. It adapts to the data like a chameleon, making it great for all sorts of problems.</p><p><strong>Cons:</strong></p><p>- <strong>Slow and Steady:</strong> As the saying goes, good things take time. KNN can be a bit slow, especially with big datasets. It’s like taking the scenic route — it might not be the fastest, but you’ll get there eventually.<br>- <strong>Memory Hog:</strong> KNN has a bit of a sweet tooth for memory. It likes to gobble up all the data and store it for later, which can be a bit heavy on your computer’s memory.<br>- <strong>Picky Eater:</strong> KNN is a bit sensitive to noise and irrelevant details. It’s like trying to find your way in a crowded room with lots of distractions — it can get a bit tricky.</p><p><strong>3. Let’s Dive into the Code: How Does It Work?</strong></p><p>Now, let’s roll up our sleeves and take a peek under the hood. The code snippet provided gives us a glimpse into how KNN tackles the challenge of recognizing handwritten digits:</p><ul><li><strong>Loading the Data:</strong> We start by loading the handwritten digit images and their labels. It’s like unpacking a box of treasures — each image is a piece of the puzzle.</li></ul><pre>val = load_digits()<br>X = val.images<br>y = val.target</pre><p><strong>Displaying the Data: </strong>We start by loading the handwritten digit images and displaying a few samples. It’s like flipping through a photo album of handwritten digits — each image tells a unique story.</p><pre>val = load_digits()<br>X = val.images<br>y = val.target<br><br>plt.figure(figsize=(12, 6))<br>for i in range(10):<br>    plt.subplot(2, 5, i + 1)<br>    plt.imshow(X[i], cmap=&quot;binary&quot;) <br>    plt.title(f&quot;Digit: {y[i]}&quot;)  # Using f-string to concatenate the title<br>    plt.axis(&#39;off&#39;)<br>plt.show()</pre><p>- <strong>Getting Ready:</strong> We flatten the images and split them into training and testing sets. It’s like laying out all the ingredients before starting to cook — we need to get organized!</p><pre># Load data<br>digits = load_digits()<br>X = digits.images.reshape((len(digits.images), -1))<br>y = digits.target<br><br>X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)</pre><p><strong>Utilizing GridSearchCV: </strong>Finding the Best Parameters. Now that we’ve familiarized ourselves with the data, it’s time to fine-tune our KNN model using GridSearchCV — a handy tool for finding the best hyperparameters.</p><pre>parameters = {<br>    &#39;n_neighbors&#39;: [3, 5, 7, 9],<br>    &#39;weights&#39;: [&#39;uniform&#39;, &#39;distance&#39;],<br>    &#39;p&#39;: [1, 2]<br>}<br>knn = KNeighborsClassifier()<br>grid_search = GridSearchCV(knn, parameters, cv=5, scoring=&#39;accuracy&#39;)<br>grid_search.fit(X_train, y_train)<br><br>print(grid_search.best_params_)<br>print(grid_search.best_score_)</pre><p>- <strong>Training the Model:</strong> We train our KNN model using a technique called grid search, which helps us find the best settings for our model. It’s like fine-tuning a radio to get the best reception — trial and error until we find the sweet spot.</p><pre>knn_best = KNeighborsClassifier(**grid_search.best_params_)<br>knn_best.fit(X_train, y_train)</pre><p>- <strong>Testing and Evaluation:</strong> We put our model to the test using the testing set and see how well it performs. It’s like taking our newly baked cake out of the oven and seeing if it’s just right — not too burnt, not too raw.</p><pre># Get the best parameters and best score<br>best_params = grid_search.best_params_<br>best_score = grid_search.best_score_<br><br># Initialize lists to store k values and corresponding accuracies<br>k_values = []<br>accuracies = []<br><br># Iterate over parameter combinations<br>for k in parameters[&#39;n_neighbors&#39;]:<br>    knn = KNeighborsClassifier(n_neighbors=k, weights=best_params[&#39;weights&#39;], p=best_params[&#39;p&#39;])<br>    knn.fit(X_train, y_train)<br>    y_pred = knn.predict(X_test)<br>    accuracy = accuracy_score(y_test, y_pred)<br>    k_values.append(k)<br>    accuracies.append(accuracy)<br><br># Plot the graph with improved aesthetics<br>plt.figure(figsize=(12, 8))<br>plt.plot(k_values, accuracies, marker=&#39;o&#39;, linestyle=&#39;-&#39;, color=&#39;b&#39;, linewidth=2, markersize=8)<br>plt.title(&#39;Accuracy of KNN for Different Values of k&#39;, fontsize=16)<br>plt.xlabel(&#39;Number of Neighbors (k)&#39;, fontsize=14)<br>plt.ylabel(&#39;Accuracy&#39;, fontsize=14)<br>plt.xticks(k_values, fontsize=12)<br>plt.yticks(fontsize=12)<br>plt.grid(True, linestyle=&#39;--&#39;, alpha=0.7)<br>plt.tight_layout()<br>plt.show()</pre><p>- <strong>Prediction Time:</strong> Finally, we feed a test image into our trained model and see what it thinks. It’s like holding up a mystery object and asking our friends to guess what it is — let’s see if our model can guess the right answer!</p><p><strong>Wrapping It Up: The Beauty of KNN</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*lcVfrqJMrM0Eg0YI.png" /></figure><p>In a world of complex algorithms and mind-bending math, KNN is like a breath of fresh air — a reminder that sometimes, simplicity is all we need. With its friendly demeanor and straightforward approach, KNN has earned its place as a beloved companion in the world of machine learning.</p><p>So, whether you’re a seasoned pro or just dipping your toes into the waters of machine learning, don’t overlook the humble KNN. With its knack for simplicity and knack for getting the job done, it might just surprise you with its magic.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc2c58b12f26" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/k-nearest-neighbors-knn-classifier-on-handwritten-digits-bc2c58b12f26">K-Nearest Neighbors (KNN) Classifier on Handwritten Digits</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Steps You Need to Learn For KNN Algorithm.]]></title>
            <link>https://blog.devgenius.io/steps-you-need-to-learn-for-knn-algorithm-2a9d342cb1af?source=rss-a0381c52edeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a9d342cb1af</guid>
            <category><![CDATA[knn-algorithm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[knn-classification]]></category>
            <dc:creator><![CDATA[Muhammad Ali Ahson]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 15:49:18 GMT</pubDate>
            <atom:updated>2024-03-10T16:41:29.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*9h-WczF6csbeut5vsvjSUA.gif" /><figcaption>KNN Algorithm</figcaption></figure><p>Have you ever wondered why KNN is often referred to as the “lazy algorithm”? Let’s find out together!</p><p>But before we jump into the world of algorithms, let’s start with the basics:</p><p>Are you ready to uncover the secrets of KNN and make your machine learning journey a breeze? Let’s dive in!</p><h3><strong><em>4. When to Use KNN?</em></strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWWF42P4RD1ZzJGqAn4U-A.png" /></figure><p>When data is labeled.<br>Data is noise-free.<br>Dataset should be small.<br>KNN doesn’t learn discriminative functions from the training set.</p><h3><strong>5. How Does the KNN Algorithm Work?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*2d9pFQZJJSTWHimtgbgrPA.jpeg" /></figure><p>It relies on a distance factor to calculate:<br><strong>Euclidean Distance:</strong> <br>We’ll discuss the procedure of KNN using Euclidean Distance. <br> The formula for it is:</p><h4><strong>Distance = Sqrt((x-a)² + (y-b)²).</strong></h4><p><strong>5.1.2. Manhattan Distance<br> 5.1.3. Makowski Distance</strong><br> <br> For more insights on these distance metrics, check out this insightful article by <strong>Abdullah Siddique. </strong><a href="https://medium.com/dev-genius/exploring-knn-with-different-distance-metrics-85aea1e8299"><strong>Here</strong></a></p><h3>5.2. Key Factors: <strong>K and p</strong></h3><h4><strong>5.2.1. How to Choose K?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RjLeVnKVOwTuahLw1_zymg.jpeg" /></figure><h4>Selecting K is based on factors like:</h4><p>1) Feature Similarity<br>2) Based on your Neighbors</p><h3><strong>Value of K:</strong></h3><p>1) Sqrt(n), where n is the total number of data points<br>2) Odd values of K are selected to avoid confusion between two classes of data</p><h3>5.2.1.3. Drawbacks of selecting an invalid value of K:</h3><p>1) If the value of K is too low, it’s biased or just too noisy.<br>2) If K is too big, it will take forever to process.</p><h3>Let’s start with the coding part for better understanding.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etZlhJE4DMdEc9vflc-DkQ.jpeg" /></figure><p>Let’s first consider the dataset for now we will be taking an Iris dataset for understanding.</p><ol><li>Requirement Libraries:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97a4f3e9061386b9671cf0adad26b05/href">https://medium.com/media/c97a4f3e9061386b9671cf0adad26b05/href</a></iframe><p>2. Reading the data using pandas:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4665cdbdaa69243400912d100900193/href">https://medium.com/media/f4665cdbdaa69243400912d100900193/href</a></iframe><p>3. Extracting Column Names and adding them to the Dictionary:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7311aa0caa7c400d32c6c847e30eb656/href">https://medium.com/media/7311aa0caa7c400d32c6c847e30eb656/href</a></iframe><p>4. Converting the output into the classes for classification:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50086248eb0912a35c2b615c6b96066f/href">https://medium.com/media/50086248eb0912a35c2b615c6b96066f/href</a></iframe><p>5. Converting Output Values into Numpy Array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/febb82cca74114e5db3519185cc215b0/href">https://medium.com/media/febb82cca74114e5db3519185cc215b0/href</a></iframe><p>6. KNN Implementation in class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9db797ec3cff9670fd960f0d7396df63/href">https://medium.com/media/9db797ec3cff9670fd960f0d7396df63/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*-OcZCg03-LXxYOHK62VXsw.png" /><figcaption>For Certain K the values are measured</figcaption></figure><p>Predicts class labels for test instances using nearest neighbors.</p><p>Takes training features <strong>X_train</strong>, labels <strong>y_train</strong>, test features <strong>X_test</strong>, and <strong>k</strong>.</p><p>For each test instance:<br> -&gt; Calculates distances to training instances.<br> -&gt; Selects <strong>k</strong> nearest neighbors.<br> -&gt; Predicts class label via majority voting.</p><p>Returns list of predicted labels for test instances.</p><p>7. Calculating K value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae64b448fc608c13b27b579d707ef1a5/href">https://medium.com/media/ae64b448fc608c13b27b579d707ef1a5/href</a></iframe><p>8. Defining the main function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/071edb123f31b548a561bb6d0778e30c/href">https://medium.com/media/071edb123f31b548a561bb6d0778e30c/href</a></iframe><h3>Drawbacks of KNN for Large Datasets:</h3><p>KNN excels with small datasets but struggles with larger ones due to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*QjzSc0Rtc2GoGJcz3iM6IQ.jpeg" /></figure><ol><li><strong>Time Complexity</strong>:<br>As dataset size increases, KNN’s time complexity rises.<br>Computing distances and sorting them for all training instances becomes time-consuming.</li><li><strong>Memory Usage</strong>:<br>Storing large datasets in memory can be problematic.<br>KNN requires holding the entire training dataset, which strains memory resources.</li><li><strong>Scalability</strong>:<br> KNN’s performance degrades as dataset sizes increase exponentially.<br> Handling large-scale datasets becomes impractical due to decreased efficiency.</li></ol><h3>Conclusion:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WDhE6C5Z-WvQxENbs1PQ5A.jpeg" /></figure><p>Armed with this understanding, you’re ready to tackle <strong>KNN</strong> effectively. Remember, practice is key to mastery. So, dive into coding and unleash KNN’s potential in your machine learning projects.</p><p><strong>Don’t Forget to comment your queries. I would love to answer them.</strong></p><h3>Image resources:</h3><ol><li><a href="https://faithfreehold.org/fefc-blog/wrong-tools">https://faithfreehold.org/fefc-blog/wrong-tools</a></li><li><a href="https://www.logodesignteam.com/blog/drawbacks-of-a-free-logo/">https://www.logodesignteam.com/blog/drawbacks-of-a-free-logo/</a></li><li><a href="https://makeameme.org/meme/and-in-conclusion-dcd674ee9c">https://makeameme.org/meme/and-in-conclusion-dcd674ee9c</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a9d342cb1af" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/steps-you-need-to-learn-for-knn-algorithm-2a9d342cb1af">Steps You Need to Learn For KNN Algorithm.</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Career Paths Unveiled: Analyst vs. Engineer vs. Scientist]]></title>
            <link>https://aliahson.medium.com/data-science-career-paths-unveiled-analyst-vs-engineer-vs-scientist-b47ff64361?source=rss-a0381c52edeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b47ff64361</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Muhammad Ali Ahson]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 16:38:38 GMT</pubDate>
            <atom:updated>2023-08-31T16:38:38.360Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s dynamic landscape, the term “Data Science” reverberates powerfully, given its immense demand across various industries. For those venturing into this field, it’s essential to grasp the intricate differentiations among roles to chart a purposeful career trajectory. Amid the swirling terminology encompassing Data Analysts, Data Engineers, and Data Scientists, a deeper understanding of their distinct responsibilities is paramount.</p><p>Let’s embark on an exploratory journey to delve into the essence of these roles.</p><blockquote><strong>1. The Role of a Data Analyst:</strong><br>A Data Analyst serves as a bridge between raw data and actionable insights. Their prowess lies in harnessing statistical methods to distill significance from data, transforming it into meaningful insights for businesses. Rooted in analysis, they employ pre-established techniques and algorithms to address challenges, ultimately visualizing pivotal data to facilitate informed decision-making. Unlike trailblazers, their focus is on leveraging existing methods to provide effective solutions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6wjeloJv3Wt0Pmsmxi2bA.png" /></figure><blockquote><strong>2. The Realm of Data Engineering:</strong><br>Diverging from Data Analysts and Data Scientists, Data Engineers assume a unique role centered on shaping data pipelines’ infrastructure. These professionals are akin to virtuosos, adeptly maneuvering databases. Their responsibilities encompass extracting data from databases and harmonizing disparate data sources. As primary data providers, they wield data manipulation techniques, rendering data suitable for various applications, from nurturing machine learning models to fueling business expansion strategies.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*mtjvly8ux3jlHNHNPBLEcQ.jpeg" /></figure><blockquote><strong>3. The Epitome of Data Science: The Data Scientist:</strong><br>The term “Scientist” in “Data Scientist” accentuates the essence of this role. Much like traditional scientists, Data Scientists are adept problem solvers and inventive solution architects. Embracing the quintessential scientific spirit, they craft innovative solutions tailored to their domain. Just as scientists in other disciplines devise novel methodologies, Data Scientists harness creativity to design solutions tailored to data-centric challenges.</blockquote><p><strong>Visualizing the Pathways:</strong><br>Picture a diagram depicting task distribution within the Data Science domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*j54gBqrIeSw0l2DY2gOyBQ.png" /></figure><p>This representation reveals that Data Scientists allocate approximately 35% of their efforts to Machine Learning pursuits. Notably, the accuracy of machine learning models hinges on the quality of training data. Structured, enriched, and uniform data catalyze the learning process, akin to a skilled teacher elucidating concepts effectively. Thus, Data Scientists shoulder the responsibility of elevating data quality, infusing it with meaningful features that empower machine learning models to glean profound insights during training sessions.</p><blockquote><strong>In Conclusion:</strong><br>The intricate tapestry of Data Science comprises distinct threads, each representing a unique role. Data Analysts, Data Engineers, and Data Scientists wield pivotal roles in translating data into actionable insights, crafting data pipelines, and innovating solutions, respectively. By grasping the essence of these roles, aspiring individuals can embark on a journey enlightened by clarity, paving the path for impactful contributions within the expansive realm of Data Science.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b47ff64361" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Mean Clustering in C++]]></title>
            <link>https://blog.devgenius.io/k-mean-clustering-in-c-fb4efd382057?source=rss-a0381c52edeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb4efd382057</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Muhammad Ali Ahson]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 18:01:32 GMT</pubDate>
            <atom:updated>2024-03-08T19:39:05.355Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>K-Means Clustering with OpenCV in C++</p><p>K-Means Clustering is a widely used unsupervised learning technique for data clustering and segmentation. The algorithm partitions a set of data points into K clusters based on their similarity. In this article, we will see how to implement K-Means Clustering in C++ using the OpenCV library.</p><p>Before diving into the implementation, let’s first understand the basics of K-Means Clustering.</p><p><strong>Understanding K-Means Clustering</strong></p><p>K-Means Clustering is a form of unsupervised learning where we group a set of data points into K clusters based on their similarity. The algorithm assigns each data point to the nearest cluster, and the cluster centroid is updated after each iteration. The process continues until the cluster centroids stop changing or reach a maximum number of iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*gGtQ9DuP7Ss0bY0b4PvRsQ.png" /></figure><p><strong>The algorithm can be summarized as follows:</strong></p><p>Initialize K cluster centroids.</p><p>Assign each data point to the nearest cluster centroid.</p><p>Update the cluster centroids based on the mean of the assigned data points.</p><p>Repeat steps 2 and 3 until convergence or a maximum number of iterations is reached.</p><p><strong>Implementing K-Means Clustering with OpenCV in C++</strong></p><p>Now that we have a basic understanding of K-Means Clustering, let’s dive into the implementation using OpenCV in C++.</p><p>First, we need to load the image file into OpenCV using the imread function.</p><p><strong>cv::Mat image = cv::imread(“image.bmp”, cv::IMREAD_GRAYSCALE);</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*UbNBk-D-8xBiJzI4rCiwMg.png" /></figure><p>Next, we convert the image to a 2D matrix of data points. We will use the reshape function in OpenCV to convert the image to a 2D matrix, where each row represents a data point and each column represents a feature.</p><p><strong>int rows = image.rows * image.cols;</strong></p><p><strong>cv::Mat data = image.reshape(3, rows);</strong></p><p><strong>data.convertTo(data, CV_32F);</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*P9HGnlbkM8xmFzIlbhU-qQ.png" /></figure><p>Row and Cols are the Rows and Columns for the Image (2D Array)</p><p>Now, we can use the k-means function in OpenCV to perform K-Means Clustering on the data matrix. We need to specify the number of clusters (K), the data matrix, and the criteria for stopping the algorithm.</p><p><strong>int K = 3;</strong></p><p><strong>cv::Mat labels, centers;</strong></p><p><strong>cv::kmeans(data, K, labels, cv::TermCriteria(), 5, </strong><strong>cv::KMEANS_PP_CENTERS, centers);</strong></p><p>The k-means algorithm iteratively groups the data points into k clusters by minimizing the sum of squared distances between the data points and their nearest centroid. The objective is to minimize the within-cluster sum of squares, which measures the similarity of the data points within a cluster.</p><p>In this way, k-means clustering is able to identify clusters in the data by comparing the similarity of neighboring data points. The resulting clusters represent groups of similar data points, allowing for insights and patterns to be discovered within the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ko7SXqX6M4LnWK63Ta5i4w.png" /></figure><p>Finally, we can use the result of the K-Means Clustering to segment the image. We will create a new image with the same size as the original image and fill it with the cluster centroids.</p><p><strong>cv::Mat result = centers.reshape(3, image.rows);</strong></p><p><strong>cv::Mat dest; result.convertTo(dest, image.type());</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ytWfhFqTMiG-BINvc1mYUg.png" /></figure><p>And that’s it! We have successfully implemented K-Means Clustering in C++ using OpenCV.</p><p>Here’s the complete code for your reference:</p><p><a href="https://lnkd.in/d6ipt3UN">GitHub - MuhammadAliAhson/OpenCV_K-Mean_Clustering_CPP: Hey Folks! I have made an &quot;OpenCV&quot; K-mean clustering program in which you can eliminate the non-populated (less or not absolute neighbors) and can convert the colored image into Grey Scale (black and white). It is used in the medical field to analyze infected skin.</a></p><p>Link for images</p><ol><li><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fbookdown.org%2Ftpinto_home%2FUnsupervised-learning%2Fk-means-clustering.html&amp;psig=AOvVaw2qtACc86dJapHhz-jkSu03&amp;ust=1675965512318000&amp;source=images&amp;cd=vfe&amp;ved=0CBAQjRxqFwoTCLCekJrAhv0CFQAAAAAdAAAAABAJ">Link for the first Image</a></li><li><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.nvidia.com%2Fen-us%2Fglossary%2Fdata-science%2Fk-means%2F&amp;psig=AOvVaw2qtACc86dJapHhz-jkSu03&amp;ust=1675965512318000&amp;source=images&amp;cd=vfe&amp;ved=0CBAQjRxqFwoTCLCekJrAhv0CFQAAAAAdAAAAABAR">Link for Second Image</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb4efd382057" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/k-mean-clustering-in-c-fb4efd382057">K-Mean Clustering in C++</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>