<?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 Ibrahim on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Ibrahim on Medium]]></description>
        <link>https://medium.com/@mibrahimzia48?source=rss-f65514797bf8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*w9EHXVM2Ho3s7CwV</url>
            <title>Stories by Muhammad Ibrahim on Medium</title>
            <link>https://medium.com/@mibrahimzia48?source=rss-f65514797bf8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:04:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mibrahimzia48/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[Setting Up a Monitoring System with Prometheus and Grafana]]></title>
            <link>https://medium.com/@mibrahimzia48/setting-up-a-monitoring-system-with-prometheus-and-grafana-e67a78d17c4a?source=rss-f65514797bf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e67a78d17c4a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[grafana-prometheus]]></category>
            <category><![CDATA[prometheus-monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Muhammad Ibrahim]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 17:37:07 GMT</pubDate>
            <atom:updated>2024-11-24T17:37:07.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTYKX-lf1xJ9WDnVvgty7A.png" /></figure><p><strong>Introduction</strong><br>In the world of DevOps, monitoring is vital for maintaining application reliability and performance. Prometheus and Grafana are two popular open-source tools for building a robust monitoring system. While Prometheus collects and stores metrics, Grafana visualizes them with customizable dashboards.</p><p>In this tutorial, you’ll learn how to set up a monitoring system using Prometheus and Grafana to monitor a sample application.</p><h3>Prerequisites</h3><p>Before we start, ensure you have the following:</p><ul><li>A Linux-based system or a compatible container runtime (like Docker).</li><li>Basic knowledge of terminal commands.</li><li>A sample application to monitor (or use a simulated application like Node Exporter).</li></ul><h3>Step 1: Install Prometheus</h3><ol><li><strong>Download Prometheus</strong><br>Download the latest version of Prometheus from the official website:</li></ol><pre>wget https://github.com/prometheus/prometheus/releases/download/&lt;version&gt;/prometheus-&lt;version&gt;.linux-amd64.tar.gz</pre><p><strong>2. Extract and Move Files</strong></p><pre>tar -xvzf prometheus-&lt;version&gt;.linux-amd64.tar.gz  <br>cd prometheus-&lt;version&gt;.linux-amd64  <br>sudo mv prometheus /usr/local/bin/  <br>sudo mv promtool /usr/local/bin/</pre><p><strong>3. Create Configuration File</strong></p><p>Edit the prometheus.yml file to define scrape targets (e.g., Node Exporter or any custom application exposing metrics). Here&#39;s a simple example:</p><pre>scrape_configs:<br>  - job_name: &#39;node_exporter&#39;<br>    static_configs:<br>      - targets: [&#39;localhost:9100&#39;]</pre><p><strong>4. Run Prometheus</strong></p><pre>prometheus --config.file=prometheus.yml</pre><p>Visit http://localhost:9090 to verify Prometheus is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16CGEWlO6tMk6U4td1RcLQ.png" /></figure><h3>Step 2: Install Grafana</h3><ol><li><strong>Download and Install Grafana</strong><br>Follow the instructions on the Grafana installation page:</li></ol><pre>sudo apt-get install -y software-properties-common  <br>sudo add-apt-repository &quot;deb https://packages.grafana.com/oss/deb stable main&quot;  <br>sudo apt-get update  <br>sudo apt-get install grafana</pre><p><strong>2. Start Grafana</strong></p><pre>sudo systemctl start grafana-server  <br>sudo systemctl enable grafana-server</pre><p>Visit http://localhost:3000 and log in with the default credentials (admin/admin).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5Tdx_mD6cJOMGGy_mMy1Q.png" /></figure><h3>Step 3: Connect Prometheus to Grafana</h3><ol><li><strong>Add Prometheus as a Data Source</strong></li></ol><ul><li>In Grafana, navigate to <strong>Configuration &gt; Data Sources</strong>.</li><li>Click <strong>Add Data Source</strong> and select <strong>Prometheus</strong>.</li><li>Enter http://localhost:9090 as the URL and save the configuration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhX-IjhzzK-6k5D8anivOA.png" /></figure><p><strong>2. Verify the Connection</strong><br>Create a new dashboard and add a panel to visualize metrics from Prometheus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2atwrmewa4DjRg-ORyUVSQ.png" /></figure><h3>Step 4: Visualizing Metrics with Dashboards</h3><ol><li><strong>Create a Custom Dashboard</strong></li></ol><ul><li>In Grafana, go to <strong>Dashboards &gt; New Dashboard &gt; Add a New Panel</strong>.</li><li>Select a metric (e.g., node_cpu_seconds_total) from Prometheus.</li><li>Customize the graph as needed and save the dashboard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTnwcCxiiK58lvtCaCHf3Q.png" /></figure><p><strong>2. Import Pre-Built Dashboards</strong><br>Grafana has a library of pre-built dashboards. To import one:</p><ul><li>Navigate to <strong>Dashboards &gt; Import</strong>.</li><li>Enter the dashboard ID from the <strong>Grafana Dashboard Repository</strong>.</li></ul><h3>Step 5: Setting Up Alerts</h3><p>Prometheus and Grafana can send alerts based on metric thresholds.</p><ol><li><strong>Prometheus Alerting Rules</strong><br>Add an alerting rule in prometheus.yml:</li></ol><pre>groups:<br>  - name: example_alert<br>    rules:<br>      - alert: HighCPUUsage<br>        expr: node_cpu_seconds_total &gt; 80<br>        for: 2m<br>        labels:<br>          severity: critical<br>        annotations:<br>          summary: &quot;High CPU usage detected!&quot;</pre><p><strong>2. Grafana Alerts</strong></p><ul><li>Go to <strong>Alerting &gt; Notification Channels</strong> in Grafana.</li><li>Configure email, Slack, or webhook notifications.</li></ul><h3>Step 6: Monitor the System</h3><p>With Prometheus and Grafana connected, you now have a fully functional monitoring system.</p><ul><li>Use dashboards to analyze real-time metrics.</li><li>Set alerts for critical issues.</li><li>Continuously improve dashboards based on your needs.</li></ul><p><strong>Conclusion</strong><br>By setting up Prometheus and Grafana, we can establish a solid foundation for monitoring our applications. This setup ensures that you are proactive in addressing potential issues, making it an essential component of any DevOps workflow. With these tools in place, we can expand monitoring to include logs, traces, and more advanced observability features.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e67a78d17c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying AWS Infrastructure with Terraform: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@mibrahimzia48/deploying-aws-infrastructure-with-terraform-a-step-by-step-guide-d1a4d71bdec7?source=rss-f65514797bf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1a4d71bdec7</guid>
            <category><![CDATA[terrraform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Muhammad Ibrahim]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 18:26:17 GMT</pubDate>
            <atom:updated>2024-10-11T18:26:17.358Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hXG-jh2cAzzwgCwYFOZEQ.jpeg" /></figure><p>Terraform is a powerful infrastructure-as-code tool that allows you to automate the deployment and management of your cloud resources. Whether you’re provisioning EC2 instances, S3 buckets, or entire VPCs, Terraform makes cloud infrastructure easier to manage, version, and scale.</p><p>In this tutorial, I will guide you through deploying AWS infrastructure (an EC2 instance) using Terraform. By the end, you’ll know how to write Terraform configuration files, apply them to create resources in AWS, and manage your infrastructure with code.</p><h3>Step 1: Install Terraform</h3><p>Before you start, you need to have <strong>Terraform</strong> installed on your local machine. You can download the latest version from the official Terraform website.</p><p>For macOS (using Homebrew)</p><pre>brew install terraform</pre><p>For windows (using choclatey)</p><pre>choco install terraform</pre><h3>Step 2: Configure AWS Credentials</h3><p>Terraform requires AWS credentials to interact with your AWS account. You can configure credentials in several ways, but the simplest method is by using the AWS CLI.</p><ol><li><strong>Install the AWS CLI</strong> (if not already installed):</li></ol><pre>sudo apt-get install awscli # for Linux<br>brew install awscli # for macOS</pre><p>2. <strong>Configure the AWS CLI</strong>:</p><pre>aws configure</pre><p>You’ll be prompted to enter your <strong>AWS Access Key ID</strong>, <strong>Secret Access Key</strong>, <strong>Region</strong>, and <strong>Output Format</strong>. These credentials will allow Terraform to authenticate with AWS.</p><h3>Step 3: Write Your First Terraform Configuration</h3><p>Let’s create a simple Terraform configuration to launch an EC2 instance in AWS.</p><h4>Create a Directory for Your Terraform Files:</h4><pre>mkdir my-terraform-project<br>cd my-terraform-project</pre><h4>Create a main.tf File:</h4><p>In the main.tf file, define the provider and the resource you want to create (in this case, an EC2 instance):</p><pre># main.tf<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-west-2&quot; <br>}<br><br>resource &quot;aws_instance&quot; &quot;my_ec2&quot; {<br>  ami           = &quot;ami-0c55b159cbfafe1f0&quot; <br>  instance_type = &quot;t2.micro&quot;<br><br>  tags = {<br>    Name = &quot;TerraformExampleInstance&quot;<br>  }<br>}</pre><p>Code explanation:</p><ul><li>The <strong>provider</strong> block specifies that we’re using AWS as our cloud provider.</li><li>The <strong>aws_instance</strong> block defines the resource (an EC2 instance) with attributes such as ami and instance_type. We also add a tag to name the instance.</li></ul><h3>Step 4: Initialize Terraform</h3><p>Before applying any configuration, you need to initialize Terraform. This downloads the necessary provider plugins (in this case, AWS).</p><pre>terraform init #this command will intialize the project directory</pre><h3>Step 5: Plan and Apply the Configuration</h3><p>After initialization, you can review your configuration by running a <strong>plan</strong>. This command doesn’t create any resources but shows what Terraform will do.</p><pre>terraform plan</pre><p>if the plan is good then apply the configuration.</p><pre>terraform apply</pre><p>Terraform will ask for confirmation. Type yes, and Terraform will create the EC2 instance as defined in the main.tf file.</p><h3>Step 6: Verify the Deployed Infrastructure</h3><p>Once the Terraform apply is complete, you can log into your AWS Management Console and navigate to the <strong>EC2 Dashboard</strong>. You should see a running EC2 instance named TerraformExampleInstance.</p><p>You can also verify using the AWS CLI:</p><pre>aws ec2 describe-instances --filters &quot;Name=tag:Name,Values=TerraformExampleInstance&quot;</pre><p>This command will show details of your EC2 instance, including its public IP, instance ID, and status.</p><h3>Step 7: Destroying the Infrastructure</h3><p>Terraform not only helps create infrastructure but also makes it easy to tear it down when you’re done. Use the terraform destroy command to remove the resources you created:</p><pre>terraform destroy</pre><p>Terraform will prompt you to confirm the destruction of the resources. After typing yes, Terraform will terminate the EC2 instance and delete any associated resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1a4d71bdec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Kubernetes: Orchestrating Containers for Modern Applications]]></title>
            <link>https://medium.com/@mibrahimzia48/a-beginners-guide-to-kubernetes-orchestrating-containers-for-modern-applications-1785aca50a67?source=rss-f65514797bf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1785aca50a67</guid>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Muhammad Ibrahim]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 18:13:58 GMT</pubDate>
            <atom:updated>2024-09-09T18:16:53.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*RceZYoeqrosUKjVtMjd2LA.png" /></figure><p>Kubernetes, often abbreviated as K8s, is one of the most powerful tools for managing containerized applications. As businesses are transitioning from traditional monolithic architectures to microservices, Kubernetes has now become essential for orchestrating and managing containers at scale. In this blog, we will explore the core concepts of Kubernetes, how it works, and why it’s important for modern applications.</p><h3>What is Kubernetes?</h3><p>Kubernetes is an <strong>open-source container orchestration platform</strong> that automates the deployment, scaling, and management of containerized applications. Originally developed by Google, it was donated to the <strong>Cloud Native Computing Foundation (CNCF)</strong>, and it’s now widely used by organizations of all sizes.</p><p>At its core, Kubernetes helps you manage applications that are made of hundreds or even thousands of containers across a distributed infrastructure. And it helps you manage them in different environments like physical machines, virtual machines, Cloud, or even hybrid deployment environments. Whether you are running containers on a single node or across multiple cloud providers, Kubernetes abstracts away the underlying complexity and provides a unified platform for managing them.</p><h3>Why Do We Need Kubernetes?</h3><p>Containers are lightweight, portable, and provide isolated environments for running applications like docker containers. But when you scale them across multiple instances, managing their lifecycle becomes challenging.</p><p>In case of docker containers some of the problems faced were:</p><ul><li><strong>manual Scaling</strong>: Docker allows you to run multiple containers, but scaling them (adding or removing instances) is manual. You have to start and stop containers yourself.</li><li><strong>No Auto-Scaling</strong>: Docker lacks the ability to automatically scale containers based on traffic or resource usage.</li><li><strong>No Self-Healing</strong>: Docker does not detect and restart services</li><li><strong>No Built-In Load Balancing</strong>: Docker does not distributes traffic across multiple containers to ensure high availability.</li><li><strong>Static Networking:</strong> Docker’s networking is relatively simple and static. To communicate between containers, you need to know their IP addresses or manually configure links between them.</li><li><strong>Manual Updates</strong>: With Docker, updating a containerized application often requires stopping the existing container and deploying a new one, which can cause downtime.</li><li><strong>No Built-In Rollbacks</strong>: Docker lacks the ability to roll back to a previous version of an application easily.</li></ul><p>Kubernetes solves these problems by offering:</p><ul><li><strong>Automated Scaling</strong>: Automatically adjusts the number of running containers based on demand.</li><li><strong>Service Discovery</strong>: Kubernetes offers built-in <strong>DNS-based service discovery</strong>, allowing containers (pods) to communicate with each other using service names without needing to know the IP addresses.</li><li><strong>Self-Healing</strong>: Detects and restarts failed containers.</li><li><strong>Load Balancing</strong>: Distributes traffic across multiple containers to ensure high availability.</li><li><strong>Declarative Configuration</strong>: You define the desired state, and Kubernetes works to maintain it.</li><li><strong>Rolling Updates</strong>: Kubernetes can perform <strong>rolling updates</strong>, where new versions of containers are deployed incrementally, without downtime.</li><li><strong>Automatic Rollbacks</strong>: If an update causes issues, Kubernetes can automatically <strong>roll back</strong> to the previous version.</li><li><strong>Automated Scaling</strong>: Kubernetes offers <strong>Horizontal Pod Autoscaling (HPA)</strong>, allowing containers to scale up and down automatically based on metrics like CPU or memory usage.</li><li><strong>Declarative Scaling</strong>: Kubernetes allows you to declare the desired state (e.g., “I want 5 replicas of this service”), and it will maintain that state even in case of failures.</li></ul><h3>Core of K8S</h3><p>Understanding Kubernetes begins with a few essential concepts that form the building blocks of the platform:</p><h4><strong>1. Nodes and Clusters</strong></h4><p>A <strong>Kubernetes cluster</strong> is composed of nodes:</p><ul><li><strong>Master Node</strong>: Responsible for controlling the cluster. It runs critical components such as the API server, scheduler, and controller manager and etcd. These will be discussed later.</li><li><strong>Worker Nodes</strong>: These nodes are where your application’s containers run. Each worker node has a <strong>Kubelet</strong> process that communicates with the master node and execute some task and it also ensures the containers are running as expected.</li></ul><h4>2. Pods</h4><p>A <strong>pod</strong> is the smallest deployable unit in Kubernetes. It’s a wrapper for one or more containers that share the same resources (e.g., network and storage). Even though we deploy containers, Kubernetes operates at the pod level, which can contain a single container or multiple tightly coupled containers. tightly coupled meaning pod containing multiple containers which are independent and need to work together to perform a certain task.</p><h4>3. Deployments</h4><p>A <strong>Deployment</strong> defines how Kubernetes should create and manage pods. It is a higher-level abstraction that allows you to:</p><ul><li>Deploy a desired number of replicas of a pod.</li><li>Automatically update or roll back containers.</li><li>Ensure high availability by distributing pods across multiple nodes.</li></ul><p>Example of a simple deployment YAML file:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  labels:<br>    app: vote<br>  name: vote<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: vote<br>  template:<br>    metadata:<br>      labels:<br>        app: vote<br>    spec:<br>      containers:<br>      - image: dockersamples/examplevotingapp_vote<br>        name: vote<br>        ports:<br>        - containerPort: 80<br>          name: vote</pre><h4>4. Services</h4><p><strong>Services</strong> in Kubernetes provide a stable endpoint (IP address or DNS) to access a set of pods. Since pods are ephemeral and can be restarted or replaced, a service ensures that clients can still reach the application without needing to track the individual pod IPs.</p><p>There are different types of services:</p><ul><li><strong>ClusterIP</strong>: Exposes the service within the cluster (default).</li><li><strong>NodePort</strong>: Exposes the service on a static port on each node.</li><li><strong>LoadBalancer</strong>: Integrates with cloud providers to expose the service externally.</li></ul><h4>5. Ingress</h4><p>While services can expose applications, <strong>Ingress</strong> provides a more flexible way to route external HTTP/S traffic to services within the cluster. It can perform URL-based routing and handle SSL termination, making it a vital component for web applications.</p><p>Example of a simple Ingress resource:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: my-ingress<br>spec:<br>  rules:<br>  - host: myapp.example.com<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: my-app<br>            port:<br>              number: 80</pre><h4>6. ConfigMaps and Secrets</h4><p><strong>ConfigMaps</strong> and <strong>Secrets</strong> are Kubernetes resources used to manage configuration data and sensitive information:</p><ul><li><strong>ConfigMaps</strong>: Store non-sensitive configuration data as key-value pairs.</li><li><strong>Secrets</strong>: Store sensitive data such as passwords or API keys, and the data is base64-encoded for security.</li></ul><h4>7. Horizontal Pod Autoscaling (HPA)</h4><p>Kubernetes offers <strong>autoscaling</strong> based on metrics like CPU or memory usage through the <strong>Horizontal Pod Autoscaler (HPA)</strong>. If the load on your application increases, Kubernetes can automatically scale up the number of pods, and similarly, scale down when the load decreases. It is called <strong>horizontal</strong> because it <strong>scales out</strong> the application by adding or removing <strong>instances</strong> of pods (increasing or decreasing the number of pods), as opposed to <strong>vertical scaling</strong>, which would involve increasing the resources (CPU, memory) allocated to individual pods.</p><pre>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: my-app-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: my-app<br>  minReplicas: 2<br>  maxReplicas: 10<br>  targetCPUUtilizationPercentage: 80</pre><h3>How Kubernetes Works: Key Components</h3><p>To understand Kubernetes’ architecture, it is important to grasp a few key components:</p><ul><li><strong>API Server</strong>: The API server is the front-end for the Kubernetes control plane, exposing Kubernetes API to users and other components.</li><li><strong>etcd</strong>: This is the database where Kubernetes stores all its configuration data and the current state of the cluster. In case disaster recovery it come in handy.</li><li><strong>Scheduler</strong>: The scheduler ensures that pods are assigned to the appropriate nodes based on available resources and constraints.</li><li><strong>Controller Manager</strong>: It watches over the state of the cluster and makes adjustments to ensure the desired state is met.</li><li><strong>Kubelet</strong>: An agent that runs on every worker node and ensures that the containers are running as per the instructions from the control plane.</li></ul><h3>The Benefits of Kubernetes for Modern Applications</h3><p>Kubernetes has transformed how modern applications are developed, deployed, and managed. Here are the key benefits:</p><ol><li><strong>Portability</strong>: Kubernetes abstracts away the underlying infrastructure, allowing you to run workloads on any cloud provider or on-premises.</li><li><strong>Scalability</strong>: Kubernetes makes it easy to scale applications up or down based on demand, optimizing resource usage.</li><li><strong>Resiliency</strong>: With self-healing, Kubernetes ensures that failed containers are automatically replaced, keeping your application highly available.</li><li><strong>DevOps Integration</strong>: Kubernetes integrates seamlessly with CI/CD pipelines, making it an essential tool in the DevOps ecosystem.</li></ol><h3>Conclusion</h3><p>Kubernetes simplifies the management of containerized applications in a complex, distributed environment. The ability to automate scaling, recovery, and deployment has made it an essential tool for modern applications. Whether you’re running a simple web application or a large-scale microservices architecture, Kubernetes provides the tools and flexibility to run it efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1785aca50a67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Implementing Model Training using Linear Regression]]></title>
            <link>https://medium.com/@mibrahimzia48/understanding-and-implementing-model-training-using-linear-regression-ef02a0f92202?source=rss-f65514797bf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef02a0f92202</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Muhammad Ibrahim]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 18:22:56 GMT</pubDate>
            <atom:updated>2023-08-14T18:22:56.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PAqzvCxPjpDN8RC9HQw45w.jpeg" /></figure><p>Predicting financial indicators is one of the applications of machine learning. Following my previous article on fundamentals of Machine Learning <a href="https://medium.com/@mibrahimzia48/a-brief-introduction-to-machine-learning-5179680f3bad">Intro to ML,</a> in this article, we will walk through a code snippet that demonstrates the process of model training to predict coffee prices using historical data. The data is taken from <a href="https://www.kaggle.com/datasets/timmofeyy/coffee-prices-historical-data?resource=download">Kaggle</a>. We will explore the basic concepts of the code, including data preprocessing, model selection, training, and evaluation.</p><p><strong>1. Importing Libraries and Loading Data</strong></p><p>The code begins by importing the necessary libraries: ‘pandas’ for data manipulation, ‘numpy’for numerical operations, and various modules from the ‘sklearn’ library for machine learning tasks. The historical coffee price data is loaded from a CSV file using the ‘pd.read_csv()’ function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*8wEYMZ2_9-_P17KCXKExsg.png" /></figure><p><strong>2. Data Exploration and Preprocessing</strong></p><p>The dataset is displayed to understand its structure. It consists of two columns: ‘date’ and ‘value’, where ‘date’ represents the date of the data point and ‘value’ represents the coffee price. However, there are missing values (NaN) in the ‘value’ column.</p><p>The missing values in the ‘value’ column are then replaced with the mean value of the column using the ‘fillna()’ function. This ensures that the missing values are filled with a reasonable estimate that doesn’t introduce bias into the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*sfea2LdOz4VwoenN_DOJng.png" /></figure><p><strong>3. Data Splitting</strong></p><p>The dataset is divided into features (X) and target (Y) variables. The ‘date’ column is dropped from the features, and the ‘value’ column becomes the target variable. The dataset is then split into training and testing sets using the ‘train_test_split()’ function. The split is performed with a test size of 20%, and a random seed (random_state) is set for reproducibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*BSo4SQkiiZ4eQZ5RMpeW5w.png" /></figure><p><strong>4. Model Selection and Training</strong></p><p>A linear regression model is chosen as the predictive model in this example. Linear regression is a simple and interpretable model that can capture linear relationships between features and the target variable. The ‘LinearRegression()’ class from ‘sklearn’ is instantiated as ‘model’, and it is trained on the training data using the ‘fit()’ method.</p><p>However, in the given dataset ARIMA model would have better suited but for the purpose of explaining Linear regression it is not used.</p><p><strong>5. Making Predictions</strong></p><p>Using the trained model, predictions are made on the testing dataset using the ‘predict()’ method. The predicted values are stored in the ‘y_pred’ variable.</p><p><strong>6. Visualization and Evaluation</strong></p><p>The article then demonstrates two types of visualizations to evaluate the model’s performance.</p><p><strong>6.1 Actual vs. Predicted Values Line Plot</strong></p><p>A line plot is created to visualize the actual and predicted values of the coffee prices over the test set’s indices. The actual values are represented by a solid line, while the predicted values are shown using a dashed line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*P6Xa1FbsVxQZ9R31Axc8fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*9l3ibLwc2_aJ83l6_WuY0A.png" /></figure><p><strong>6.2 Scatter Plot for Evaluation</strong></p><p>A scatter plot is generated to evaluate the correlation between the actual and predicted values. Each point on the plot represents a data point from the test set. The predicted values are plotted on the x-axis, and the actual values are plotted on the y-axis. A well-performing model would have points closely aligned to the diagonal line, indicating strong predictive accuracy. In the current scenario, it is evident that the model is overfit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*qsOF46z3RfpnIwZ9sAcufw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*efKgGWSKafJa_b_qstTOew.png" /></figure><p><strong>7. Model Evaluation — R-squared (R2)</strong></p><p>The coefficient of determination (R-squared or R2) is calculated using the ‘r2_score()’ function from ‘sklearn.metrics’. R2 measures the proportion of the variance in the dependent variable (target) that is predictable from the independent variables (features). An R2 value of 1.0 indicates a perfect fit of the model to the data, implying that the model explains all the variability in the target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*KfKEasEHIsDQqwc0MWDY_g.png" /></figure><p>8. <strong>Conclusion</strong></p><p>In this code snippet, we have seen how to perform a basic model training process to predict coffee prices using historical data. We started with data loading and preprocessing, followed by data splitting, model selection (linear regression), training, prediction, and evaluation. Visualization techniques were used to gain insights into the model’s performance, and the R2 score provided a quantitative measure of the model’s accuracy.</p><p>It is visible in the above example that the model is overfitting. It’s important to note that this example showcases a simple linear regression model. In real-world scenarios, more complex models and additional features might be required to achieve accurate predictions for financial indicators. Nonetheless, this code provides a foundation for understanding the essential steps in training a predictive model for financial data.</p><p>The complete code is available at <a href="https://github.com/muhammad-12345/Linear-Reg">GitHub.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef02a0f92202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Brief Introduction to Machine Learning]]></title>
            <link>https://medium.com/@mibrahimzia48/a-brief-introduction-to-machine-learning-5179680f3bad?source=rss-f65514797bf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5179680f3bad</guid>
            <category><![CDATA[introduction-to-ml]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Muhammad Ibrahim]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 06:58:58 GMT</pubDate>
            <atom:updated>2023-07-27T07:27:18.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_qkt5zJR3r8pCACi-NSqA.jpeg" /></figure><h4>Why should you read this?</h4><p>If you are Interested in understanding one of the most transformative technologies of this century, then you should read this simple article on Introduction to Machine Learning (ML) to give you a Head start. Machine Learning is becoming increasingly threatening to humans. It is a technology that is shaping the future in many ways. And that is why you should understand the fundamentals of how ML works to become well informed in today’s AI driven world.</p><h4>What is Machine Learning?</h4><p>Machine Learning comes under the umbrella of Artificial Intelligence (AI) that teaches computers to learn from experiences without relying on predetermined equations and make decisions or predictions without being explicitly programmed for it. This process of teaching the computer on past experiences is called Model Training. The model is used for <strong>Predictions </strong>and <strong>Inferences</strong>.</p><h4>How ML works?</h4><p>These Models learn from past experiences. And these experiences are provided to the machine as input in the form of structured and well-engineered data known as <strong>training data</strong>.</p><p>Since one of the goals of Model is to predict event therefore one of the columns in the training data consists of the data that is to be predicted. This is called <strong>output variable </strong>or <strong>dependent variable</strong>.</p><p>There are two main learning methods in Machine Learning, Namely <strong>Supervised</strong> and <strong>Unsupervised learning</strong>.</p><h4>Supervised Learning</h4><p>Supervised learning uses the dataset which includes the output variable to make predictions. It contains known inputs and corresponding known outputs. Some of the techniques include <strong>classification </strong>and <strong>regression </strong>technique.</p><h4>Classification vs regression technique</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*TUy3lCMdOxBgQJ-HwYtYjA.png" /><figcaption>-javatpoint</figcaption></figure><p>Briefly summarizing the method of classification, it categorizes the data into predefined classes or categories and then trains the model to learn the underlying pattern in the data. Afterwards, assign the unseen instance to the predefined classes.</p><p>The input data consists of:</p><ul><li>Features/attributes for describing each data</li><li>Target variable/class label</li></ul><p>The training data includes instances with known class labels and the model learns to map input features to the correct class label.</p><p>Some of the common algorithms used in classification method are:</p><ul><li>Logistic regression</li><li>Decision tree</li><li>Random forest</li><li>Support vector</li><li>Naïve bayes</li></ul><p>On the other hand, regression is used to predict continuous numerical values based on input features. This is normally used when the given data is continuous and not discrete.</p><p>The training data consists of input features and target variables. The model establishes the relationship between these two through regression method.</p><p>Some of the common algorithms used in regression method are:</p><ul><li>Linear regression</li><li>Decision trees</li><li>Random forest</li><li>Support vector regression</li><li>Gradient boosting — combination of weak models</li></ul><h4>Unsupervised Learning</h4><p>Unsupervised learning does not require any output variable, instead it works by discovering patterns between input variables without any explicit guidance. A common method is <strong>clustering</strong>.</p><h4>How clustering works</h4><p>Clustering works by grouping similar data points based on Intrinsics and patterns. The aim is to maximize intra cluster similarity and minimize inter cluster similarity.</p><p>The process includes:</p><ol><li><strong>Data representation </strong>— dataset containing different data points with multiple features.</li><li><strong>Similarity measurement</strong> — grouping data in clusters requires a similarity metric to measure the similarity index between two data points. Common metrics are Euclidean distance, Manhattan distance, cosine similarity.</li><li><strong>Cluster initialization</strong> — prototype selection includes choosing appropriate clustering algorithm based on nature of data. Determining the number of clusters to be formed is always crucial. Some of the algorithms for defining number of clusters are: <br>3.1. <strong>K-Means </strong>— widely used clustering algorithm which aims to partition the data into K clusters. It then iteratively assigns each data to the nearest mean of the cluster. <br>3.2. <strong>Hierarchical Clustering </strong>— works by building a tree-like structure of nested clusters. Clusters are split or merged based on similarity.</li><li><strong>Assignment step </strong>— in this step individual data points are assigned to cluster that has the closest center. Afterwards mean, median and centroid are calculated within the cluster. This takes place in a loop until convergence.</li><li><strong>Evaluation </strong>— since clustering is an unsupervised method therefore there are no corresponding output variable against which we can test our model. Therefore, there are evaluation metrics to check out model. They include: <br>5.1. Silhouette score <br>5.2. Dunn index <br>5.3. Cohesion <br>5.4. Separation measure</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jSqQjaZV2MEpp4UaHfHgA.png" /><figcaption>-Data science team</figcaption></figure><h4>What are the phases of ML?</h4><p>Training a model involves several steps. Namely:</p><ol><li>Data preparation</li><li>Model selection</li><li>Feature engineering</li><li>Model training</li><li>Model evaluation</li><li>Model deployment</li><li>Monitoring and maintenance</li></ol><p>We will briefly discuss each step now.</p><p><strong>Data Preparation </strong>— this step involves collecting data from various sources and preprocessing them. The process of preprocessing means to:</p><ul><li>Clean data</li><li>Handle missing values</li><li>Normalizing features</li><li>Splitting the data into training and testing sets</li></ul><p><strong>Model selection </strong>— this step requires choosing an appropriate Machine Learning algorithm based on the provided dataset. If we are going supervised learning, then classification or regression otherwise clustering.</p><p><strong>Feature engineering </strong>— this step requires extracting relevant features from the data. This process requires domain knowledge and statistical analysis to analyze the data and identify any potential patterns.</p><p><strong>Model training </strong>— the step includes:</p><ul><li>Defining model architecture — which is a process of specifying the structure and design of a machine learning model. It involves number and types of layers and the activation functions.</li><li>Feeding data into model — as the name suggests, this process includes providing input to the model for it to make predictions and decisions. This process, generally, has two phases: <br>1. <strong>Training </strong>— where we provide input data with target variables on which our model is trained. <br>2. <strong>Inference </strong>— after the model is trained, we will provide our model with input data without target/output variable. The model will provide us with output variable based on already established patterns in the training phase.</li><li>Loss function and optimization — after training our model we will have to define loss function to measure the discrepancy between our model’s predicted output vs actual output/target variable. We will choose an optimization algorithm i.e., stochastic gradient descent.</li><li>Next, we will update model’s parameter iteratively.</li></ul><p><strong>Training loop </strong>— in each iteration we will feed a batch of data then calculate loss then back propagate the gradient and then update model’s parameters.</p><p><strong>Model evaluation</strong> — this is the process of measuring the efficiency and performance of our model. It involves measuring how well the model predicts the output variable corresponding to input variable.</p><p>The evaluation is performed on testing sets called metrices. There are four common metrices:</p><ol><li><strong>Accuracy </strong>— measure the proportion of correctly classified instances. It is generally used in balanced data sets.</li><li><strong>Recall</strong> — measure the proportion of true positive predictions out of actual positive instances. This metric is useful when the cost of false negative is high.</li><li><strong>Precision </strong>— measure the proportion of true positive predictions. It is useful when the cost of false positives is high.</li><li><strong>F1-Score </strong>— this metric is the harmonic mean of precision and recall. In other words, it overcomes the drawbacks of both metrices.</li></ol><p>After evaluation we will have to iterate and tune.</p><p><strong>Model deployment </strong>— after training and testing we will deploy it in real world where it can be used by end users.</p><p><strong>Monitoring and maintenance </strong>— once we deploy our model, we will often have to monitor and maintain it for reliability and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5179680f3bad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>