<?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 Majid Ahmad Khan on Medium]]></title>
        <description><![CDATA[Stories by Majid Ahmad Khan on Medium]]></description>
        <link>https://medium.com/@majidahmadkhan?source=rss-e0e6bbefc491------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G1xUydQ7mniUxCMltkDx0A.jpeg</url>
            <title>Stories by Majid Ahmad Khan on Medium</title>
            <link>https://medium.com/@majidahmadkhan?source=rss-e0e6bbefc491------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:51:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@majidahmadkhan/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[Ace Every ML Challenge with This All-Purpose Jupyter Notebook]]></title>
            <link>https://medium.com/@majidahmadkhan/ace-every-ml-challenge-with-this-all-purpose-jupyter-notebook-d6ff87075794?source=rss-e0e6bbefc491------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ff87075794</guid>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Majid Ahmad Khan]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 01:41:16 GMT</pubDate>
            <atom:updated>2023-02-09T02:34:08.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*5UcOrmRnpInxdKCm1V9_Jg.png" /></figure><h4><strong>Introduction</strong></h4><p>Machine learning has become a crucial part of many businesses and organizations, helping to make better decisions, automate processes, and solve complex problems. With its ability to extract valuable insights from large amounts of data, it has become an essential tool for data scientists, engineers, and researchers.</p><p>In this article, we will demonstrate how to build a general machine-learning solution in Jupyter Notebook using the popular Python library, sci-kit-learn (SKlearn). By following this guide, you can use it as a base to solve any machine learning problem, whether it be regression, classification, clustering, or dimensionality reduction.</p><p><strong>Step 1: Import the necessary Libraries</strong></p><p>To get started, we need to import the following libraries:</p><ul><li>Numpy: a library for numerical computing in Python</li><li>Pandas: a library for data manipulation and analysis</li><li>Matplotlib: a plotting library for visualizing data</li><li>SKlearn: the machine learning library we will be using</li></ul><p>Here is the code to import the libraries:</p><pre># Get the critical imports out of the way<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import numpy as np</pre><p><strong>Step 2: Load the dataset</strong></p><p>Next, we need to load the dataset. For this, I have used an open-source dataset which is employee-review data from glassdoor, and used it in a hackathon at HackerEarth. You can use any other dataset you prefer. You can load the dataset using the following code:</p><pre>#getting data<br>dftrain=pd.read_csv(&quot;data/dataset/train.csv&quot;)<br>dftest=pd.read_csv(&quot;data/dataset/test.csv&quot;)<br>dftrain.head(5)</pre><p><strong>Step 3: Cleaning the data</strong></p><p>This is one of the most important steps we clean the data using various methods like checking for NaNs, one-hot-encoding or label encoding columns that have string-like values. Also, we check the number of unique values by column so we include only those columns as features have a reasonable ratio of unique values and total values. The following code explains how you do it:</p><pre>#checking for Nan<br>dftrain.isnull().any()<br>#Exploring unique values by column<br>dftrain.nunique()<br>loading Label encoder<br># Import label encoder<br>from sklearn import preprocessing<br>  <br># label_encoder object knows how to understand word labels.<br>label_encoder = preprocessing.LabelEncoder()<br>  <br># Encode labels in column &#39;species&#39;.<br>dftrain[&#39;Place&#39;]= label_encoder.fit_transform(dftrain[&#39;Place&#39;])</pre><p><strong>Step 4: Split the data into independent and dependent variable</strong></p><p>Before we start building our machine learning model, it’s important to split the data into dependent(Y) and independent data(X).</p><pre>from sklearn.model_selection import train_test_split<br>y = dftrain.pop(&#39;overall&#39;)<br>X = dftrain</pre><p><strong>Step 5: Scaling the data</strong></p><p>Next, we need to preprocess the data. This can include scaling, normalization, or encoding. For this example, we will be scaling the data.</p><pre>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import MinMaxScaler<br><br>scaler = StandardScaler()<br># keep our unscaled features just in case we need to process them alternatively<br>features_scaled = X <br>X_scaled = scaler.fit_transform(features_scaled)<br><br>scaler = MinMaxScaler()<br># keep our unscaled features just in case we need to process them alternatively<br>features_minmax = X<br>X_minmax = scaler.fit_transform(features_minmax)</pre><p><strong>Step 6: Splitting the data into training and test set.</strong></p><p>Before we start building our machine learning model, it’s important to split the data into training and testing sets. This will allow us to evaluate the performance of our model on unseen data.</p><pre>############ Standard Scaled test/train set ###########<br># The labels/classes (y_train, y_test) never change, keep old values <br>X_train_scaled, X_test_scaled, _, _ = train_test_split(<br>    X_scaled, <br>    y, <br>    test_size=0.2, <br>    random_state=69<br>)</pre><p><strong>Step 7: Select models and train it</strong></p><p>With the data preprocessed, we can now select a machine-learning model and train it. There are many models to choose from in SKlearn, such as k-nearest neighbors, decision trees, random forests, and support vector machines, to name a few. For this example, we will be using multiple ML models. With the model trained, we can now evaluate its performance. The following code explains how you do it:</p><pre>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.svm import SVC<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier<br>from sklearn.naive_bayes import GaussianNB<br>from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis<br><br>classification_models = [<br>    KNeighborsClassifier(),#(3),<br>    SVC(kernel=&#39;linear&#39;, C=0.025),#, C=0.025),<br>    SVC(kernel=&#39;rbf&#39;),<br>    DecisionTreeClassifier(),#max_depth=5),<br>    RandomForestClassifier(),#max_depth=5, n_estimators=10, max_features=1),<br>    AdaBoostClassifier(),<br>    GaussianNB(),<br>    QuadraticDiscriminantAnalysis()]<br><br>scores = []<br>for model in classification_models:<br>    model.fit(X_train_scaled, y_train)<br>    score = model.score(X_test_scaled, y_test)<br>    model_name = type(model).__name__<br>    if model_name==&#39;SVC&#39; and model.kernel==&#39;rbf&#39;: model_name+=&#39; RBF kernel&#39;<br>    scores.append((model_name,(f&#39;{100*score:.2f}%&#39;)))<br># Make it pretty<br>scores_df = pd.DataFrame(scores,columns=[&#39;Classifier&#39;,&#39;Accuracy Score&#39;])<br>scores_df.sort_values(by=&#39;Accuracy Score&#39;,axis=0,ascending=False)</pre><p><strong>Conclusion</strong></p><p>There you have it and usually through this method can achieve good accuracy and can estimate how much accuracy is achievable.</p><p>In conclusion, the Jupyter notebook serves as a powerful tool for solving any machine-learning problem with ease. With the use of various SKlearn libraries, the notebook provides a comprehensive framework for building and testing various machine-learning models. The versatility of the notebook makes it an ideal starting point for individuals and organizations looking to dive into the world of machine learning. By leveraging the functionality of the libraries and the Jupyter environment, it is possible to explore and analyze complex data sets, select the most appropriate model, and deploy it in a practical setting. Whether you are a beginner or an experienced practitioner, this Jupyter notebook is a must-have resource for anyone interested in the field of machine learning.</p><p>References</p><p>Github source code: <a href="https://github.com/code-mj12/SingleMLpipeline">Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ff87075794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of K Means: Unlocking the Secrets of Clustering ]]></title>
            <link>https://medium.com/@majidahmadkhan/the-power-of-k-means-unlocking-the-secrets-of-clustering-ebf7eadf0a11?source=rss-e0e6bbefc491------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf7eadf0a11</guid>
            <category><![CDATA[k-means-algorithm]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[k-means-implementation]]></category>
            <dc:creator><![CDATA[Majid Ahmad Khan]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 21:48:48 GMT</pubDate>
            <atom:updated>2023-03-07T21:41:22.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*IkmHzp8v8-eAwqvYk449Nw.png" /></figure><h4>Introduction</h4><p>K Means Clustering is a popular unsupervised machine learning algorithm that helps divide a large dataset into smaller groups (or clusters) based on similarity. The algorithm can be applied to various fields, including market segmentation, image segmentation, and document classification. In this blog, we’ll explore the basics of K Means Clustering and how to implement the algorithm.</p><p><strong>The Key Concept of K Means Clustering</strong></p><p>K Means Clustering algorithm works by finding K number of centroids in a given dataset, where K represents the number of clusters. Then, each data point is assigned to the nearest centroid based on Euclidean distance. The algorithm continues to update the centroids until the data points are optimally divided into the required number of clusters.</p><p>The algorithm follows the following steps:</p><ol><li>Initialize K centroids randomly in the dataset.</li><li>Calculate the distance of each data point from each centroid.</li><li>Assign each data point to the nearest centroid.</li><li>Recalculate the centroids as the mean of all data points assigned to them.</li><li>Repeat steps 2–4 until the centroids stop changing or reach a maximum iteration limit.</li></ol><h4>How to Choose K in K Means Clustering</h4><p>Choosing the right value of K is crucial for the accuracy of the algorithm. There are several methods to determine the value of K, including the elbow method, the silhouette method, and the gap statistic method.</p><p>The elbow method is one of the simplest methods where we plot the sum of squared distances (SSE) for each value of K and select the value of K where the change in SSE starts to level off.</p><p>The silhouette method is another popular method that evaluates the similarity of each data point to its cluster compared to other clusters. The silhouette score ranges from -1 to 1, and a higher score indicates a better fit of the data point to its cluster.</p><p>The gap statistic method is based on comparing the observed SSE to a null reference distribution. The gap statistic helps determine the optimal number of clusters by identifying the gap between the observed SSE and the reference distribution.</p><h4>Implementing K Means Clustering in Python</h4><p>The dataset we are using here is the Mall Customers data (CSV provided). It’s unlabeled data that contains the details of customers in a mall ( features like genre, age, annual income(k$), and spending score ). We aim to cluster the customers based on the relevant features of annual income and spending score. So first we load the dataset using pd.read_csv() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*WmIvdn8mD8UEUhGens3lqA.png" /><figcaption>Fig. 1(dataset)</figcaption></figure><p>After that, we remove columns that do not contribute to our clustering such as customerID. For the gender column as they are of string type, we can convert them into a one-hot encoded vector using pd. getdummies() function. We also add a ‘cluster’ column so that a datapoint can be assigned a cluster number.</p><pre># keeping only the desired column<br>col = [&#39;Genre&#39;, &#39;Age&#39;, &#39;AnnualIncome&#39;, &#39;SpendingScore&#39;]<br>customer_features = df[col]<br>#converting Genre/gender column into one hot encoded vector<br>customer_features = pd.get_dummies(customer_features, <br>                                     columns= [&#39;Genre&#39;])<br>#adding a cluster column<br>customer_features[&#39;cluster&#39;]=0</pre><p><strong>Defining K-Means function</strong></p><p>Firstly we make an array of zeros where we store our datapoint’s centroid number. Secondly, we get <strong>K </strong>random array values for centroids. Then we loop over the datapoints(X values) and also do a nested loop over centroids values. Inside the nested loop, we calculate the euclidean distance between a centroid point and a data point. Now we apply a condition to check if the euclidean distance of the datapoint and centroid is less than the minimum distance of that datapoint assigned to the respective centroid. Finally, new centroid values are calculated by taking the mean.</p><pre>def kmeans(X, k):<br>    diff = 1<br>    #making a cluster array of zeros of size of number of datapoints<br>    cluster = np.zeros(X.shape[0])<br>    #this gets random values for each column k times<br>    centroids = data.sample(n=k).values<br>    while diff:<br>        for i, row in enumerate(X):<br>            #minimum distance set at positive infinity<br>            mn_dist = float(&#39;inf&#39;)<br>            #this loop goes over each of the centroid<br>            for idx, centroid in enumerate(centroids):<br>                #calculating eucludiean distance between a centeroid point and datapoint<br>                d = np.sqrt((centroid[0]-row[0])**2 + (centroid[1]-row[1])**2+ <br>                            (centroid[2]-row[2])**2 + (centroid[3]-row[3])**2 + <br>                            (centroid[3]-row[3])**2 )<br>                #this condition works if euclidean distance of datapoint(d1) and centeroid(c2) is less than mn_dist than <br>                #earlier centroid(c1) datapoint is assigned the respective centroid <br>                if mn_dist &gt; d:<br>                    mn_dist = d<br>                    cluster[i] = idx<br>        #after placing points in respective centeroids the new_centroid values calculated by taking mean<br>        new_centroids = pd.DataFrame(X).groupby(by=cluster).mean().values<br>        #closing condition <br>        if np.count_nonzero(centroids-new_centroids) == 0:<br>            print(new_centroids)<br>            diff = 0<br>        else:<br>            centroids = new_centroids<br>    return centroids, cluster</pre><p>Finally, after running the function now we can visualize see fig.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*wxjmWK7Fgz9w1BWHd9V9EQ.png" /><figcaption>Fig. 2</figcaption></figure><h4><strong>References/Link</strong></h4><p>The Github Repo code. <a href="https://github.com/code-mj12/K-Mean-clustering">Link</a></p><p>This a great article to read for further understanding. <a href="https://www.javatpoint.com/k-means-clustering-algorithm-in-machine-learning">Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf7eadf0a11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Nearest Neighbors: The Power of Proximity]]></title>
            <link>https://medium.com/@majidahmadkhan/k-nearest-neighbors-the-power-of-proximity-47bed5436ffc?source=rss-e0e6bbefc491------2</link>
            <guid isPermaLink="false">https://medium.com/p/47bed5436ffc</guid>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <category><![CDATA[k-nearest-neighbours]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Majid Ahmad Khan]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 23:28:49 GMT</pubDate>
            <atom:updated>2023-02-01T23:30:10.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*ui_INSXWV-MBMQ7nzcQaOw.png" /></figure><p>K-Nearest Neighbors (KNNs) is a simple yet powerful machine learning algorithm widely used for classification and regression tasks. It identifies the K nearest data points to a given input and uses them to make predictions based on the majority of their class or the average of their values. KNNs are known for their ease of implementation, ability to handle multi-class problems and versatility in handling different data structures. In this article, we’ll delve into the mechanics of KNNs, understand their key strengths and weaknesses, and explore various applications and use cases in real-world scenarios</p><p>Okay, let us dive into how we should implement KNNs. The basic algorithm of KNNs can be summarized as follows:</p><p>1. A positive integer k is specified, along with a new sample<br>2. We select the k entries in our database which are closest to the new sample<br>3. We find the most common classification of these entries<br>4. This is the classification we give to the new sample</p><h4>How it works</h4><p>KNN is a machine learning algorithm used for classification. It involves finding the class of an unknown data point (blue star, fig. 1) by taking a vote from the K (in this case, K=3) nearest neighbors in a given data spread (red circles and green squares). The nearest neighbors are determined by enclosing the unknown data point in a circle with a radius that only includes K data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*j8ELqRMKqVb8Up8ZLCSY7g.png" /><figcaption>Fig. 1</figcaption></figure><p>In this case, the three closest data points to the unknown blue star are all red circles. So, it can be confidently classified as a red circle. The choice of K, which determines the number of nearest neighbors to classify an unknown data point is crucial in the KNN algorithm and the best value for K should be determined based on various factors.</p><h4>Choosing the value of factor K</h4><p>The K value in KNN determines the number of nearest neighbors to consider when classifying an unknown data point. The process of calculating distances between test points and training data points is computationally expensive, which makes KNN a “lazy learning” algorithm. The choice of K can greatly affect the performance of KNN, and there is no pre-defined method to determine the optimal value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*I7vyIdgez6BZaIkXpAkauA.png" /><figcaption>Fig. 2</figcaption></figure><p>As you see in fig. 2 that if we choose K=3, the unknown data comes out as Class B, while if K =7 is chosen then it is classified as Class A.</p><ul><li>K value has a significant impact on the performance of KNN</li><li>There is no pre-defined method to determine the optimal value of K</li><li>A common approach is to initialize with a random K value and evaluate the error rate for different values in a defined range</li><li>Small K values result in unstable decision boundaries</li><li>Large K values lead to smoother decision boundaries</li><li>Optimal K is chosen as the one with the minimum error rate by plotting the error rate against K in a defined range.</li></ul><h4>Implementation</h4><p>To implement KNN I am using a dataset of diabetes.csv which predicts if a person has diabetes based on range of features(see fig.3). To read the dataset use the following code(make sure diabetes.csv file is in same location as your code).</p><pre>data=pd.read_csv(“diabetes.csv”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*-xBMoUNQzRAh6PbK1Hg4Ow.png" /><figcaption>fig. 3</figcaption></figure><p><strong>Cleaning the data</strong></p><p>As we know glucose, blood pressure skin thickness, BMI or insulin levels cannot be zero for a person. To overcome this problem in the data we take the mean of the column and replace the zero values. This is how we replace the zero values using the Numpy library.</p><pre>zero_not_accepted =[‘Glucose’,’BloodPressure’,’SkinThickness’,’BMI’,’Insulin’]<br>for col in zero_not_accepted:<br> data[col]= data[col].replace(0,np.NaN)<br> mean = int(data[col].mean(skipna=True))<br> data[col] = data[col].replace(np.NaN,mean)</pre><p><strong>Splitting the data</strong></p><p>Now after cleaning the data we extract the independent variables which is also known as features(X values) and the dependent variable which in this case is whether the person has diabetes or not(Y values). After that use the train_test_split of the Sklearn library to split the data</p><pre>#extracting independent variables<br>X = data.iloc[:,0:8]<br>#extracting dependent variable<br>y = data.iloc[:,8]<br><br>from sklearn.model_selection import train_test_split<br>X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)</pre><p><strong>Defining the KNN classifier</strong></p><ul><li>KNN Classifier: Implements a K-Nearest Neighbors (KNN) classifier algorithm.</li><li>Distance Calculation: Calculates the Euclidean distance between each test sample and every training sample.</li></ul><p><em>The code contains two nested loops:</em></p><p>The outer loop: It runs num_test times, where num_test is the number of test samples. For each test sample, the code calculates the distances between that test sample and all the training samples.</p><p>The inner loop: It runs num_train times, where num_train is the number of training samples. For each training sample, the code calculates the Euclidean distance between the current test sample and that training sample. The index of the training sample is also stored in a list called index.</p><p>The inner loop calculates the distances between the current test sample and all the training samples. The outer loop repeats this process for all the test samples, so the code calculates the distances between all the test samples and all the training samples.</p><ul><li>Sorting and Selecting: Sorts the distances in ascending order and selects the top K nearest neighbors.</li><li>Predictive Counting: Counts the number of nearest neighbors belonging to each class and predicts the label for the test sample based on which class has the majority.</li><li>Result: Returns a list of predicted labels for all the test samples.</li></ul><pre>def KNNClassifier(K):<br>    labels=[]<br>    num_test = X_test.shape[0]<br>    num_train = X_train.shape[0]<br>    for i in range(num_test):<br>        distance=[] <br>        index=[]<br>        for j in range(num_train):<br>            distance.append(Euclidian_Distance(X_test.iloc[i],X_train.iloc[j]))<br>            index.append(j)<br>        #dis_list = zip(distances, y_train)<br>        #sorted_list = sorted(dis_list)<br>        df1=pd.DataFrame({&#39;Dis&#39;:distance,&#39;ind&#39;:index})<br>        df1=df1.sort_values(&#39;Dis&#39;)<br>        zero_count = 0<br>        one_count = 0<br>        for i in df1[&#39;ind&#39;].head(K):<br>            if y_train.iloc[i] == 1:<br>                one_count += 1<br>            else:<br>                zero_count += 1<br>        if one_count &gt;= zero_count:<br>            labels.append(1)<br>        else:<br>            labels.append(0)<br>    return labels</pre><h4>Conclusion</h4><p>KNN, a simple yet powerful algorithm, uses the power of neighbors to predict the unknown. It’s a go-to solution for many classification problems and is known for its ease of implementation and accuracy. Whether it’s solving a real-life problem or a computational one, KNN is always ready to be your nearest ally.</p><h4>Links</h4><p>Check out the code and dataset by clicking on the Github repo: <a href="https://github.com/code-mj12/K-Nearest-Neighbors">Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47bed5436ffc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Istio: A service mesh solution]]></title>
            <link>https://medium.com/@majidahmadkhan/istio-a-service-mesh-solution-13450f84b93e?source=rss-e0e6bbefc491------2</link>
            <guid isPermaLink="false">https://medium.com/p/13450f84b93e</guid>
            <category><![CDATA[istio-service-mesh]]></category>
            <category><![CDATA[istio]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Majid Ahmad Khan]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 11:16:54 GMT</pubDate>
            <atom:updated>2022-12-01T11:16:54.264Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Istio is a modernized service networking layer called a “service mesh” that offers a clear, language-independent method for dynamically and quickly automating application network tasks. For managing the various microservices that compensate a cloud-native application, it is a well-liked option. Istio service mesh also facilitates the data sharing and communication between those microservices.</p><p>Enterprises can protect, connect, or manage microservices with the help of Istio, which enables them to update their corporate apps more quickly and securely.</p><p>Without requiring changes to the application code, Istio controls how traffic moves between services, upholds access rules, and accumulates telemetry data. By seamlessly overlaying atop already-existing distributed applications, Istio reduces the complexity of deployment.</p><h4><strong>What are Istio service mesh benefits?</strong></h4><p>The main 3 benefits of using Istio service mesh that it improves your services’ networking performance, secure your services and improve your application performance.</p><p>· <strong>Achieve consistent service networking</strong>: Without additional development burden, your networking operators can reliably handle networking for all of their services.</p><p>· <strong>Secure your services with Istio benefits</strong>: Service-to-service security, including authentication, authorization, and encryption, can be readily implemented by your security personnel.</p><p>· <strong>Improve your application performance</strong>: Get deep visibility into your apps and implement best practices, such as canary rollouts, to determine where to concentrate your performance improvement efforts</p><h4><strong>How do Istio, Envoy, and Kubernetes work together?</strong></h4><p>Understanding Envoy and Kubernetes is essential to comprehending Istio and the its architecture. It’s not a case of Istio vs Envoy or Istio versus Kubernetes, they frequently collaborate to ensure the smooth operation of a containerized environment based on microservices.</p><p>For instance, Istio service meshes consist of a control plane and a data plane. Istio’s data plane is an expanded version of Envoy. After then, Envoy controls all incoming and outgoing communication within the Istio service mesh.</p><p>On the other side, Kubernetes is an open-source platform that automates and orchestrates many of the manual tasks associated with scaling and deploying containerized applications. Also, the main benefit of Istio is that it is platform-independent and can work alongside Kubernetes, Cloud or even on on-premise servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1RTIKlBDJ9uotF0AVCUow.png" /></figure><h4><strong>Istio and its use cases</strong></h4><p>Organizations may deploy application programs at scale using Istio. It makes network activities between services easier, including traffic control, authentication, security, auditing, and reliability. Here are a few of the most typical Istio usage examples that demonstrate its advantages:</p><p><strong>Secure cloud-native apps: </strong>With powerful identity-based authentication, authorization, and encryption, put your security efforts at the application level.</p><p><strong>Easily deploy with Kubernetes and virtual machines</strong>: Istio offers network controls and visibility for both conventional and contemporary applications, such as virtual machines and containers.</p><p><strong>Manage traffic effectively</strong>: Utilize fault injection, retries, failovers, and rich routing rules to get fine-grained control over traffic behavior.</p><p><strong>Simplify load balancing with advanced features</strong>: Use client-based forwarding and canary deployments along with automated load balancing for all of your traffic.</p><p><strong>Monitor service mesh</strong>: With the powerful tracing, monitoring, and logging features of Istio, you can gain a thorough insight of how service performance affects things upstream.</p><p><strong>Enforce policies</strong>: Utilize a pluggable policy layer and configuration API to enforce policies and implement access controls, rate limits, and quotas.</p><h4><strong>Installation and deployments</strong></h4><p>To download Istio you can extract the latest release automatically on Linux or macOS or using WSL if you are using Windows. Type the following command into your terminal</p><pre>$ curl -L https://istio.io/download Istio | sh -</pre><p>Move to the Istio package directory. For example, if the package is istio-1.20.0:</p><pre>$ cd istio-1.20.0</pre><p>Add the istioctl(The <a href="https://istio.io/latest/docs/reference/commands/istioctl">istioctl</a> client binary in the bin/ directory.) client to your path</p><pre>$ export PATH=$PWD/bin:$PATH</pre><h4>Installing Istio</h4><p>To install Instio run the the following command</p><pre>istioctl install — set profile=demo -y</pre><p>When you later deploy your application, add a namespace label to tell Istio to automatically inject Envoy sidecar proxies:</p><pre>$ kubectl label namespace default istio-injection=enabled</pre><p>Deploying sample application using kubectl</p><pre>$ kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml</pre><p>The program will launch. The Istio sidecar will deploy with each pod as it is prepared.</p><pre>$ kubectl get services</pre><pre>$ kubectl get pods</pre><p>Make sure everything has been operating properly up until this point. Run the following command and look for the page title in the response to see whether the application is active within the cluster and serving HTML pages:</p><pre>$ kubectl exec “$(kubectl get pod -l app=ratings -o jsonpath=’{.items[0].metadata.name}’)” -c ratings — curl -sS productpage:9080/productpage | grep -o “&lt;title&gt;.*&lt;/title&gt;”</pre><h4><strong>Recap</strong></h4><p>We have gain understanding of what is Istio and the service mesh benefits</p><p>We have seen how Kubernetes, Envoy and Istio works together</p><p>We have learned the use cases of Istio and how it helps developers.</p><p>Installation and deployment of a sample application on Istio</p><p><strong>References/Related links</strong></p><p>A Google article on Istio, <a href="https://cloud.google.com/learn/what-is-istio">link</a></p><p>Istio documentation on setting up Istio, <a href="https://istio.io/latest/docs/setup/getting-started/">link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13450f84b93e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kyverno: Kubernetes Policy Manager]]></title>
            <link>https://medium.com/@majidahmadkhan/kyverno-kubernetes-policy-manager-4863aba167e3?source=rss-e0e6bbefc491------2</link>
            <guid isPermaLink="false">https://medium.com/p/4863aba167e3</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-policies]]></category>
            <category><![CDATA[kyverno]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <dc:creator><![CDATA[Majid Ahmad Khan]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 06:56:55 GMT</pubDate>
            <atom:updated>2022-12-01T06:56:55.859Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What is Kyverno?</strong></h4><p>Kyverno is a tool that main goal to manage policy for Kubernetes, Kyverno literally means ‘govern’ in Greek. Also, no additional language is necessary to write policies because Kyverno manages them like Kubernetes resources. This enables managing policies using well-known tools like kubectl, git, and kustomize. In addition to ensuring OCI image supply chain security, Kyverno policies may validate, alter, and produce Kubernetes resources. As part of a CI/CD pipeline, the Kyverno CLI can be used to test policies and validate resources.</p><p>You can use Kyverno for:</p><p>· Improving cluster security by regulating policies</p><p>· Set default guidelines and regulations using tools such as kustomize.</p><p>· Performing an audit or enforcing the regulations</p><p>· Before using, validate resources and modify resources.</p><p>· Create regulations</p><p>· Overseeing Pod security</p><h4><strong>Brief Working</strong></h4><p>To simply understand how Kyverno works is that the Kubernetes API server sends a request to Kyverno to check, review, transform, or authenticate the request. Its kinds of run as an admission controller within Kubernetes cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Crm4M0xTI2Rd4x3UCcjjA.jpeg" /><figcaption><em>Image Source: CNCF Kyverno Webinar</em></figcaption></figure><p>It is simple to define the policies in Kyverno, and you will discover that it is quite similar to defining any other Kubernetes object.</p><h4>Installing Kyverno</h4><p>You can directly apply the manifests or use the official Helm chart to install Kyverno. The installation process using Helm will be described in this post. It is a good idea to review and consider how you want the security and policy enforcement to be carried out inside your cluster before deploying.</p><p>The validationFailureAction and podSecurityStandard are the two recommended options to take into account before installing. Based on the current but soon-to-be-deprecated Kubernetes Pod Security Standards, the podSecurityStandard setting manages the security profile for Pods.</p><p>From the following three choices, you may select:</p><p><strong>Baseline</strong>: Minimum restriction designed to prevent ordinary privilege escalation is called the baseline.</p><p><strong>Restricted</strong> — provides further hardening of the cluster and a considerably higher security standard</p><p><strong>Custom</strong> — The policies can be altered to meet your needs.</p><p>When installing Kyverno with Helm, the Baseline profile will be picked by default if no choice is supplied. You have two choices for the validationFailureAction setting: enforce or audit mode. When enforced, a request will be denied if a policy violation happens as a result of the configured pod security.</p><p>The resource request will be approved in audit mode, and the policy violation will be recorded. If no other parameter is supplied, audit mode is the default.</p><p>To install first add Helm git repository by running the following command:</p><pre>$ helm repo add kyverno https://kyverno.github.io/kyverno/</pre><p>This will add your helm ‘Kyverno’ repo. Now run an update command.</p><pre>$ helm repo update</pre><p>Installing Kyverno in its own namespace is recommended. Additionally, you can install the pod security choices according on the level of protection you choose.</p><p>We will use the policy parameters’ presets from the Helm chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*jjTf82AhlX_21rRotgaVsw.png" /></figure><p>You will get the install notes and a policy setup output if the installation is successful. You can use this command to monitor the Kyverno pod.</p><pre>$ kubectl -n kyverno get pods</pre><p>Something of this sort will appear to tell the name, status and the age of Kyverno pod.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*19_JeI4DjaX4f7Q9bdpehw.png" /><figcaption>Display after running th command</figcaption></figure><h4>Types of policies in Kyverno</h4><p>There are two main categories of webhooks in Kubernetes: validating webhooks and mutating webhooks.</p><p>However, in addition to the validating and mutating webhooks, Kyverno also provides policy Generation, which can be used to produce configuration depending on an event, when it is installed as an admission controller.</p><p>We will discuss each of the three kinds in detail so that you may better understand how, where, and why they are employed.</p><p><strong>Validate</strong>: With the validation kind of policy, when a request is received, it is first validated by the admission controller, and depending on the binary result status, a response is either approved or denied.</p><p><strong>Mutate: </strong>If the object isn’t compliant with the policy defined by Kyverno when the request is sent to the Kubernetes API, it will be modified and changed before being applied and written to the ETCD database.</p><p>There are three ways to change the request when using the mutation webhook. The JSON patch technique, the Kubernetes strategic merge, or a set conditional for the desired end state can all be used to accomplish this.</p><p><strong>Generate: </strong>As previously mentioned, Kyverno can be used to generate a policy based on a cluster event.</p><h4><strong>Recap</strong></h4><p>· You’ve gained knowledge of Kyverno and how to improve cluster security.</p><p>· Studied the inner workings of Kyverno and how it interfaces with Kubernetes</p><p>· Kyverno was set up and installed on a cluster.</p><p>· Discovered several webhooks and policy types</p><h4>References/Related Links</h4><p>Kyverno Policy Management in Kubernetes by Kristijan Mitevski, <a href="https://www.squadcast.com/blog/kyverno-policy-management-in-kubernetes">link</a></p><p>Kyverno <a href="https://kyverno.io/">website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4863aba167e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buildah: An alternative to Docker]]></title>
            <link>https://medium.com/@majidahmadkhan/buildah-an-alternative-to-docker-3c2f8664520d?source=rss-e0e6bbefc491------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c2f8664520d</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[container-images]]></category>
            <category><![CDATA[buildah]]></category>
            <dc:creator><![CDATA[Majid Ahmad Khan]]></dc:creator>
            <pubDate>Tue, 25 Oct 2022 15:14:51 GMT</pubDate>
            <atom:updated>2022-10-25T15:14:51.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*SOgPjpKYhF7nKszuxqwRuw.png" /></figure><h3>Introduction</h3><p>Buildah is a tool from Redhat community of Linux that allows to build containers that are compatible with Open Container Initiative (OCI) which means they are compatible with popular container orchestration tools such as Kubernetes. Buildah allows you to build containers with fine-grained specifications, which means you can create resourceful container images that does not gobble up your system resources. Also, the added benefit of using command line to create your container is that your container images are much secure.</p><h3>Why Buildah</h3><p>Buildah uses a command line interface (CLI) to build container images which means it can build these images without Dockerfiles. Also, you could create image from any snapshot (kind of like a starting point where some parameters for image is already predefined)</p><p>Buildah build some of the very small images due to the fact that it does not include any overheads like build tools in the images which allows for loading and transferring the images much easier as they are smaller.</p><p>It is compatible with Dockerhub because of its compatibility with Open Container Initiative (OCI) so if a client needs to shift to Dockerhub he can easily move out.</p><p>Buildah is flexible enough to create images without Dockerfiles and to include different development tools into the build phase. It is also efficient enough to use build tools that aren’t internal to the image, which makes it possible to innovate and implement new concepts more quickly. Container images can be easily developed and expanded upon using only the tools and procedures required to just get them running.</p><p>Buildah has main advantage that it can run daemonless unlike Dockerhub which requires daemon which take up your computer resources considerably. Also, Buildah’s cousin Podman which was created after has GUI interface but it creates images with root permission and this may result in security issues.</p><h3>Installation</h3><p>Installation of Buildah is very easy in linux as it is quite developed and has a strong community behind it.</p><pre>sudo apt update &amp;&amp; apt install buildah</pre><h3>Building and publishing an image</h3><p>The CLI interface for creating an image is quite similar to the docker one, if not the same. Consider the following straightforward code.</p><pre>FROM aphine<br>LABEL name=firstapp<br>COPY index.html /usr/share/aphine/html</pre><pre>buildah build — tg localhost:4000/firstapp</pre><pre>Buildah publish –tg localhost:4000/firstapp</pre><h3>Conclusion</h3><p>As you can see Buildah is an efficient tool to create efficient containers with added benefits of security and images which are made with fine grained specs which results in containers images being smaller in size</p><h3>Resources</h3><p><a href="https://www.redhat.com/en/topics/containers/what-is-buildah">RedHat’s official article</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c2f8664520d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring a NodeJS application on Docker]]></title>
            <link>https://medium.com/@majidahmadkhan/configuring-a-nodejs-application-on-docker-df707ee77091?source=rss-e0e6bbefc491------2</link>
            <guid isPermaLink="false">https://medium.com/p/df707ee77091</guid>
            <dc:creator><![CDATA[Majid Ahmad Khan]]></dc:creator>
            <pubDate>Sun, 18 Sep 2022 22:54:21 GMT</pubDate>
            <atom:updated>2023-03-07T21:40:30.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-1v06fdYmvlmE5-_G0Y0w.jpeg" /></figure><p>In this tutorial, we are going to look at how to run and configure a docker to run a NodeJS application.</p><h4>Building a simple NodeJS webpage</h4><p>Firstly, lets build simple NodeJS webpage. For that, I am writing a simple NodeJS code that just displays simple text—here using express.get function we display the book and show the title.</p><pre>const express = require(&#39;express&#39;)</pre><pre>const cors = require(&#39;cors&#39;)</pre><pre>const app = express()</pre><pre>app.use(cors())</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>res.json([<br>{<br>&quot;id&quot;:&quot;1&quot;,<br>&quot;title&quot;:&quot;Book Review: Harry Potter&quot;<br>},<br>{<br>&quot;id&quot;:&quot;2&quot;,<br>&quot;title&quot;:&quot;Game Review: Call Of Duty&quot;<br>},<br>{<br>&quot;id&quot;:&quot;3&quot;,<br>&quot;title&quot;:&quot;Show Review: Dark&quot;<br>},<br>{<br>&quot;id&quot;:&quot;4&quot;,<br>&quot;title&quot;:&quot;Show Review: Game of Thrones&quot;<br>}<br>])<br>})</pre><p>We also have to open a listening port so we can listen to request from clients such as web browser accessing a web page. Add this line of code to the above.</p><pre>app.listen(5000, () =&gt; {</pre><pre>console.log(&#39;listening for requests on port 5000&#39;)</pre><pre>})</pre><h4>Configuring the docker file</h4><p>To configure the docker file for the NodeJS application first we use the FROM command which is used to specify the NodeJS image, specify the working directory and use the COPY command to copy contents, then use RUN command to install the required libraries, also use the command EXPOSE to open the listening port.</p><pre>FROM node:17-alpine</pre><pre>WORKDIR /app</pre><pre>COPY . .</pre><pre>RUN npm install</pre><pre>EXPOSE 5000</pre><pre># required for docker desktop port mapping</pre><pre>CMD [&quot;node&quot;, &quot;app.js&quot;]</pre><p>The whole source will be available in my GitHub repository with the required package file. Click <a href="https://github.com/code-mj12/Nodejsdocker/tree/main">here</a>.</p><p>Now open the terminal and use the following command, this pulls the latest NodeJS image from the Docker hub(Note this command is not necessary). Before running this command just make sure you have installed Docker desktop and WSL2.</p><pre>docker pull node</pre><p>Here you can see on Docker desktop about the Node image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNLhsjiUygRclacg9AldSw.png" /></figure><p>Now run this command to build your NodeJS application image in the terminal. It will take time if you are running it for the first time.</p><pre>docker build -t nodejsapp .</pre><p>Now on the Docker desktop, you can see nodejsapp image being shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0J7bAIxmqGzfPqbWnbPi1A.png" /></figure><p>Now hover your cursor on the nodejsapp image and run it, open the optimal setting, and write the host port. The host port is different from the container port as the host port is written in the browser. The host port and container port can be the same. Now click run to run a container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*mih09ch4d6fmXi6L_7A8KA.png" /><figcaption>I have to use the same host port as the container listening port.</figcaption></figure><p>Now go to your browser and type localhost:5000, you would see your NodeJS webpage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONZ7KgXaEgGSeIka_0y0mA.png" /></figure><p>Congratulation, you have created your first NodeJS containerized application.</p><h3>Conclusion</h3><p>At first, I did not feel that I should complicate my everyday life with another technology necessary for development. Docker has shown that you can run applications in the totally isolated environments within seconds. After this and the fact that I can test against the same infrastructure on my local computer, they have convinced me to use Docker daily. I hope the above workflow helps others also to get to love Docker for its benefits.</p><h3>Resources</h3><p><a href="https://youtu.be/t9YuqwGYUUg">What is docker by Wolfgang</a></p><p>Docker by Net Ninja: <a href="https://youtube.com/playlist?list=PL4cUxeGkcC9hxjeEtdHFNYMtCpjNBm3h7">link</a></p><p><a href="https://github.com/code-mj12/Nodejsdocker">NodeJS app Github repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df707ee77091" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>