<?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 Merve Günak on Medium]]></title>
        <description><![CDATA[Stories by Merve Günak on Medium]]></description>
        <link>https://medium.com/@mervegunak?source=rss-dd943720f140------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3XNILiyOcqxi28juo68JzQ.jpeg</url>
            <title>Stories by Merve Günak on Medium</title>
            <link>https://medium.com/@mervegunak?source=rss-dd943720f140------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 07:21:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mervegunak/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[Exploring the World of Containers: Docker, Kubernetes and Beyond]]></title>
            <link>https://medium.com/datapebbles/exploring-the-world-of-containers-docker-kubernetes-and-beyond-3bf80beed5c2?source=rss-dd943720f140------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf80beed5c2</guid>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Merve Günak]]></dc:creator>
            <pubDate>Mon, 06 May 2024 09:26:23 GMT</pubDate>
            <atom:updated>2024-05-06T09:26:23.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*bcZReh-SMUCyuc-IBapxDQ.jpeg" /><figcaption>Green Pheasant on Pine Branch, by Utagawa Hiroshige, 1830–1844</figcaption></figure><h3>Introduction</h3><p>Welcome to a journey into the world of containers, where we will talk about Docker, virtual machines (VMs), Kubernetes and orchestration. If you have taken your seats, let’s get started.</p><p>At the center of everything are physical machines, i.e. tangible entities, that provide the computing resources to manifest our digital desires. Think of these as the solid ground on which our virtual efforts stand. What about virtual machines (VMs)? They are like digital twins of physical machines running on the hypervisor layer. Each VM creates its own share of CPU, memory and storage, replicating the functionality of an advanced machine.</p><p>I hope this article will be a guide to understanding its complexities and the mechanism behind it as we delve deeper into this journey.</p><p><strong>Containers: The Game Changer</strong></p><p>But here’s where things get interesting: containers. Think of them as these lightweight, portable packages that contain everything your application needs to run smoothly. Unlike VMs, which carry their own mini-operating systems, containers share the host operating system’s core, making them super-efficient.</p><p>Containers encapsulate not just your app, but also its dependencies, libraries, and settings. This means you can run your application anywhere without worrying about compatibility issues. It’s like having your lunch packed in a neat, spill-proof box that you can take with you wherever you go.</p><p>Containerization existed long before docker was invented. What Docker basically does is present this in a user-friendly API. Docker make it easy to use.</p><p>It is important to remember that containers are not physical entities, but rather virtualized environments that contain and run applications seamlessly. This virtualization offers unparalleled flexibility and efficiency, revolutionizing the software development, deployment and management landscape.</p><p>Docker is emerging as a major player taking containerization to new heights with its robust toolset. Docker streamlines the development workflow by empowering developers to effortlessly build, deploy, and manage containerized applications.</p><p>So let’s delve deeper into the world of Docker.</p><h4>Docker and its Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*trmedW_1BgTK29AfZDsIDQ.png" /></figure><p>You may have heard of the classic “it works on my machine” scenario, where deployment issues arise due to inconsistent environments.</p><p>This is where Docker comes in, providing a solution by providing consistent and portable containers that facilitate deployment processes.</p><p>Picture this: Encapsulating your applications and dependencies into portable, self-contained units that can run seamlessly in any environment. This is Docker’s trick. It allows you to run your applications consistently without compatibility issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAWPa5-itOG0cS5F7ja3JA.png" /></figure><p>At its core, Docker consists of Dockerfiles, Docker Containers, and Docker Images. These components allow developers to effortlessly build, run, and manage containerized applications.</p><p>Docker’s platform isolates applications from the underlying system, allowing multiple applications to run on the same machine without conflict. It eliminates manual dependency installations and simplifies deployment processes, making it ideal for web development.</p><h4>Virtual Machines vs. Containers</h4><p>Now, let’s take a step back and compare virtual machines (VMs) with containers. It also helps you understand the concept and logic better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*v7fOwhPY0Ig-knqnYETWTA.gif" /><figcaption>VM’s vs Containers, choose your side</figcaption></figure><p>A comparison between virtual machines (VMs) and containers reveals fundamental differences in architecture and functionality. While VMs emulate entire operating systems on a hypervisor layer, containers leverage the host operating system’s resources, resulting in lighter, more efficient deployments. Containers, with their faster startup times and lower resource consumption, offer a compelling alternative to the resource-intensive nature of VM.</p><p>This fundamental difference in architecture makes containers more lightweight and efficient compared to VMs. While VMs require significant overhead due to emulation of entire hardware environments, containers run more directly on the host system, resulting in faster startup times and lower resource consumption.</p><p>And containers are very fast, their creation are cheaper than VMs.</p><p>So, VMs and containers represent two different paradigms for deploying applications. VMs offer full isolation and compatibility but come with higher resource load. Containers, on the other hand, provide lightweight, portable environments that share resources with the host operating system, making them ideal for modern application deployment. Understanding these differences is crucial to navigating the modern software development environment.</p><p>Docker revolutionizes application deployment by providing self-sufficient containers that streamline the development, testing, and production processes. These containers, defined by configuration files, eliminate the “it works on my machine” dilemma, ensuring consistent performance from development to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*RKA7oPOCFcf4EKJIhbVaIw.png" /><figcaption>LXC, Docker Contaiers, VMs</figcaption></figure><h4>Kubernetes: The Captain of Container Orchestration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*bBH13hN1QZ9-ikwq23KJQQ.gif" /><figcaption>one captain rule them all</figcaption></figure><p>Now, where does Kubernetes come into play? Think of Kubernetes as an orchestra conductor that aligns the various elements of your cloud infrastructure to work in sync. Just as an orchestra conductor directs musicians to produce a beautiful piece of music, Kubernetes coordinates containers, storage, scaling mechanisms, and network services to bring your application to life.</p><p>Kubernetes is just an orchestrator.</p><p>From a technical perspective, Kubernetes acts as a centralized management system, enabling seamless deployment, scaling and management of containerized applications.</p><p>Kubernetes consists of several components that work together to facilitate container orchestration. For example, the kubelet agent runs on each node in the Kubernetes cluster, ensuring that pods are created, scheduled, and maintained according to the desired state. The kube-proxy component enables network communication between pods and external services, while the kube-scheduler optimally distributes workloads among available nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*mREYBdLV_W6_BkpxuUR1Ig.png" /><figcaption>A Simple Kubernetes Architecture</figcaption></figure><p>Without going too deep, let’s examine the two important components of Kubernetes and their functions.</p><p><strong>Pods: Your Basic Building Blocks</strong></p><p>Let’s talk about pods. Think of pods as your basic building blocks in the Kubernetes world. They’re like little bundles of joy that house one or more containers, kind of like roommates sharing an apartment.</p><p>Interestingly, the term “pod” is derived from the sci-fi concept of a space capsule, signifying its role in encapsulating containers.</p><p>So why are pods necessary? Well, imagine that you manage a video streaming service that requires both a media server and a caching system. Instead of running these elements separately in their own containers, Kubernetes says, “Let’s put them in the same pod!” This arrangement facilitates seamless communication between them, allowing seamless sharing of resources such as storage space.</p><p>So pods are not just random groupings; They are strategic clusters of containers that cooperate harmoniously. When you ask Kubernetes to deploy something, it’s usually about deploying pods, not individual containers. This is like saying to your friend, “Hey, let’s host a meeting at my house” instead of sending individual invitations to each guest.</p><p>Each pod in Kubernetes has a unique IP address; this allows direct communication between pods without the need to make each container available separately. This increases efficiency and security within the cluster.</p><p><strong>The Kubelet — Agent of Kubernetes</strong></p><p>You can think of Kubelet as an agent of Kubernetes. It acts as a tireless intermediary across all servers and all workers. It’s like having a multitasking assistant on each server that has the ability to adapt to different environments.</p><p>So what does the kubelet actually do? It’s like a nosy messenger constantly checking the Kubernetes API server. It’s always asking the question: “Hey, do I have a pod assigned to me? Is there something I need to take care of?”</p><p>This is where it gets interesting: Imagine the scheduler makes a decision and assigns a specific worker, let’s call it worker 1. Worker 1’s kubelet immediately jumps into action and checks the API server to see if there is a pod waiting for it. If there is, it’s like saying, “Okay, I’ll handle it. Let’s make it work here.”</p><p>So how does kubelet manage to run these containers? kubelet doesn’t actually know how to run containers. Docker, like Containerd and even Podman, is based on what we call Container Runtime. So, when it comes time to run a container, the kubelet instructs the runtime to do the job.</p><p>Kubelet is essentially the unsung hero of Kubernetes; It manages containers seamlessly and keeps your cluster running smoothly.</p><p>When we talk about Kubernetes components, there is actually a lot to tell such as Controller Manager, Schedular, etcd etc.. We can talk about the details of these in another article. For now, let’s continue our article.</p><p>Kubernetes simplifies container management by controlling the container lifecycle, scaling, and networking tasks. It automatically replaces faulty containers to maintain uninterrupted operation and allows external communication when necessary. In software deployment, Kubernetes ensures consistency and reliability across diverse environments, freeing developers from the complexity of infrastructure management so they can focus on defining the desired state of their applications.</p><p>Alternative tools for orchestration include Docker Swarm, Docker Compose, Mesos, Nomad, and OpenShift. Each has its own strengths and weaknesses that suit different use cases and needs.</p><p><strong>Conclusion</strong></p><p>In this dive into the world of containers, we took a bird’s eye journey through the fundamentals of modern software development. From the beginnings of containers as lightweight, portable packages that revolutionized application delivery, to the orchestration prowess of Kubernetes that seamlessly aligns cloud infrastructure components.</p><p>At the heart of modern computing infrastructure are physical hosts, which are tangible machines that provide computing resources. Virtual machines (VMs) abstract these physical resources, allowing multiple virtual instances to be run on a single physical host. Containers, on the other hand, encapsulate applications and their dependencies, allowing consistent deployment in different environments.</p><p>I hope your containers run smoothly, your pods thrive, and your orchestration is always solid. Until we meet again, happy containerization!🚀🐳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*CfCwKdW7dD5l4V6TX3Ys1Q.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf80beed5c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datapebbles/exploring-the-world-of-containers-docker-kubernetes-and-beyond-3bf80beed5c2">Exploring the World of Containers: Docker, Kubernetes and Beyond</a> was originally published in <a href="https://medium.com/datapebbles">DataPebbles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into AWS with a Practical Project]]></title>
            <link>https://medium.com/@mervegunak/diving-into-aws-with-a-practical-project-74c6b91e57db?source=rss-dd943720f140------2</link>
            <guid isPermaLink="false">https://medium.com/p/74c6b91e57db</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Merve Günak]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 19:40:32 GMT</pubDate>
            <atom:updated>2024-03-14T22:22:39.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*G4xXc4ggB5O9deuIWbe2FQ.jpeg" /><figcaption>Kanagawa Oki Nami Ura — Hokusai</figcaption></figure><h3>Project Overview</h3><p>I believe in learning by doing and prefer to dive into practical projects as soon as I grasp the basics. In this blog post, we’ll work on a simple project together to improve our AWS skills. Whether you’re new to AWS or aiming to enhance your data engineering expertise, this project is for you.</p><p>In a previous blog post, I shared an ETL script that extracted Spotify playlist data and stored it in SQLite. Now, we’ll modify this script to send data to an Amazon S3 bucket.</p><p>We can expand this project by using services such as AWS Lambda and RedShift later or in future sections. Let’s keep it simple for now. No need to jump into the hardest, most unresolved thing — at least not yet.</p><p>Feel free to check <a href="https://github.com/mervegunak/spotify-etl-pipeline">GitHub repository</a> and <a href="https://medium.com/@mervegunak/simple-etl-pipeline-with-python-spotify-b0bc4bbf8890">blog post</a>.</p><p>The key point here is when opening your AWS account and setting it up, go step by step, paying close attention to specific details like security and billing, which I’ll explain later.</p><h3>Step-by-Step Guide: Uploading Data to AWS S3 Bucket with Boto 3</h3><h4>What is our Goal?</h4><p>Our goal is to upload data extracted from the Spotify API into an Amazon S3 Bucket using Python and Boto3. We’ll start by setting up the AWS side and we’ll be integrating S3 functionality into our Spotify ETL Pipeline script.</p><p><strong>Prerequisites:</strong></p><p>Before diving into the project, ensure you have the following prerequisites:</p><ul><li><strong>AWS Account</strong></li><li><strong>Spotify API Credentials</strong></li><li><strong>AWS Credentials</strong></li></ul><p>Our path will be as follows, this is the scenario I designed for this project. When designing your project, you should make a plan based on the most appropriate options for the problem and data at hand. Don’t forget to design it on paper first.</p><p>And, the rest is up to your imagination…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*w8u9PotpXiayVa3fwKnusw.gif" /></figure><p>At the end of the day, if you complete everything correctly, when you execute the script, your data will be in S3 Bucket in the folder you specified.</p><h3>So, Let’s Start…</h3><p>To upload data to an Amazon S3 bucket, we’ll follow these steps:</p><h4>1) Setting Up Your AWS Account</h4><p>If you haven’t already, create an AWS account, making use of the free tier and credits. Enable billing alerts in AWS Billing and Cost Management to avoid unexpected charges.</p><p>Enable Multi-Factor Authentication (MFA) for your root account with a strong password.</p><p>For further guidance, refer to <a href="https://docs.aws.amazon.com/whitepapers/latest/aws-security-best-practices/welcome.html">AWS Security Best Practices</a> documentation. You can also explore articles and tutorials on topics like creating billing alerts and enhancing account security. Also check out : “<a href="https://docs.aws.amazon.com/accounts/latest/reference/welcome-first-time-user.html"><em>Getting started: Are you a first-time AWS user</em></a>?” guide from AWS documentation.</p><p>Once you’ve created a strong AWS account by following best practices, you’re free to play.</p><h4>2) <strong>Create an IAM User for Admin Privileges</strong></h4><p>It’s time to create an IAM User with administrative features.</p><p>To begin, log in to your AWS root account and navigate to the IAM service. From the Users page in the left control panel, create a new user. You can name this user anything you prefer, such as “admin-user.” In this example, let’s call it “Merve.” Assign the “AdministratorAccess” policy to grant comprehensive administrative permissions.</p><p>In the image below, you’ll see the IAM User named “Merve” with admin privileges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krXAbLBHSiiyT5ri7i4uyA.png" /><figcaption>AWS Console with Admin User called Merve</figcaption></figure><h4>3) Creating an S3 Bucket</h4><p>Before creating the bucket, we will create an IAM user with a policy only on a specific S3 bucket and specific actions that we specify.</p><p>I will follow these steps before creating an S3 Bucket:</p><ol><li>Creating Customer Managed User Policy</li><li>Creating an IAM User and attach IAM User Policy</li></ol><p>After, we will move on to the step of creating the S3 bucket from the S3 service.</p><p><strong># Creating Customer Managed User Policy</strong></p><p>Before we start creating the S3 bucket, we will create an IAM User Policy that defines the exact access privileges for the specified bucket. This policy ensures that the IAM user to which it is attached has permissions only for specific actions related to the S3 bucket.</p><p>Later, you will generate Access Keys for this IAM user to send data to S3 from your code.</p><blockquote><strong>“ Customer managed policies</strong> — Managed policies that you create and manage in your AWS account. Customer managed policies provide more precise control over your policies than AWS managed policies.” — <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html">Policies and permissions in IAM</a></blockquote><p>To create the User Policy:</p><p>From the AWS console, go to the IAM service. In the control panel on the left, click “Policies” and create a new policy. Although various services are accessible via search, I prefer the JSON file option to generate the policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esxg4NDQ8gnhGpk64_N2_A.png" /><figcaption>Policy Settings</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pobQu8a_tyrb4deSoedzfA.png" /><figcaption>Custom Policy — JSON</figcaption></figure><p>Here is the custom user policy JSON file in specific bucket privileges:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [  <br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:ListAllMyBuckets&quot;,<br>                &quot;s3:ListBucket&quot;,<br>                &quot;s3:GetBucketLocation&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3::: spotifydatabucket1&quot;,<br>                &quot;arn:aws:s3::: spotifydatabucket1/*&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>Simply put, this policy restricts access to only the specified Bucket and defines the allowed actions. It can list other buckets, but there is no access to see object inside them. It also does not have permissions for other services such as IAM.</p><p>We called that policy “ <strong>single-bucket-access-spotify</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfJGCMQJ_AxdVKBASoOHAg.png" /><figcaption>Custom Policy that we created in The Policies Page</figcaption></figure><p><strong># Create an IAM User and attach IAM User Policy</strong></p><p>By default IAM users have no permissions to do anything.</p><blockquote>“ Use customer managed policies instead of inline policies. It’s also best to use customer managed policies instead of AWS managed policies. AWS managed policies usually provide broad administrative or read-only permissions. For greatest security, grant least privilege, which is granting only the permissions required to perform specific job tasks.” — <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html">link</a></blockquote><p>To create an IAM User:</p><p>In the IAM service, navigate to the users page and click on the “create user” button. Choose a name for the IAM User, such as “test-user1” or whatever you want to call it, and configure additional settings as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFuAMSBddrBtw6kl4yoeIw.png" /><figcaption>Creating IAM User</figcaption></figure><p>Next, select the “Add Policies Directly” option on the page that appears, then locate and select the “single-bucket-access-spotify” policy we previously created from the policy search section. Proceed by clicking the NEXT button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkYwxOXOo-ZhvzDOwy9D7Q.png" /></figure><p>As you continue, you will reach the final step where you can view your user information and password. This is your last chance to review and download this information.</p><p>When completed, the IAM user will be created with the privileges specified in the actions in the policy attached to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*jgX_8UxeP80SEd_6FU6oVA.png" /><figcaption>IAM Service — Users</figcaption></figure><h4><strong>Finally, Creating an S3 Bucket</strong></h4><p>If you have followed the steps so far and successfully created your “test-user1” IAM user, congratulations! You can now proceed to create your S3 Bucket and populate it with the objects you want.</p><p>Begin by logging in with the IAM user “test-user1.” Navigate to the AWS console page and search for the S3 service. Click on the “create bucket” button. On the next page, provide a name for your bucket and specify your preferred region:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*Y4YP1G1nI_foOZ9eBsu5yg.png" /></figure><p>Once you’ve filled in the necessary information, proceed by confirming your settings. That’s it! Your S3 Bucket has been successfully created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGZeZNagAKUOuxRyGCzwTg.png" /></figure><h4>4) <strong>Creating Access Key for IAM User</strong></h4><p>Once you’ve successfully created your bucket “spotifydatabucket1”, it is time to create AWS credentials to upload data to our S3 Bucket from our Python script. Create an Access Key for the authorized IAM user for our S3 Bucket. Be sure to store this information securely for future use.</p><h4>5) Coding Part with Python Boto3</h4><p>I will talk about the function we added to the Spotify ETL Pipeline script to load data to S3. We interact with our S3 Bucket using the Boto3 library and I integrate the necessary operations into the <a href="https://github.com/mervegunak/spotify-etl-pipeline">code</a>.</p><blockquote><em>Boto3 acts as a powerful Python SDK for AWS, enabling seamless integration and automation of tasks such as managing resources and storing data in S3 buckets.</em></blockquote><p>Function that uploads data to S3:</p><pre>def upload_to_s3(df, key, folder_name=&#39;&#39;, aws_access_key=None, aws_secret_key=None, aws_region=None, aws_s3_bucket_name=None):<br>    try:<br>        csv_buffer = StringIO()<br>        df.to_csv(csv_buffer, index=False)<br><br>        if aws_access_key and aws_secret_key and aws_region and aws_s3_bucket_name:<br>            s3_client = boto3.client(<br>                service_name=&#39;s3&#39;,<br>                region_name=aws_region,<br>                aws_access_key_id=aws_access_key,<br>                aws_secret_access_key=aws_secret_key<br>            )<br><br><br>            full_key = f&quot;{folder_name}/{key}&quot; if folder_name else key<br>            s3_client.put_object(Body=csv_buffer.getvalue(), Bucket=aws_s3_bucket_name, Key=full_key)<br><br>            logging.info(f&quot;Data successfully uploaded to AWS S3 with key: {full_key}&quot;)<br>        else:<br>            raise ValueError(&quot;AWS credentials are missing. Data not uploaded to AWS S3.&quot;)<br>    except botocore.exceptions.NoCredentialsError:<br>        logging.error(&quot;AWS credentials are incorrect or missing. Please check your AWS access key and secret key.&quot;,<br>                      exc_info=True)<br>    except botocore.exceptions.ParamValidationError:<br>        logging.error(&quot;Invalid parameter value. Please check your AWS region or S3 bucket name.&quot;, exc_info=True)<br>    except Exception as e:<br>        logging.error(f&quot;An error occurred during data upload to AWS S3: {e}&quot;, exc_info=True)<br>    finally:<br>        csv_buffer.close()</pre><pre>def etl_pipeline():<br><br>  # ...<br>    aws_access_key = os.getenv(&#39;AWS_ACCESS_KEY&#39;)<br>    aws_secret_key = os.getenv(&#39;AWS_SECRET_KEY&#39;)<br>    aws_s3_bucket_name = os.getenv(&#39;AWS_S3_BUCKET_NAME&#39;)<br>    aws_region = os.getenv(&#39;AWS_REGION&#39;)<br><br>    if aws_access_key and aws_secret_key and aws_s3_bucket_name:<br>        # ETL Load to AWS S3<br>        upload_to_s3(user_df, &#39;user.csv&#39;, &#39;csv-files&#39;, aws_access_key, aws_secret_key, aws_region, aws_s3_bucket_name)<br>        upload_to_s3(playlist_df, &#39;playlist.csv&#39;, &#39;csv-files&#39;, aws_access_key, aws_secret_key, aws_region, aws_s3_bucket_name)<br>        upload_to_s3(track_df, &#39;track.csv&#39;, &#39;csv-files&#39;, aws_access_key, aws_secret_key, aws_region, aws_s3_bucket_name)<br>        upload_to_s3(album_df, &#39;album.csv&#39;, &#39;csv-files&#39;, aws_access_key, aws_secret_key, aws_region, aws_s3_bucket_name)<br>        upload_to_s3(artist_df, &#39;artist.csv&#39;, &#39;csv-files&#39;, aws_access_key, aws_secret_key, aws_region, aws_s3_bucket_name)<br><br>        logging.info(&quot;Data uploaded to AWS S3 successfully.&quot;)<br>  # ...      </pre><p>This code snippet shows the “upload_to_s3” function where we convert the received data into a DataFrame and upload it as a .csv file to the S3 bucket in the folder we specify.</p><p>I’ve made the loading section of my ETL Pipeline optional. Now, by providing AWS parameters, you can choose to load your data directly into your S3 Bucket rather than using SQLite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*oM1s81tkV54ncAdL2_gjRg.png" /></figure><h4>Let’s RUN the world !</h4><p>If you have followed each step carefully and provided your parameters and credentials correctly, running the script will ensure that your data is uploaded to the specified Bucket without any problems.</p><p>Once you have all the necessary scripts, all you have to do is run “main.py” to load your data into the designated folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpKw37pXXIjRkC9DZ6nr-g.png" /><figcaption>running “main.py” with successful upload outputs</figcaption></figure><p>Now let’s check our AWS S3 Bucket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xpia4Bnu3Zg2yIz93wLpLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*_t3RLUjQi3TsZm3LCyahIA.gif" /></figure><p>As you can see, the files were successfully uploaded to our S3 bucket in .csv format in the exact folder that we wanted in our S3 Bucket.</p><p>It’s important to understand that the user we’ve granted privileges within the relevant S3 Bucket can only list other buckets and cannot view their contents. You have the flexibility to customize these settings to your specific needs using the JSON format policy when creating a Customer Managed Policy. Just do not forget grant least privilege.</p><p>In this scenario, I prefered for User Policies for S3 authorization, although Bucket Policy or IAM Role are alternative methods. If you’re interested in exploring these alternatives further, we can discuss them in a separate, more detailed article.</p><h3>Summary</h3><h4>What did we do?</h4><h4><strong>AWS part:</strong></h4><ul><li>Created a strong AWS account with a strong password and Multi-Factor Authentication (MFA).</li><li>IAM user with admin privileges has been created and MFA enabled.</li><li>Another IAM user is created that has restricted access only to the specified S3 Bucket.</li><li>S3 bucket was created and attached with a user policy, allowing only the specified user to access the bucket.</li><li>Access Key is created for the IAM user to upload data to the S3 bucket.</li></ul><h4><strong>Coding part:</strong></h4><ul><li>Integrated a function into the Spotify ETL Pipeline Python script to upload data to the S3 bucket.</li><li>The data was uploaded to the S3 Bucket after running the code with the S3 IAM user’s access key.</li></ul><h4>Final Thoughts</h4><p>We covered basic topics such as AWS IAM users, policies, access key and S3 Bucket through a practice. By running a Python script, we successfully loaded the playlist data extracted from the Spotify API into AWS S3 Bucket in .csv format.</p><p>Through this practical project, I aimed to provide a basic understanding of AWS while offering a hands-on learning opportunity. I believe you gained basic experience with AWS services and perspective to improve your ETL skills.</p><p>Stay with science and art!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74c6b91e57db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple ETL Pipeline with Python: Spotify]]></title>
            <link>https://medium.com/@mervegunak/simple-etl-pipeline-with-python-spotify-b0bc4bbf8890?source=rss-dd943720f140------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0bc4bbf8890</guid>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[spotify]]></category>
            <dc:creator><![CDATA[Merve Günak]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 20:49:03 GMT</pubDate>
            <atom:updated>2023-11-15T20:49:03.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*luCfxs3o9Veyvs49lr2KLg.png" /><figcaption>Portrait of Sarah Harrop (Mrs. Bates) as a Muse (details)</figcaption></figure><p><strong><em>“Music is a moral law. It gives soul to the universe, wings to the mind, flight to the imagination, and charm and gaiety to life and to everything.” — Plato</em></strong></p><p>Have you ever been curious about Spotify data? In this practice, we start on creating a simple yet powerful ETL (Extract, Transform, Load) pipeline using Python and SQLite3. Our primary goal is to raise our data engineering skills and build an simple ETL pipeline that opens the door of data-driven insights.</p><h3><strong>What does ETL mean?</strong></h3><p>Before diving deep into our project, let’s start a clear understanding of ETL. You may have encountered the term ETL before in the realms of data engineering, data science, and business intelligence. ETL stands for Extract, Transform, Load. It’s the process of taking data from one source, transforming it, and loading it into another source.</p><p>In a way, turning chaos into clarity, making data more structured and ready for analysis.</p><p>Okay, what is ETL process?</p><h3><strong>ETL Process</strong></h3><p>We’ll follow these stages:</p><ol><li><strong>Connect with the Spotify API: </strong>Connecting with Spotify API by fetching predefined data.</li><li><strong>Creating a SQLite Database: </strong>Creating a SQLite database with a structured data schema compatible with the data we will extract.</li><li><strong>Data Extract Transform and Load: </strong>Extracting, transforming and inserting the specified data from the relevant API endpoints into the created SQLite database.</li><li><strong>Automation with Cron: </strong>Automate the entire ETL process using Cron on Linux, ensuring the pipeline runs at scheduled intervals for more efficient data processing.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*D37FZYYBGIFe9GZgfqnQeA.png" /><figcaption>Architecture Diagram</figcaption></figure><h3>The Process Behind the Project</h3><p>In the coding part, first we create the SQLite database, connect to the Spotify API, and manage the ETL process. Our Python scripts cover the required functionality, from fetching user playlists and songs to transforming and loading data.</p><blockquote>Before diving into the project, you need to have a spotify account and you should create your Spotify App.</blockquote><h4><strong>Create a Spotify Developer Account</strong></h4><p>Begin your practice by visiting the <a href="https://developer.spotify.com/dashboard/">Developer Dashboard</a> and create a web app to obtain the client id and client secret. For more details, refer to the <a href="https://developer.spotify.com/documentation/general/guides/app-settings/">documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*utgptaD73jO0qTpvJPUBKg.png" /><figcaption>My Spotify App in Dashboard</figcaption></figure><h4><strong>API Interaction</strong></h4><p>To retrieve user, playlist and track data from Spotify, I use the SpotifyAPI class I defined in spotify_api.py. This class handles communication with the Spotify API, managing authentication and making GET requests.</p><p>The get_user_data and get_playlists methods are examples of how I retrieve user information and playlists respectively :</p><pre>class SpotifyAPI:<br>    &quot;&quot;&quot;A class for interacting with the Spotify API.&quot;&quot;&quot;<br><br>    # ...<br><br>    def get_user_data(self):<br>        &quot;&quot;&quot;Get user data for the specified user ID.&quot;&quot;&quot;<br>        return self._authenticated_request(f&quot;{self.USER_ENDPOINT}/{self.user_id}&quot;)<br><br>    def get_playlists(self):<br>        &quot;&quot;&quot;Get playlists for the specified user ID.&quot;&quot;&quot;<br>        return self._authenticated_request(f&quot;{self.USER_ENDPOINT}/{self.user_id}/{self.PLAYLISTS_ENDPOINT}&quot;)[&quot;items&quot;]</pre><h4>Creating SQLite Database</h4><p>Database creation is orchestrated through the create_database function, ensuring a structured form for Spotify data.</p><p>Here, sample of create_db.py file:</p><pre><br>def create_database(db_path=&#39;spotify_data.db&#39;):<br>    try:<br>        with sqlite3.connect(db_path) as conn:<br>            cursor = conn.cursor()<br><br>            # Table Definitions (aligned for consistency)<br>            cursor.execute(&#39;&#39;&#39;<br>                CREATE TABLE IF NOT EXISTS user (<br>                    id TEXT PRIMARY KEY,<br>                    name TEXT<br>                )<br>            &#39;&#39;&#39;)<br><br>            # ... <br><br>            conn.commit()<br>            cursor.close()<br><br>    except sqlite3.Error as e:<br>        logging.error(f&quot;Error creating database: {e}&quot;, exc_info=True)</pre><h4><strong>Data Extraction</strong></h4><p>The extract_spotify_data function instantiates the Spotify API class, retrieves user, playlist and track data and processes the data.</p><pre><br>def extract_spotify_data(client_id, client_secret, user_id):<br>    spotify_api = SpotifyAPI(client_id, client_secret, user_id)<br><br>    # Tables list:<br>    track_data = []<br>    artist_data = []<br>    album_data = []<br>    playlist_data = []<br><br>    # Get user data<br>    user_item = spotify_api.get_user_data()<br><br>    # Extract user_name from user_item<br>    user_name = user_item.get(&quot;display_name&quot;, &quot;&quot;)  # Assuming display_name is available in user_data<br><br>    user_dict = {<br>        &quot;user_name&quot;: user_name,<br>        &quot;user_id&quot;: user_id<br>    }<br><br>    user_data = [user_dict]<br><br>    # Get playlists <br>    playlist_item = spotify_api.get_playlists()<br><br>    if playlist_item:<br>        for item in playlist_item:<br>            # Playlist information<br>            playlist_id = item[&#39;id&#39;]<br>            playlist_name = item[&#39;name&#39;]<br><br>            playlist_dict = {<br>                &quot;playlist_id&quot;: playlist_id,<br>                &quot;user_id&quot;: user_id,<br>                &quot;playlist_name&quot;: playlist_name<br>            }<br>            playlist_data.append(playlist_dict)<br><br>            # Get tracks for each playlist<br>            tracks_item = spotify_api.get_playlist_tracks(playlist_id)<br><br>            for i in tracks_item:<br>                track_id = i[&#39;track&#39;][&#39;id&#39;]<br>                track_name = i[&#39;track&#39;][&#39;name&#39;]<br>                artist_id = i[&quot;track&quot;][&quot;artists&quot;][0].get(&quot;id&quot;)<br>                artist_name = i[&quot;track&quot;][&quot;artists&quot;][0].get(&quot;name&quot;)<br>                album_id = i[&quot;track&quot;][&quot;album&quot;].get(&quot;id&quot;)<br>                album_name = i[&quot;track&quot;][&quot;album&quot;].get(&quot;name&quot;)<br><br>                track_dict = {<br>                    &quot;track_id&quot;: track_id,<br>                    &quot;playlist_id&quot;: playlist_id,<br>                    &quot;artist_id&quot;: artist_id,<br>                    &quot;album_id&quot;: album_id,<br>                    &quot;track_name&quot;: track_name<br>                }<br><br>                artist_dict = {<br>                    &quot;artist_id&quot;: artist_id,<br>                    &quot;artist_name&quot;: artist_name<br>                }<br><br>                album_dict = {<br>                    &quot;album_id&quot;: album_id,<br>                    &quot;album_name&quot;: album_name<br>                }<br><br>                track_data.append(track_dict)<br>                artist_data.append(artist_dict)<br>                album_data.append(album_dict)<br><br>            # Log the number of tracks found for each playlist<br>            logging.info(f&quot;Playlist {playlist_id} has {len(tracks_item)} tracks.&quot;)<br>    else:<br>        logging.info(&quot;No playlists found.&quot;)<br><br>    return user_data, playlist_data, track_data, album_data, artist_data</pre><h4><strong>Transformation</strong></h4><p>After data extraction, I transformed data into Pandas DataFrames and rename the column names to match structure in the database by the transform_data function for better manipulation.</p><pre>def transform_data(track_data, artist_data, album_data, playlist_data, user_data):<br>    track_df = pd.DataFrame(track_data).rename(<br>        columns={&quot;track_id&quot;: &quot;id&quot;, &quot;playlist_id&quot;: &quot;playlist_id&quot;, &quot;artist_id&quot;: &quot;artist_id&quot;, &quot;album_id&quot;: &quot;album_id&quot;,<br>                 &quot;track_name&quot;: &quot;name&quot;})<br>    artist_df = pd.DataFrame(artist_data).rename(columns={&quot;artist_id&quot;: &quot;id&quot;, &quot;artist_name&quot;: &quot;name&quot;})<br>    album_df = pd.DataFrame(album_data).rename(columns={&quot;album_id&quot;: &quot;id&quot;, &quot;album_name&quot;: &quot;name&quot;})<br>    playlist_df = pd.DataFrame(playlist_data).rename(<br>        columns={&quot;playlist_id&quot;: &quot;id&quot;, &quot;user_id&quot;: &quot;user_id&quot;, &quot;playlist_name&quot;: &quot;name&quot;})<br>    user_df = pd.DataFrame(user_data).rename(columns={&quot;user_id&quot;: &quot;id&quot;, &quot;user_name&quot;: &quot;name&quot;})<br>    return user_df, playlist_df, track_df, album_df, artist_df</pre><h4>Validation</h4><p>I’ve implemented a function to validate incoming data before it gets sent to the database. This function checks for duplicate entries in the DataFrames and removes them. Additionally, it issues a warning message if there are any missing data values.</p><p>You can improve this part according to the needs of your project.</p><pre>def check_duplicates_and_missing_values(track_df, artist_df, album_df, playlist_df, user_df):<br>    for df, name in [(track_df, &quot;track&quot;), (artist_df, &quot;artist&quot;), (album_df, &quot;album&quot;), (playlist_df, &quot;playlist&quot;),<br>                     (user_df, &quot;user&quot;)]:<br>        duplicate_entries = df[df.duplicated()]<br>        if not duplicate_entries.empty:<br>            logging.warning(f&quot;Duplicate {name} found. Duplicates will be removed.&quot;)<br>            df.drop_duplicates(inplace=True)<br><br>        if df.isnull().values.any():<br>            logging.warning(f&quot;Missing values found in {name} data. Please handle missing values appropriately.&quot;)</pre><h4><strong>Loading</strong></h4><p>After successfully validating and transforming the data, the final step is loading it into SQLite database. I am setting up a connection to the database using the sqlite3 module and efficiently loading Pandas DataFrames into their corresponding tables.</p><pre>def load_data_to_database(user_df, playlist_df, track_df, album_df, artist_df, db_path):<br>    try:<br>        conn = sqlite3.connect(db_path)<br>        user_df.to_sql(&#39;user&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        playlist_df.to_sql(&#39;playlist&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        track_df.to_sql(&#39;track&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        album_df.to_sql(&#39;album&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        artist_df.to_sql(&#39;artist&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>    except sqlite3.Error as e:<br>        logging.error(f&quot;An error occurred during data insertion: {e}&quot;, exc_info=True)def load_data_to_database(user_df, playlist_df, track_df, album_df, artist_df, db_path):<br><br>    try:<br>        conn = sqlite3.connect(db_path)<br>        user_df.to_sql(&#39;user&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        playlist_df.to_sql(&#39;playlist&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        track_df.to_sql(&#39;track&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        album_df.to_sql(&#39;album&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        artist_df.to_sql(&#39;artist&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>    except sqlite3.Error as e:<br>        logging.error(f&quot;An error occurred during data insertion: {e}&quot;, exc_info=True)</pre><h3>Putting It All Together: The ETL Pipeline</h3><p>Now it’s time to connect the dots and make sense of it all. Consider the etl_pipeline function as our guide on this data process. That’s what ties everything together for data process.</p><p>This function below encapsulates the entire data process — from extracting raw Spotify data, transforming it into structured DataFrames, simple data validation, and loading of data into SQLite database.</p><pre>def etl_pipeline():<br>    try:<br>        # ETL Extract<br>        client_id = os.getenv(&#39;SPOTIFY_CLIENT_ID&#39;)<br>        client_secret = os.getenv(&#39;SPOTIFY_CLIENT_SECRET&#39;)<br>        user_id = os.getenv(&#39;SPOTIFY_USER_ID&#39;)<br>        db_path = os.getenv(&#39;DB_PATH&#39;)<br><br>        user_data, playlist_data, track_data, album_data, artist_data = extract_spotify_data(client_id, client_secret,<br>                                                                                             user_id)<br><br>        # ETL Transform<br>        user_df, playlist_df, track_df, album_df, artist_df = transform_data(track_data, artist_data, album_data,<br>                                                                             playlist_data, user_data)<br><br>        # Perform data validation checks<br>        check_duplicates_and_missing_values(track_df, artist_df, album_df, playlist_df, user_df)<br><br>        # ETL Load<br>        load_data_to_database(user_df, playlist_df, track_df, album_df, artist_df, db_path)<br>        logging.info(&quot;ETL Pipeline completed successfully.&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;An error occurred during ETL Pipeline: {e}&quot;, exc_info=True)</pre><h4><strong>Automation with Cron</strong></h4><p>Now, after making sure that ETL pipeline is running smoothly and ready, I automate it by scheduling the script at the interval I specify using Cron. I chose Cron because it is fast, reliable and easy to use.</p><p>Let’s say we want it to run every Friday at midnight, just add this line to your crontab:</p><pre>0 23 * * 5  /usr/bin/python your_data_path/main.py &gt;/dev/null 2&gt;&amp;1</pre><p>This line in your crontab ensures that your script run every Friday at midnight.</p><p>There are many great and open-source tools you can use during the automation phase. You can look at these and choose the best tool for you according to your project and needs. For example, Airflow might be a good alternative for workflow scheduling in our case.</p><h3>Conclusion:</h3><p>The primary goal of this project is to provide a hands-on, practical guide on creating and automating a simple ETL pipeline, using Spotify data as an example. Thus, this project hopes to offer a practical way to improve your data engineering skills.</p><p>But the adventure doesn’t end there. Spotify data can be used for a variety of analytical purposes and provides valuable insight into user behavior, popular playlists and music tastes.</p><p>For enthusiasts looking to perform deeper analysis and develop ETL pipelines, Spotify’s Developer Web API opens the door to a variety of data. You can look <a href="https://developer.spotify.com/documentation/web-api">here</a> to discover more about the spotify data and feel free to access all the code on my <a href="https://github.com/mervegunak/spotify-etl-pipeline">GitHub</a> repository.</p><p>Who knows, maybe the next project will be an exciting one that goes into data analysis and graphics?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*b4hMulbQRAq8-JnQx4U6sA.gif" /></figure><p><em>While we almost all love creating playlists and discovering new tracks, the real magic happens when we can transform raw data into meaningful insights.</em></p><p>Stay with art and science! 🎵🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0bc4bbf8890" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overview of Red Hat OpenShift Container Platform]]></title>
            <link>https://medium.com/@mervegunak/overview-of-red-hat-openshift-container-platform-8cdd384aa90c?source=rss-dd943720f140------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cdd384aa90c</guid>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[redhat-openshift]]></category>
            <category><![CDATA[openshift-4]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Merve Günak]]></dc:creator>
            <pubDate>Sat, 27 May 2023 15:30:59 GMT</pubDate>
            <atom:updated>2023-05-27T15:38:51.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*SiaWxwYBhPxXlmJfg0Y5RQ.jpeg" /><figcaption>Girl with the Red Hat, c. 1669<br>Johannes Vermeer</figcaption></figure><p><strong>1. Introduction</strong></p><p>Containerization has transformed application development, deployment, and management, and Red Hat OpenShift Container Platform (OCP) stands as a reliable and flexible solution for these tasks. Whether you’re new to containers or looking to level up your skills, this blog post will be your beginner’s guide to OCP.</p><p><strong>What is Red Hat OpenShift Container Platform?<br></strong>Red Hat OpenShift Container Platform simplifies the building, deploying, and managing of containerized applications. It is a Kubernetes-based platform that provides a scalable and secure environment for effective collaboration between developers and operations teams.</p><p>So, What is the difference between OCP and Kubernetes or even Docker Swarm?</p><p>OpenShift Container Platform (OCP) distinguishes itself from Kubernetes and Docker Swarm with its comprehensive feature set and enterprise-grade support. While Kubernetes is an open-source platform focused on managing containerized applications, OCP builds upon Kubernetes, offering additional tools, enhanced management capabilities, and a user-friendly web console. Docker Swarm, on the other hand, is a lightweight orchestration solution provided by Docker.</p><p><strong>2. Getting Started with Red Hat OpenShift Container Platform</strong></p><p>To begin your OCP journey, it’s important to set up your development environment and grasp the core concepts. Follow this step-by-step guide:</p><p><strong>Install OpenShift Tools:</strong> Download and install the OpenShift command-line tools (oc) specific to your operating system. Follow the installation instructions provided by Red Hat to ensure a successful setup.</p><p>You can check → <a href="https://docs.okd.io/latest/cli_reference/openshift_cli/getting-started-cli.html">Getting started with the OpenShift CLI</a></p><p><strong>Access a Cluster:</strong> Determine whether you will be working with a local or remote OpenShift cluster. If setting up a local development environment, consider using tools like Minishift or CodeReady Containers. Alternatively, obtain access to a remote cluster provided by your organization or a cloud provider.</p><p><strong>Create a Project:</strong> Use the oc command-line tool to create a project that will serve as a logical container for your applications. This allows for better organization and management of your workloads within the OpenShift environment. You can also create a project directly through the web console provided by OpenShift. You can choose the method that suits your preference and workflow — whether it’s using the oc command-line tool or the web console.</p><p>While the web interface for OpenShift is user-friendly and convenient, I believe it is valuable to invest time in mastering the CLI commands.</p><p>Although the interface provides ease of use, in my opinion, learning the CLI commands enables automation, scripting, and integration with other tools, granting greater control and efficiency in managing your OpenShift environment. =)</p><p><strong>Deploy Your Application:</strong> Prepare your application artifacts, such as Docker images or source code, and use the oc command-line tool to deploy them to the project you created. Follow the appropriate deployment approach based on your application’s requirements, whether it involves source-to-image (S2I) or using pre-built container images.</p><ul><li><strong><em>S2I Approach: </em></strong><em>You provide your application’s source code along with a builder image that contains the necessary build dependencies and instructions. OpenShift will then automatically build a container image from your source code and the builder image. This process streamlines the build and deployment workflow, simplifying the application lifecycle management.</em></li><li><strong><em>Pre-Built Container Images:</em></strong><em> You can deploy your application using pre-built container images. These images are ready-to-use and typically obtained from container registries such as Red Hat Quay, Docker Hub, or private repositories. You can select the appropriate pre-built image that matches your application’s requirements, pulling it into your project and deploying it directly.</em></li></ul><p>Check documentation: <a href="https://docs.openshift.com/container-platform/4.13/openshift_images/index.html">Understanding containers, images, and image streams</a></p><p><strong>Key Concepts:</strong> Familiarize yourself with essential concepts in OpenShift Container Platform. Understand pods, learn about services, explore routes and finally, understand deployments. These resources are the Core Concepts of OCP.</p><p><strong>— Pods</strong>: Pods are the smallest units of deployment in OpenShift, representing running containers.<br> — <strong>Services</strong>: Services enable communication between pods and provide a stable network endpoint.<br> — <strong>Routes</strong>: Routes expose your application to external traffic and enable access from outside the cluster.<br> — <strong>Deployments</strong>: Deployments provide control over scaling and updating your application as needed, allowing for seamless updates without downtime.</p><p>For more on Core Concepts just <a href="https://docs.openshift.com/online/pro/architecture/core_concepts/index.html">click</a>.</p><p><strong>Explore Web Console: </strong>Access the web console, a graphical user interface provided by OpenShift, through your preferred web browser.</p><p>The OpenShift web console is a user-friendly graphical interface that allows you to visually manage and monitor applications. With features such as health monitoring, resource management, scaling options, and log access, the web console streamlines application management tasks and enhances control within the OpenShift environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yo9VlTGx-3h4S522-mknFQ.png" /><figcaption><a href="https://redhat-scholars.github.io/openshift-starter-guides/rhs-openshift-starter-guides/4.7/common-explore.html">OpenShift Web Console</a> in the Administrator Perspective</figcaption></figure><p>For more detailed information on documentation OpenShift Container Platform 4.13, I highly recommend visiting the official documentation <a href="https://docs.openshift.com/container-platform/4.13/getting_started/openshift-overview.html">here</a>.</p><p>— I will plan to share a detailed and hands-on blog post for this section in the future.</p><p><strong>3. Building and Deploying Applications in OpenShift Container Platform</strong></p><p>Once you have established a foundation, it’s time to dive deeper into application development and deployment in OCP.</p><p>Building and deploying applications in Red Hat OpenShift Container Platform involves several key steps that enable efficient development and seamless deployment.</p><p>One crucial aspect is creating container images for your applications. This can be achieved by utilizing existing images from container registries or building custom images using Dockerfiles. For instance, suppose you have a web application written in Node.js. In that case, you can create a container image that incorporates the necessary dependencies, configurations, and your application code.</p><p>Once you have your container image, you can leverage OpenShift’s build configurations to automate the build process. This includes defining triggers, specifying build strategies, and connecting to source code repositories. For instance, you can set up a build configuration that triggers a new build whenever changes are pushed to your Git repository.</p><p>Deployment configurations in OpenShift allow you to define the desired state of your application. You can specify the number of replicas and configure deployment strategies like rolling updates, ensuring smooth application updates without downtime. In our example, you can define a deployment configuration that ensures three replicas of your Node.js web application are always running.</p><p>To handle varying traffic and demand, OpenShift provides scaling and resource management capabilities. You can configure auto-scaling based on metrics like CPU or memory usage. As your web application gains popularity and draws in more visitors, OpenShift springs into action with seamless efficiency, effortlessly spawning additional replicas to gracefully handle the increased load. So, whether it’s a sudden surge or a gradual climb, OpenShift ensures your application stays responsive and performs at its best, without breaking a sweat.</p><p>OpenShift’s monitoring and logging features are vital for effective application management. By tracking resource utilization, performance metrics, and log data, you can swiftly identify and resolve any issues. For instance, if your application experiences increased resource consumption, OpenShift’s monitoring and logging capabilities help you pinpoint the root cause and take necessary measures to ensure smooth operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trjV2JqnGUdA0iApN6NuAg.png" /><figcaption><a href="https://jbcodeforce.github.io/openshift-studies/ocp/">Default Grafana Dashboards</a></figcaption></figure><p>Lastly, integrating OpenShift with CI/CD tools like Jenkins or GitLab enables continuous integration and delivery. You can automate the entire software delivery pipeline, including building, testing, and deploying applications. For example, you can configure OpenShift to automatically trigger a build and deployment whenever changes are pushed to your Git repository.</p><p>By following these steps, you can efficiently build and deploy applications in Red Hat OpenShift, enabling seamless development and ensuring scalability and reliability for your applications.</p><p>Useful Article: <a href="https://www.redhat.com/sysadmin/deploy-web-service-openshift">How to deploy a web service on OpenShift</a></p><p><strong>4. Key Features of OpenShift Container Platform</strong></p><p><strong>Kubernetes Superpowers:</strong> OCP harnesses the immense power of Kubernetes, relieving you of scaling and load balancing headaches. You can trust OCP to handle it all with ease.</p><p><strong>Developer Delight:</strong> OCP understands developers’ needs and speaks their language. Its user-friendly interface and command-line tools make you feel like a coding wizard. Plus, it’s got tricks like source-to-image (S2I) up its sleeve, turning your source code into container magic.</p><p><strong>CI/CD Integration:</strong> OpenShift’s CI/CD integration streamlines the software delivery process by seamlessly integrating with popular CI/CD tools. With automated workflows and optimized pipelines, you can accelerate your software releases and achieve greater efficiency in your development lifecycle. Say goodbye to manual tasks and hello to automated superhero speed.</p><p><strong>Scalability: </strong>When your application experiences a sudden surge in traffic, OCP steps up its game. Through automatic scaling and load balancing, OCP ensures that your apps can handle the increased load without breaking a sweat. Your users will be delighted as your applications continue to perform flawlessly, effortlessly adapting to the growing demand.</p><p><strong>Security Shield:</strong> Protecting your applications is OCP’s top priority. With built-in security features like role-based access control (RBAC) and secure container registries, it’s like having a bulletproof shield for your code.</p><p><strong>Insights in a Flash:</strong> OCP grants you superhero vision into your app’s performance. Monitor and analyze metrics like a pro, effortlessly troubleshoot issues, and save the day when things go awry. It’s like having a built-in crystal ball!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*xUec78_6fi849ty6sN9KOA.png" /></figure><p>So far, I’ve discussed the positive aspects of Red Hat OpenShift Container Platform. Now, let’s consider some of the potential drawbacks or considerations to provide a more balanced perspective. Here are a few points to keep in mind:</p><p><strong>5. Considerations and Potential Drawbacks of OCP</strong></p><p><strong>Learning Curve: </strong>OpenShift can be complex, especially for beginners, requiring time and effort to understand its advanced features.</p><p><strong>Resource Requirements:</strong> Running OpenShift requires substantial hardware and operational resources, adding complexity and costs.</p><p><strong>License Costs: </strong>OCP is <strong>not free </strong>and requires a subscription, which may be a consideration for organizations on a tight budget.</p><p><strong>Upgrades and Compatibility:</strong> Upgrading to newer versions can be challenging and may have compatibility issues with existing applications.</p><p><strong>Vendor Lock-In:</strong> Choosing OCP ties you to the Red Hat ecosystem, limiting long-term flexibility.</p><p>C<strong>ustomization and Flexibility:</strong> OpenShift may have limitations when it comes to specific customizations or unique requirements.</p><p><strong>Community and Third-Party Ecosystem:</strong> The third-party ecosystem for OpenShift may be less extensive compared to other platforms, affecting the availability of specific integrations or tools.</p><p><strong><em>6. Conclusion</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*L6RLG2-jwIY56LfgzBo57w.png" /></figure><p>Red Hat OpenShift Container Platform offers a comprehensive solution for containerized application development and management. It provides a user-friendly interface, robust features, and a supportive community. However, it’s important to carefully consider the potential challenges discussed earlier before making a decision. By evaluating the pros and cons, individuals and organizations can determine if OpenShift is the right fit for their needs.</p><p>Whether you’re a beginner or an experienced professional, exploring OpenShift can open up exciting possibilities in the world of containerization. Feel free to visit the <a href="https://developers.redhat.com/">Red Hat Developer website</a> to learn more and dive deeper into the possibilities of OpenShift.</p><p>Thank you for taking the time to read this article! I hope you found it helpful and gained valuable insights from it.</p><p>You can always reach me on <a href="https://www.linkedin.com/in/merve-gunak/">linkedln</a> and <a href="https://twitter.com/mervgunak">twitter</a>.</p><p>Stay with science and art!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cdd384aa90c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python ile Zaman Serileri Tahmin Yöntemleri]]></title>
            <link>https://medium.com/@mervegunak/python-ile-zaman-serileri-tahmin-y%C3%B6ntemleri-4eeb784d4562?source=rss-dd943720f140------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eeb784d4562</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[timeseries-forecasting]]></category>
            <dc:creator><![CDATA[Merve Günak]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 10:57:16 GMT</pubDate>
            <atom:updated>2022-11-27T12:01:28.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*_oa6LcFwsGDTzdBYEHaT2A.jpeg" /><figcaption>Gaetano Previati, L’Assunzione, Museo dell’Ottocento</figcaption></figure><p>Merhabalar,</p><p>Daha önce konuyu teorik olarak ele almıştık. Bu bölümde Zaman Serileri Tahmin Yöntemlerini Python üzerinden uygulamalı olarak aktarmaya çalışacağım.</p><p>Serinin birinci ve ikinci bölümlerini okumak isterseniz;</p><blockquote><a href="https://medium.com/@mervegunak/zaman-serileri-analizi-1-181422b3c4b4">Zaman Serileri Analizi — 1</a> ve <a href="https://medium.com/machine-learning-t%C3%BCrkiye/zaman-serileri-analizi-2-e4f6a750cd5d">Zaman Serileri Analizi — 2</a></blockquote><p>Çalışma için kullanacağımız veriler Türkiye’nin 2017–2022 yılları arasındaki elektrik tüketim verileridir ve <a href="https://seffaflik.epias.com.tr/transparency/">EPİAŞ ŞEFFAFLIK PLATFORMU</a> sitesinden çekilmiştir.</p><p>Öncelikle, gerekli kütüphanelerin ve veri setinin içeri aktarılması ile başlıyoruz. Veri setine genel bir bakış, kolon isimlerinin düzenlenmesi ve tip dönüşümlerini yapıyoruz. Bu düzenlemeleri yaptıktan sonra saatlik frekanstaki veriyi günlük frekansa çektim.</p><p>Bu aşamaları bu yazıya dahil etmiyorum, eğer detayları görmek isterseniz kodun tamamına <a href="https://github.com/mervegunak/time-series-forecasting">buradan</a> erişebilirsiniz.</p><p>Veri setimizi düzenledik ve saatlik verileri günlük frekansa getirdik. Şimdi veri setimizin ilk beş elemanına bir göz atalım:</p><pre>data_daily = df.set_index(&quot;Tarih&quot;).asfreq(&#39;D&#39;)<br>data_daily.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*u0IYY641Z8omYj7-I-3pRg.png" /></figure><p>Zaman Serisi verileriyle çalışacağımız için “Tarih” kolonunu da indeks olarak veriyoruz.</p><p>Daha sonra veri setinde eksik ve yinelenen (duplike) değer var mı diye kontrol edeceğiz. Bu aşamada veri setinde eksik değer bulunmamıştır fakat 3 adet duplike kayıt tespit edilmiş ve veri setinden çıkarılmıştır.</p><p><strong>Verileri Çizgi Grafiği Üzerinde Görelim:</strong></p><pre>plt.figure(figsize=(22,4))<br>sns.lineplot(data = data_daily.reset_index(), x=&quot;Tarih&quot;, y=&quot;Tuketim&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysgIXhHS7JyKtklh_idieQ.png" /><figcaption><em>2017–2022 Türkiye Elektrik Tüketim</em></figcaption></figure><p><strong>Zaman Serisi Bileşenleri :</strong></p><pre>data_monthly = df.set_index(&quot;Tarih&quot;).asfreq(&#39;M&#39;)<br><br>plt.rcParams[&#39;figure.figsize&#39;] = [20,7]<br>decomposition = sm.tsa.seasonal_decompose(data_monthly)<br>fig = decomposition.plot()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*td6Y4ScutLjlNvcizgtmJw.png" /><figcaption>Zaman Serisi Bileşenleri</figcaption></figure><p>Görsellerden anlayabileceğimiz üzere, elektrik tüketim verilerinin özellikle 2020 yılından sonra genel bir pozitif eğilime ve mevsimselliğe sahip olduğunu söyleyebiliriz.</p><p>Elektrik tüketim değerleri yaz aylarında zirve ve sonbaharda keskin bir düşüş yapar, ardından kış mevsimine kadar hafif bir artış olur ve bahar mevsimi boyunca yavaş yavaş azalır.</p><p>Verilerin hem trend hem de mevsimselliğe sahip olması verilerin durağan olmadığı anlamına gelir.</p><p><strong>ACF ve PACF Grafikleri:</strong></p><p>Zaman serileri analizinde verilerin otokorelasyon ve kısmı otokorelasyon grafiğinin incelenmesi önemli bir adımdır. Model terimlerinin sayısını belirlemek için Otokorelasyon fonksiyonu (ACF) ve kısmi otokorelasyon fonksiyonu (PACF) grafiklerinden yararlanacağız. Aynı zamanda bu grafiklere bakarak serinin durağanlığı hakkında çıkarımlar yapabildiğimizi öğrenmiştik. Serinin diğer yazılarında bu konulardan detaylıca bahsediyorum.</p><pre>fig, (ax1, ax2) = plt.subplots(1, 2,figsize=(20,5), dpi= 70)<br><br>plot_acf(data_daily.Tuketim.tolist(), ax=ax1, lags=48)<br>plot_pacf(data_daily.Tuketim.tolist(), ax=ax2, lags=48, method=&quot;ywm&quot;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAn7o3a77aKElPTohuS3PQ.png" /></figure><p>Verilerin çizgi grafiği, zaman serileri bileşenleri ve ACF-PACF grafiğinden yola çıkarak serinin durağan olmadığını söyleyebiliriz.</p><p>Yaptığımız gözlemleri doğrulamak için Dickey-Fuller ve KPSS hipotez testlerini kullanacağız:</p><p><strong>Durağanlık Analizi</strong></p><p><strong>1- Augmented Dickey-Fuller Testi</strong></p><ul><li>Sıfır Hipotez H0 : Seri Durağan Değildir</li><li>Alternati Hipotez H1 : Seri Durağandır (Birim Kök Yoktur)</li></ul><p><strong>2- Kwiatkowski-Phillips-Schmidt-Shin Testi</strong></p><ul><li>Sıfır Hipotez H0 : Seri Durağandır (Birim Kök Yoktur)</li><li>Alternati Hipotez H1: Seri durağan değildir</li></ul><pre># ADF Testi:<br><br>def adf(data):<br>    adf_test = sm.tsa.adfuller(data, autolag=&#39;AIC&#39;)<br>    print(f&#39;ADF Statistic: {adf_test[0]}&#39;)<br>    print(f&#39;p-value: {adf_test[1]}&#39;)<br>    print(&quot;Seri Durağan Değildir&quot;) if adf_test[1] &gt; 0.05 else print(&quot;Seri Durağandır(Birim Kök Yoktur)&quot;)<br><br># KPSS Testi:<br><br>def kpss(data):<br>    kpss_test = sm.tsa.kpss(data)<br>    print(&#39;KPSS Statistic: %f&#39; % kpss_test[0])<br>    print(&#39;p-value: %f&#39; % kpss_test[1])<br>    print(&quot;Seri Durağandır&quot;) if kpss_test[1] &gt; 0.05 else print(&quot;Seri durağan değildir(Seri Birim Kök İçerir)&quot;)<br><br>adf(data_daily)<br>kpss(data_daily)</pre><pre>ADF Statistic: -3.721<br>p-value: 0.003<br>Seri Durağandır(Birim Kök Yoktur)<br><br>KPSS Statistic: 2.007<br>p-value: 0.010<br>Seri durağan değildir(Seri Birim Kök İçerir)</pre><p>Sonuçların farklı gelmesi güzel oldu çünkü önemli bir noktaya değineceğiz. Eğer ADF testi bir birim kök bulamazsa, ancak KPSS testi bulursa, seri fark-durağandır. Yine de fark almanız gerekir. Testlerden biri bile birim kökün varlığına işaret ediyorsa, seri durağandır diyemeyiz.</p><p>Serinin durağan olmadığına emin olduktan sonra fark yöntemi ile serinin birinci dereceden farkını alarak serinin durağan hale gelip gelmediğini test edelim:</p><pre>data_daily_diff = data_daily.copy()<br>data_daily_diff[&#39;Tuketim&#39;] = data_daily[&#39;Tuketim&#39;] - data_daily[&#39;Tuketim&#39;].shift(1)<br>data_daily_diff = data_daily_diff.dropna()</pre><pre>fig, (ax1, ax2) = plt.subplots(1, 2,figsize=(20,5), dpi= 70)<br><br>plot_acf(data_daily_diff.Tuketim.tolist(), ax=ax1, lags=48)<br>plot_pacf(data_daily_diff.Tuketim.tolist(), ax=ax2, lags=48, method=&quot;ywm&quot;)<br>plt.show()<br><br>adf(data_daily_diff)<br>kpss(data_daily_diff)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7pOVkkJV1Utyvgz_pjxVg.png" /><figcaption>Birinci Dereceden Farkı Alınan Serinin ACF-PACF grafiği</figcaption></figure><pre>ADF Statistic: -11.067<br>p-value: 4.649e-20<br>Seri Durağandır(Birim Kök Yoktur)<br><br>KPSS Statistic: 0.049<br>p-value: 0.100<br>Seri Durağandır</pre><p>Serimiz artık durağan hale gelmiş olsa bile hala ACF grafiğinde dalgalanmalar yani mevsimselliğin olduğunu ve gecikme sayılarının tekrarlarını incelediğimiz zaman periyodun 7 olduğunu tespit edebiliyoruz. Ayrıca PACF’deki 7. gecikmenin de sınırlar dışında kaldığını görüyoruz.</p><p>Periyot 7 olarak belirledikten sonra birinci dereceden mevsimsel fark alıyoruz:</p><pre>data_daily_diff2 = data_daily_diff.diff(7).dropna()</pre><pre>fig, (ax1, ax2) = plt.subplots(1, 2,figsize=(20,5), dpi= 70)<br><br>plot_acf(data_daily_diff2.Tuketim.tolist(), ax=ax1, lags=48)<br>plot_pacf(data_daily_diff2.Tuketim.tolist(), ax=ax2, lags=48)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9h9oHyJyaIa99KXcPPsgA.png" /></figure><p>Böylece serimizi trend ve mevsimsel etkiden arındırmayı başardık.</p><p>Modelleme aşamasına geçmeden önce, yaptığımız analizler doğrultusunda model parametrelerini manuel olarak belirleyemeye çalışalım.</p><p>Hem trend hem mevsimsel fark alınarak durağan hale geldiği için d = 1 ve D = 1 şeklinde tanımlayacağız.</p><p>ACF grafiğinde 1,2 ve 7&#39;de önemli bir gecikme vardır. Bu nedenle MA(q) parametresi 2 ve mevsimsel MA(Q) parametresi 1 olabilir.</p><p>PACF grafiğinde ise 1,2 ve 7,14,21’de önemli bir gecikme vardır. AR(p) parametresi 2 olabilir. Mevsimsel AR(P) parametresinin ise aslında bu durumda 0 alınması tavsiye ediliyor.</p><p>Bazı kaynaklarda, mevsimsel gecikmedeki otokorelasyon negatifse, modele mevsimsel MA(Q) terimi eklenip mevsimsel AR(P) teriminin atlanması yani 0 alınması öneriliyor. Fakat yapmış olduğum denemelerde AR(P)=1 almak daha düşük hata oranı ve yüksek R Kare değeri verdiği için biz burada AR(P) terimini 1 olarak alacağız.</p><p>Buradan yola çıkarak;</p><p><strong>ARIMA(2,1,2)</strong> ve <strong>SARIMA(2,1,2)x(1,1,1,7)</strong> olacak şekilde notasyonumuzu oluşturuyoruz.</p><p>Model parametrelerini belirlemenin (<a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.arima.AutoARIMA.html">autoarima</a>, gridsearch gibi) ve test etmenin başka yolları vardır. Biz bu çalışmada manuel olarak belirlediğimiz parametreleri kullanacağız ve herhangi bir model iyileştirmesi yapmayacağız.</p><p>Şimdilik amacım, ileri düzey bir elektrik tüketim tahmini yapmaktan ziyade zaman serileri tahmin yöntemlerini basit şekilde Python ile nasıl uygulamaya dökeriz göstermeye çalışmak.</p><p><strong>Modelleme ve Tahmin</strong></p><p>1 Ocak 2017 - 31 Temmuz 2022 eğitim seti, 1 Ağustos 2022 - 31 Ağustos 2022 ise test seti olacak şekilde ayırıyoruz. Her model için aynı aralıkta bir tahminleme işlemi yapacağız sonrasında sonuçları test setindeki gerçek değerler ile karşılaştıracağız.</p><p><strong>ARIMA</strong></p><p>ARIMA(2,1,2) modelini statsmodels paketini kullanarak oluşturalım ve belirlediğimiz aralık için bir tahminleme gerçekleştirelim. Ardından gerçek değerler ile tahmin edilen değerleri bir görsel üzerinde gösterelim.</p><p>Verileri eğitim ve test seti olarak ikiye ayırıyoruz:</p><pre>train_data = data_daily[:&#39;2022-07-31&#39;]<br>test_data = data_daily[&#39;2022-08-01&#39;:&#39;2022-08-31&#39;]<br>pred_df = test_data.copy()</pre><pre># ARIMA (2,1,2)<br><br>arima_model = sm.tsa.arima.ARIMA(np.asarray(train_data),order=(2,1,2))<br>arima_model_fit = arima_model.fit()<br>arima_pred = arima_model_fit.forecast(len(test_data),disp=False)<br><br>pred_df[&quot;arima_pred&quot;] = arima_pred.round(2)<br>plt.figure(figsize=(22,4))<br>sns.lineplot(data = pred_df[[&#39;Tuketim&#39;, &#39;arima_pred&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNYeAXMHAbvBmOVr30wPYQ.png" /></figure><p>ARIMA modeli grafikten anlayacağımız üzere pek iyi çalışmadı çünkü verilerimiz mevsimsellik içeriyor ve ARIMA tarafından iyi tahmin edilemiyor. Bu tür durumlarda daha önceki yazımda bahsettiğim gibi SARIMA modeli daha iyi çalışacaktır.</p><p>Şimdi aynı tahmin işlemini SARIMA üzerinde gerçekleştirelim.</p><p><strong>SARIMA</strong></p><p>SARIMA (2,1,2) (1,1,1,7)</p><pre># SARIMA (2,1,2) (1,1,1,7)<br><br>sarima_model = SARIMAX(np.asarray(train_data), order=(2, 1, 2), seasonal_order=(1,1,1,7))<br>sarima_model_fit = sarima_model.fit()<br>sarima_pred = sarima_model_fit.forecast(len(test_data))<br><br>pred_df[&quot;sarima_pred&quot;] = sarima_pred.round(2)<br>plt.figure(figsize=(22,4))<br>sns.lineplot(data = pred_df[[&#39;Tuketim&#39;, &#39;sarima_pred&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvfWKuxeLxaGMaY14dYdDQ.png" /></figure><p>SARIMA modelinin ARIMA modelinden daha iyi sonuç verdiğini grafikten gözlemleyebiliyoruz.</p><p>Son olarak Prophet ile bir tahminleme yapalım ve sonuçları değerlendirelim:</p><p>PROPHET</p><p>Burada Prophet algoritması girdi olarak “ds” ve “y” değişkenleriyle çalıştığı için eğitim ve test setimizi buna göre ayarlıyoruz:</p><pre># PROPHET<br><br>prophet_df = data_daily.reset_index()<br>prophet_df.columns = [&quot;ds&quot;,&quot;y&quot;]<br><br>train_data_prophet = prophet_df[prophet_df[&#39;ds&#39;] &lt; &#39;2022-08-01&#39;]<br>test_data_prophet = prophet_df[(prophet_df[&#39;ds&#39;] &gt;= &#39;2022-08-01&#39;) &amp; (prophet_df[&#39;ds&#39;] &lt;= &#39;2022-08-31&#39;)]<br><br>prophet_model = Prophet()<br>prophet_model.fit(train_data_prophet)<br>model_predict = prophet_model.predict(test_data_prophet)<br><br>pred_df[&quot;prophet_yhat&quot;] = model_predict[&quot;yhat&quot;].values.round(2)<br>pred_df[&quot;prophet_yhat_lower&quot;] = model_predict[&quot;yhat_lower&quot;].values.round(2)<br>pred_df[&quot;prophet_yhat_upper&quot;] = model_predict[&quot;yhat_upper&quot;].values.round(2)<br><br>plt.figure(figsize=(22,4))<br>sns.lineplot(data = pred_df[[&#39;Tuketim&#39;, &#39;prophet_yhat&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mt-SKhXDdHDZ8BYmoLJmGA.png" /></figure><p>yhat, yhat_lower ve yhat_upper değerlerini içeren grafik :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUIxfkYFzW6bNa4gKXdIog.png" /></figure><p>Modeli değerlendirmek için MAPE, RMSE ve R2 metriklerini kullanacağız:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*dR1N6p6T9Sxqvx7jjgk09Q.png" /></figure><p><strong>R2 (Coefficient of Determination) :</strong> R Kare, belirleme katsayısıdır. Verilerin fit edilen model tarafından ne kadar iyi açıklandığının bir ölçüsüdür yani bağımlı değişkendeki değişkenliğin ne kadarının model tarafından açıklanabileceğini ölçer ve 0 ile 1 arasında bir değer aldığı varsayılır fakat R Kare negatif değerler de alabilir. R Kare değeri 1&#39;e yaklaştıkça güçlü bir korelasyon var ve algoritmamız iyi, 0&#39;a yaklaştıkça modelimiz ortalamaya yaklaşır ve ilişki azalır.</p><p><strong>RMSE (Root Mean Squared Error): </strong>Kök Ortalama Kare Hata, MSE yani Hata Kareler Ortalamasının kareköküdür. Hata Kareler Ortalaması, tahmin edilen değer ile gerçek değer arasındaki farkların karelerinin ortalamasını temsil eder.</p><p><strong>MAPE (Mean Absolute Percentage Error) :</strong> Ortalama Mutlak Yüzde Hata, tahminlerin mutlak yüzde hatalarının ortalamasıdır.</p><p>Bizim örneğimizde ARIMA modelinin R Kare değeri -0.042 gibi negatif bir değer çıkmıştır. Bu da demek oluyor ki model gerçekten de verilerimiz için uygun değil.</p><p>İlgili dönem aralığındaki model performans sonuçlarında SARIMA modeli en düşük RMSE ve MAPE değerine sahip olmakla birlikte R Kare skoru 0,66&#39;dır ve bu, modellerimiz arasında en yüksek puandır.</p><p>Sonuçlar aslında şaşırılacak şekilde iyi görünüyor? Rastgele bir doğrulama dönemi seçerek bir dizi tek adımlı tahmin yaptık. Bu oluşturulan modellerin, geleceğe yönelik birçok dönemi doğru bir şekilde tahminleyeceği anlamına gelmez. Yani etkili bir zaman serisi modelini bulmak ve doğrulamak aslında bu kadar basit değil.</p><p>Burada çok temel şekilde modellerimizi oluşturduk ve hiperparametre ayarlamalarını yapmadık. Ayrıca daha gerçekçi bir senaryoda aslında verilerinizi üç farklı veri kümesi şeklinde ayırmanız iyi bir pratiktir. Güvenilir bir model oluşturmak istiyorsanız veri kümenizi eğitim, validasyon ve test şeklinde ayırmanız gerekir.</p><p>SARIMA ve Prophet modellerinin geliştirilmesi ve hata oranlarının düşürülmesi için doğru şekilde veri setinin ayrıştırılması, parametre optimizasyonu, anlamlı bağımsız değişkenlerin modele eklenmesi, tatil günlerinin ayrıştırılması gibi yapabileceğiniz birçok şey vardır.</p><p>Çalışma üzerinde kendiniz birtakım denemeler yaparsanız, mesela eğitim ve test seti dönemlerini değiştirmek gibi, o zaman sonuçların aslında ne kadar yanıltıcı olabileceğini görebilirsiniz. Bu çalışmanın, kendinizin bazı içgörüleri oluşturabilmesi adına size bir başlangıç noktası verebileceğini düşünüyorum.</p><p>Gelecek zamanlarda bu temel modellerin ötesine giderek elektrik tüketim tahminlemesi çalışmamızı derinleştireceğiz.</p><p>Bana her zaman <a href="https://www.linkedin.com/in/merve-gunak/">linkedln</a> ve<a href="https://twitter.com/mervgunak"> twitter</a> üzerinden ulaşabilirsiniz.</p><p>Bilim ve Sanatla Kalın !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eeb784d4562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zaman Serileri Analizi — 2]]></title>
            <link>https://medium.com/machine-learning-t%C3%BCrkiye/zaman-serileri-analizi-2-e4f6a750cd5d?source=rss-dd943720f140------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4f6a750cd5d</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[time-series-modeling]]></category>
            <category><![CDATA[facebook-prophet]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Merve Günak]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 14:21:49 GMT</pubDate>
            <atom:updated>2021-12-23T13:44:47.256Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Zaman Serileri Analizi — 2</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*N-EDZeiEBcMJLYu6FSnhew.jpeg" /><figcaption>The Time Machine</figcaption></figure><h3>Zaman Serileri Tahmin Yöntemleri— ARIMA, SARIMA &amp; Facebook Prophet</h3><p>Bir önceki bölümde zaman serilerine genel bir giriş yaparak önemli temel kavramlardan bahsettim. Bu bölümde ARIMA ve SARIMA modellerini anlatmaya çalışacağım. Daha sonra Facebook Prophet’e kısa bir giriş yaparak yazıyı sonlandıracağım.</p><p>Serinin ilk bölümünü merak edenler için : <a href="https://medium.com/@mervegunak/zaman-serileri-analizi-1-181422b3c4b4"><strong>Zaman Serileri Analizi — 1</strong></a></p><p>Box-Jenkins yöntemine geçmeden önce AR, MA ve ARMA modelleriyle alakalı kısa bir bilgi vermek gerekirse, temelde AR ve MA, doğrusal durağan stokastik ARMA modelinin özel bir halidir ve bu modeller durağan olan zaman serilerinin analizinde kullanılır. Gerçek dünya verileri çoğunlukla durağan değildir. Bu durumda eğer seri (mesela farkı alınarak) durağan hale getirilebiliyorsa, ARIMA gibi yöntemler uygulanabilir.</p><p>NOT: Eğer ACF ve PACF’deki anlamlı korelasyonlar birden fazla ise duruma göre ARMA ya da ARIMA modelinin kullanılması daha doğru olacaktır.</p><p><strong>ARIMA (A</strong>uto<strong>R</strong>egressive <strong>I</strong>ntegrated <strong>M</strong>oving <strong>A</strong>verage<strong>)</strong></p><p>Box-Jenkins yöntemlerinden biri olan ARIMA(Otoregresif Entegre Hareketli Ortalama) modeli, zaman serileri analizinde kullanılan istatistiksel analiz yöntemlerinden biridir. Yeteri kadar örneklem varsa kısa dönem tahminlerde başarılı olabilir.</p><p>ARIMA terimini üçe ayırabiliriz:</p><p><strong><em>AR(p)</em></strong> :<em> Autoregression</em><strong><em>/</em></strong><em>Otoregresif — tahmin denklemindeki değişkenlerin gecikmeleri göstermektedir</em></p><p><strong><em>I(d)</em></strong><em>:</em> <em>Integrated</em><strong><em>/</em></strong><em>Entegre — durağanlığa ulaşmak için fark alma işlemini gerçekleştirdiğimiz sırayı veren fark derecesini göstermektedir</em></p><p><strong><em>MA(q)</em></strong><em> : Moving</em><strong><em> </em></strong><em>Average</em><strong><em>/</em></strong><em>Hareketli Ortalama — tahmin hatalarının gecikmeleri göstermektedir</em></p><p><strong><em>p</em></strong><em> : modele dahil edilen gecikmelerin sayısı</em></p><p><strong><em>d </em></strong><em>: farklılaşma derecesi</em></p><p><strong><em>q</em></strong><em> : hareketli ortalama penceresinin sayısı</em></p><p>Notasyonu şu şekildedir : <strong><em>ARIMA (p,d,q)</em></strong></p><p>Bir ARIMA modeli oluştururken p,q ve d parametrelerini belirlememiz gerekiyor. Peki bu parametreleri neye göre seçeceğiz?</p><p>Zaman serisini, farkını alarak durağan hale getirdikten sonra (d=1), p ve q parametrelerini belirlemek için genel kabul görmüş tek bir yöntem olmamakla birlikte otokorelasyon fonksiyonu (ACF) ve kısmi otokorelasyon fonksiyonu (PACF) grafiklerine bakarak, AR ve MA terimlerinin sayısını belirleyebiliriz. Aynı zamanda bu grafiklere bakarak serinin trend ve mevsimsellik içerip içermediği hakkında da yorumlar yapabiliriz.</p><p><em>ACF </em>grafiği, serinin kendisi ile gecikmeleri arasındaki korelasyon katsayılarının bir çubuk grafiğidir. <em>PACF</em> grafiği ise, 2 gecikmeli değer arasındaki gecikmeleri veren ve diğer gecikmelerin önemli olmadığı bir çubuk grafiktir. Genellikle AR terimi için PACF, MA terimi için ACF grafiğine bakılmaktadır. AR ve MA düzeyini belirlerken, güven sınırının dışında kalan otokorelasyon sayısına bakılmaktadır.</p><p>Ne demek istediğimi bir örnek üzerinden giderek anlamaya çalışalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*Xvo5o3Z3r0XZvxsVdCRrIw.png" /><figcaption>ACF Grafiği</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*cqhHdTUOJZJiHG7c7OT4sg.png" /><figcaption>PACF Grafiği</figcaption></figure><p>Yukarıdaki grafikler, günlük frekansta oluşturulan bir zaman serisi verilerinin ACF ve PACF grafiklerini göstermektedir. Serinin durağan olmadığı ilk bakışta gözümüze çarpıyor. İlk dört gecikme güven sınırları dışında olduğu için trend içerdiğini söyleyebiliriz. Ayrıca 7 günde bir gecikmeler zirve yapmış görünüyor.</p><p>Bu bilgiler ışığında veri setinin hem trend hem mevsimsellik etkisinde olduğunu söyleyebiliriz.</p><p>Serinin durağan olmadığına emin olmak için bir de ADF ve KPSS testleri yapıldığında gelen sonuçlar şu şekildedir :</p><pre>ADF Statistic: -2.8507122243484138<br>p-value: 0.051387040622567326<br>Seri Durağan değil<br><br>KPSS Test Statistics: 0.22902758041889848<br>p-value: 0.01<br>Seri Durağan değil</pre><p>Serinin durağan olmadığına ikna olduğumuza göre yolumuza seriyi durağan hale getirerek devam ediyoruz.</p><p>Logaritmik dönüşüm, trend ekleme, box-cox dönüşümü gibi farklı durağanlaştırma teknikleri olmakla birlikte biz burada fark alarak durağanlaştırma yöntemini kullanacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*wUB8kOD1gQs1KQhzxtRPsA.png" /><figcaption>Birinci Farkı Alınmış — ACF Grafiği</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*D3OenAA-M-BANZOWvP4Cmw.png" /><figcaption>Birinci Farkı Alınmış —PACF Grafiği</figcaption></figure><p>Yukarıdaki grafikler, serinin farkı alındıktan sonra oluşturulan ACF ve PACF grafiklerini göstermektedir. Seri durağan hale gelmiş gibi görünüyor fakat sizin de bir şey dikkatinizi çekmiyor mu?</p><p>Dikkat etmemiz noktaya değinmeden önce gelin bir de ADF ve KPSS testi yaparak serinin durağan hale gelip gelmediğinden emin olalım :</p><pre>ADF Statistic: -11.517895214887874<br>p-value: 4.1073890331024725e-21<br>Seri Durağan<br><br>KPSS Test Statistics: 0.018849922085689242<br>p-value: 0.1<br>Seri Durağan</pre><p>Tamam seriyi durağan hale getirmeyi başardık. Peki, yukarıdaki grafiklerde hala bazı gecikmelerde bir ilişki olduğu görülmektedir. Bunun sebebi serinin mevsimsellik barındırmasıdır. İlk başta tespit ettiğimiz şekilde, zirveler her 7 günde bir olmaktadır. Yani periyodumuzun 7 olduğunu söyleyebiliriz. Bu bilgi de bizi mevsimsel ARIMA yani SARIMA modelinin serimiz için daha uygun olabileceği bilgisine götürüyor.</p><p>DİKKAT! DİKKAT! :)</p><p>Serinin birinci farkını alarak yaptığımız durağanlaştırma işlemi seriyi trend etkisinden arındırarak durağan hale gelmesini sağladı. Burda yaptığımız işlem mevsimsel olmayan fark alma işlemidir. Yalnız seri hala mevsimselliğin etkisindedir. Bu durumda kuracağınız ARIMA modeli muhtemelen iyi performans göstermeyecektir.</p><p>Peki ne yapabiliriz?</p><p>Serinin bir de mevsimsel farkını almamız gerekmektedir. Az önce de bahsettiğim gibi mevsimsellik içeren serilere uygun bir model olan SARIMA modelini kullanabiliriz.</p><p><strong>SARIMA (S</strong>easonal <strong>A</strong>uto<strong>R</strong>egressive <strong>I</strong>ntegrated <strong>M</strong>oving <strong>A</strong>verage<strong>)</strong></p><p>Bir diğer Box-Jenkins yöntemi, Mevsimsel eğilimleri modelleyebilmemizi sağlayan SARIMA(Mevsimsel<strong> </strong>Otoregresif Entegre Hareketli Ortalama) modeli, ARIMA modelinin uyarlanmış bir versiyonudur diyebiliriz.</p><p>SARIMA modeli, ARIMA modelindeki mevsimsel olmayan bileşenlere (p,d,q) ek olarak, mevsimsel bileşenlere (P,D,Q,s) sahiptir. Mevsimsel bileşenler sırasıyla; otoregresif sırasını, fark sırasını ve hareketli ortalama sırasını ve periyot sayısını temsil eder.</p><p>Notasyonu şu şekildedir : <strong><em>SARIMA (p,d,q) (P,D,Q)s</em></strong></p><p>Bu da temelde modelin mevsimsel hareketleri algılayarak daha iyi öngörü yapmasını sağlıyor.</p><p>Mevsimsellikten kurtulmak için ACF grafiğinden daha önce belirlediğimiz periyot sayısını baz alarak serinin mevsimsel farkını alıyoruz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*OVl5y_qDgwhNVHmTiSIiTw.png" /><figcaption>Mevsimsel Farkı Alınmış — ACF</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*xMlFDNlt-9DOlXyfgMLtOw.png" /><figcaption>Mevsimsel Farkı Alınmış —PACF</figcaption></figure><p>ACF grafiğinden anlaşılacağı üzere mevsimsellik etkisini ortadan kaldırmayı başardık.</p><pre>ADF Statistic: -18.372774147759294<br>p-value: 2.2166111743407356e-30<br>Seri Durağan<br><br>KPSS Test Statistics: 0.010250802628270732<br>p-value: 0.1<br>Seri Durağan</pre><p>Serimizdeki trend ve mevsimsellik etkisini ortadan kaldırarak serinin durağan hale geldiğini tespit ettik. Bu analizler sonucunda bir model yapısı kurmaya çalışalım:</p><p>ARIMA ve SARIMA sürecindeki analizlerden yola çıkarak modelimizi oluşturuyoruz: <strong><em>SARIMA (2,1,1) (0,1,1)7</em></strong></p><p>Hem trend hem mevsimsel fark alınarak durağan hale gelen bir seri olduğunu tespit etmiştik( d = 1 ve D = 1). PACF grafiğinde ilk iki gecikmenin önemli olması AR(2) süreci olabileceğini düşündürmektedir. MA terimi için birden fazla gecikme önemli gibi durmaktadır. Burada yaklaşık bir çıkarım yapmak zor olduğu için şimdilik ilk modelimizdeki MA sürecini MA(1) olarak tanımladım. Mevsimsel AR(P) için PACF grafiğine baktığımız zaman ilgili gecikmelerde tekrar eden bir durum söz konusu olduğu için P = 0, Mevsimsel MA(Q) için tek bir gecikme olması Q=1 sürecine karar vermeme neden oldu.</p><p>Seçilen parametreleri model sonuçlarındaki anlamlılık düzeylerine göre değiştirebilir veya çıkartabilirsiniz.</p><p>Model parametrelerini belirlemenin başka yolları da vardır. Bunlardan biri “grid search” yapmaktır. Kabaca sistemin çalışma mantığı, birtakım istatistiksel testler yaparak modelinize en uyumlu parametreleri döndürmesidir. Bu pratik bir yöntemdir fakat öncesinde gerekli analizlerin yapılarak zaman serisinin çözümlenmesi oldukça faydalı olabilir.</p><p>Burada temel mantığı aktarmak adına, ACF-PACF grafiklerini inceleyerek manuel olarak bir parametre seçimi yapmayı göstermek istedim.</p><p><strong>Facebook Prophet</strong></p><p>Geleneksel zaman serileri analiz yöntemlerini kullanarak başarılı sonuçlar elde etmek uzmanlık gerektirir ve zaman alıcıdır. Özellikle model oluşturma aşamasında parametrelerin seçilmesi ve ayarlanması oldukça zordur. Ve bazen tüm denemelere rağmen tatmin edici sonuçlar elde edilemeyebilir.</p><p>Ayrıca “<em>Ben bu alanda bilgi sahibi değilim ya da benim zamanım kısıtlı tüm bu analiz ve çözümlerle vakit kaybetmek istemiyorum ama zaman serileriyle de çalışmak istiyorum</em>” diyebilirsiniz.</p><p>Facebook bu noktada, 2017&#39;de, zaman serileri analizi hakkında herkesin rahatlıkla kullanabileceği hızlı, güçlü ve kolay bir şekilde tek değişkenli zaman serisi modellemesi sağlayan, Python ve R’da uygulanabilir, açık kaynak kodlu bir kütüphane olan <em>Prophet’i</em> geliştirdi.</p><p>Prophet, trend, mevsimsellik ve tatiller olmak üzere üç ana model bileşene sahiptir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*JvUcuq2jFABRmkK8pKT0Gw.jpeg" /><figcaption>Prophet Bileşenleri</figcaption></figure><p><strong>g(t):</strong> parçalı doğrusal veya lojistik büyüme eğrisi</p><p><strong>s(t):</strong> mevsimsellik</p><p><strong>h(t):</strong> tatiller</p><p><strong>εt:</strong> hata terimi</p><p>Prophet kabaca, zamanın doğrusal ve doğrusal olmayan fonksiyonlarını otomatik bir şekilde bileşen olarak modele fit etmeye yani uydurmaya çalışır. Prophet, serinin içerisinde bulunan trendleri otomatik olarak bizim için tespit eder. Daha sonra fit edilen modeli kullanarak geleceğe yönelik tahmin işlemleri gerçekleştiririz.</p><p>FB Prophet’e özet bir giriş yapmış olduk. Daha sonra uygulamalı olarak anlatmaya devam edeceğim FB Prophet konusunu şimdilik burada bitiriyorum.</p><p>Bir sonraki yazımda, <a href="https://medium.com/@mervegunak/zaman-serileri-analizi-1-181422b3c4b4">Zaman Serileri Analizi — 1</a> ve bu bölümde anlattıklarımı Python ile pratiğe dökeceğiz. Aynı zamanda FB Prophet konusuna uygulamalı olarak kaldığımız yerden devam etmiş olacağız.</p><p>Vakit ayırdığınız için teşekkürler…</p><p>Bana her zaman <a href="https://www.linkedin.com/in/merve-gunak/">linkedin</a> ve<a href="https://twitter.com/mervgunak"> twitter</a> üzerinden ulaşabilirsiniz.</p><p>Bilim ve Sanatla Kalın !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4f6a750cd5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-t%C3%BCrkiye/zaman-serileri-analizi-2-e4f6a750cd5d">Zaman Serileri Analizi — 2</a> was originally published in <a href="https://medium.com/machine-learning-t%C3%BCrkiye">Machine Learning Turkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zaman Serileri Analizi — 1]]></title>
            <link>https://medium.com/machine-learning-t%C3%BCrkiye/zaman-serileri-analizi-1-181422b3c4b4?source=rss-dd943720f140------2</link>
            <guid isPermaLink="false">https://medium.com/p/181422b3c4b4</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Merve Günak]]></dc:creator>
            <pubDate>Sat, 20 Nov 2021 10:56:05 GMT</pubDate>
            <atom:updated>2023-08-02T19:51:12.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zaman Serileri Analizi — 1</h3><figure><img alt="Time Machine" src="https://cdn-images-1.medium.com/max/1024/1*oSXXoR26EyCU-sI4WWVk2Q.png" /><figcaption>The Time Machine</figcaption></figure><h3>Zaman Serisi Nedir?</h3><p>Zaman Serisi verileri kısaca eşit zaman aralıklarında elde edilen ve kronolojik bir zaman sırasında tutulan verilerdir. Zaman serisi verileri hemen hemen her yerdedir, çünkü zaman gözlenebilen her şeyin bir parçasıdır. Ekonomik göstergeler, hava durumu, sensör verileri ve tıklamalar zaman serisi verilerine örnektir.</p><p>Yüzyıllar boyunca insanlık geleceği bilmek istedi ve bir zaman sonra bu istek aynı zamanda zorunlu bir hale geldi. Bir gözlemin bugünkü ve geçmiş değerlerine bakarak, gelecekte alacağı değerlerin tespit edilmeye çalışılması geleceği tahminleme işidir. Bunu yapabilmenin en iyi yollarından birisi zaman serisi analizleridir.</p><p>Zaman serisi analizinin birden fazla alanda farklı kullanım durumları vardır. Elektrik tüketim tahmini, örüntü tanıma, sinyal işleme, deprem tahmini, aykırı değerlerin yakalandığı anomali tespiti gibi birçok yerde kullanılır.</p><p>Aşağıdaki grafik bir zaman serisinin grafiksel gösterimine örnek olması açısından EPİAŞ üzerinden çektiğim ve günlük frekansta oluşturduğum 2017–2021 Türkiye’nin Elektrik Tüketim verilerini temsil etmektedir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKJOg1aQP0ZqV3t5flkFxg.png" /><figcaption>2017–2021 Türkiye Elektrik Tüketimi Grafiği</figcaption></figure><h3>Zaman Serisi Bileşenleri</h3><p>Zaman serileri dört bileşene ayrılabilir:</p><p><strong><em>Trend</em></strong> — Verilerin yukarı ya da aşağı yönlü olarak uzun vadede sergiledikleri harekete trend denir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*E9NDUGEAjFtybsnwIzWDow.png" /></figure><p><strong><em>Mevsimsellik</em></strong> — Bir dönem boyunca tekrar eden belirli bir kalıbı tanımlar. Periyodik olarak tekrar eden bir örüntü sergiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*OlgiPLxytWyq6ysqRc5DaQ.png" /></figure><p><strong><em>Gürültü</em></strong> — Kalıntılar veya düzensizlikler olarak da bilinir. Trend ve mevsimsellik etkisi ortadan kaldırıldıktan sonra geriye kalan şey kalıntılardır. Öngörülemeyen kısa vadeli dalgalanma şeklinde de özetlenebilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*B2nEpPBvXsl1MRmiiAZJ7g.png" /></figure><p><strong><em>Konjonktürel Dalgalanmalar </em></strong>— Bir yıldan fazla süren, uzunluğu sabit kalmayan ve genellikle ekonomik koşulların etkisinden dolayı birçok değişkende görülen dalgalanmalardır.</p><p>Bu incelemelerin yapılmasındaki esas amaç zaman serisi verilerindeki desenleri ortaya çıkarıp, bir sonraki bölümde göreceğimiz model seçimi aşamasında bu örüntüleri doğru şekilde kavrayabilecek bir model seçimi yaparken bize yol gösterecek olmalarıdır.</p><p><strong><em>Zaman serisi analizi temelde belirli bir değişkenin zamanla nasıl değiştiğini görmek istediğimiz zaman bize ışık tutacak bir yöntemdir.</em></strong></p><p><strong><em>İki tür zaman serisi modeli vardır:</em></strong></p><ul><li><strong>Tek değişkenli zaman serisi:</strong> Bir zamana bağlı değişkeni ve tek bir bağımsız değişkeni olan zaman serisi.</li><li><strong>Çok Değişkenli Zaman Serileri</strong>: Bir zamana bağlı değişken ve birden fazla bağımsız değişken içeren zaman serileri.</li></ul><p>Dikkat edilmesi gereken noktalardan bir diğeri ise serinin deterministik veya stokastik özelliklerinin incelenmesidir.</p><p>Sabit bir kat sayı, mevsimsellik ve trend deterministik özelliklerken, stokastik özellik değişkenin durağanlığı ile ilgilidir.</p><p>Hmm… Durağanlık mı…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*K76_tukUjnmuRzAG2QBBMw.png" /></figure><h3><strong>Durağanlık ve Durağan-Dışılık Nedir?</strong></h3><p>Bir serinin geçmiş değerlerine bakarak geleceğe yönelik tahminler yapmaktan söz ediyorduk. Bunu doğru bir şekilde yapabilmemiz için elimizdeki serinin “durağan” olmasını bekliyoruz.</p><p>Peki tam olarak bir seriye durağan diyebilmemiz için ne olması gerekiyor?</p><p><em>Zaman içinde belirli bir değere doğru yaklaşan yani sabit ortalama, sabit varyans ve sabit otokorelasyon yapısına sahip olan seriler durağan serilerdir. Bu tanımlamalardan herhangi birini sağlamayan bir zaman serisi durağan-dışı olarak tanımlanır.</em></p><p>Zaman serileri genellikle durağan değildir. Bu seriler birinci veya ikinci farkları ya da logaritmaları alınarak durağan hale getirilmektedir.</p><p>Zaman serileri çözümlemesinde serilerin durağan olması neden önemlidir?</p><p>Çünkü bir seri eğer durağan değilse farklı örüntüler sergiler. Bu durumda serinin davranışı diğer dönemlere genellenemez ve geleceği tahmin etmek için faydalı olmaz. İşte bu yüzden elimizdeki bir zaman serisinin durağan olup olmadığını bilmek isteriz.</p><p>Gelin hep beraber bir serinin durağan olup olmadığını nasıl tespit edebileceğimizi görelim.</p><h3><strong>Durağanlık Sınamaları Nasıl Yapılır ?</strong></h3><p>Durağanlık sınaması için çeşitli yöntemler vardır. Bunlar arasından en yaygın kullanılan ADF,<strong> </strong>Phillipps-Perron, KPSS birim kök testlerinden ve Korelogram grafiğinden bahsedeceğim:</p><p><strong>1-Birim Kök Testleri</strong></p><ul><li><strong>Genişletilmiş Dickey-Fuller Testi (ADF) :</strong></li></ul><p><em>Sıfır hipotezi : Zaman serisinin durağan-dışı (birim kök içerir)</em></p><p><em>Alternatif Hipotez: Zaman serisinin durağan (birim kök içermez)</em></p><p>T-test üzerinden hesaplanan değer ADF Testi için hesaplanmış olan kritik değerlerden küçükse sıfır hipotezi reddedilir ve bu serinin durağan olduğu anlamına gelir. Eğer sıfır hipotezini reddetmekte başarısız olunursa seri birim kök içerir yani durağan-dışı deriz.</p><ul><li><strong>Phillipps-Perron Testi</strong></li></ul><p>Zaman serilerinde bir diğer birim kök sınaması için kullanılan test<strong> </strong>Phillipps-Perron testidir. ADF’den farklı olarak t-test istatistiğine parametrik olmayan bir düzeltme yapar. Böylelikle otokorelasyonlar ve değişen varyans durumlarında daha düzgün sonuçlar üretir.</p><ul><li><strong>KPSS</strong></li></ul><p>ADF testi gibi, KPSS testi de bir serinin durağanlığını analiz etmek için yaygın olarak kullanılmaktadır. KPSS testi için sıfır ve alternatif hipotez, ADF testinin tersidir.</p><p><strong>2- Otokorelasyon (ACF)</strong></p><p>ACF grafiği, verilerin zaman grafiğine bakmanın yanı sıra, durağan olmayan zaman serilerini belirlemek için de kullanışlıdır.</p><p><strong>ACF</strong> durağan olmayan bir zaman serisi için yavaşça düşer. Mesela çok yüksek bir değerden başlayıp sıfıra doğru çok yavaş düşmesi. Durağan bir zaman serisi içinse otokorelasyon fonksiyonu hızla sıfıra yaklaşır.</p><p>Aşağıdaki ilk grafik durağan olmayan bir serinin ACF grafiğini göstermekte olup, ikinci grafik aynı serinin birinci farkı alınıp durağan hale getirildikten sonra çizilen ACF grafiğini temsil etmektedir :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*1pOKSzl_whO9NkyCgA-5tA.png" /><figcaption>Durağan-Dışı Seri — ACF Grafik</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*T-_tm__3xk9rm85egtaKNw.png" /><figcaption>1. Farkı Alınan Seri — ACF Grafik</figcaption></figure><p>Özetle,</p><p>Yukarıdaki durağanlık sınama yöntemlerinden sadece bir tanesinin kullanılmasından ziyade hem grafiksel hem de parametrik yöntemlerin birlikte kullanılması seri hakkında daha doğru çıkarımlar yapılmasını sağlayacaktır.</p><p>Özellikle istatistiksel bir alanda çalışma yapıyorsanız, tek bir teste bağlı kalmak bazen sizi büyük bir yanılgıya doğru sürükleyebilir.</p><p>Buraya kadar zaman serisi hakkında fazla detaya ve istatistiksel ispatlara girmeden önemli temel kavramlardan bahsettim. <a href="https://medium.com/machine-learning-t%C3%BCrkiye/zaman-serileri-analizi-2-e4f6a750cd5d">Gelecek bölümde</a> Box-Jenkis Modelleri ve Facebook Prophet üzerinde duracağız…</p><p>Vakit ayırdığınız için teşekkürler…</p><p>Bana her zaman <a href="https://www.linkedin.com/in/merve-gunak/">linkedin</a> ve<a href="https://twitter.com/mervgunak"> twitter</a> üzerinden ulaşabilirsiniz.</p><p>Bilim ve Sanatla Kalın !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=181422b3c4b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-t%C3%BCrkiye/zaman-serileri-analizi-1-181422b3c4b4">Zaman Serileri Analizi — 1</a> was originally published in <a href="https://medium.com/machine-learning-t%C3%BCrkiye">Machine Learning Turkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>