<?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 Anurag Bisht on Medium]]></title>
        <description><![CDATA[Stories by Anurag Bisht on Medium]]></description>
        <link>https://medium.com/@anuragbisht12?source=rss-97bc9eb0b784------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PgamYYWIWkcM1HEmW3lQxQ.jpeg</url>
            <title>Stories by Anurag Bisht on Medium</title>
            <link>https://medium.com/@anuragbisht12?source=rss-97bc9eb0b784------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:50:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anuragbisht12/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[Cohesion vs Coupling in Software Design Patterns]]></title>
            <link>https://anuragbisht12.medium.com/cohesion-vs-coupling-in-software-design-patterns-5154f6db4148?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/5154f6db4148</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[cohesion]]></category>
            <category><![CDATA[coupling]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 08:51:08 GMT</pubDate>
            <atom:updated>2023-11-24T08:51:08.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYr6Y-vu046P4TzbTpQU4g.png" /><figcaption>source: internet</figcaption></figure><p>Software design is a crucial aspect of the development process that involves creating a blueprint for building a system or application. Two fundamental concepts in software design are cohesion and coupling, which play a significant role in determining the quality and maintainability of code. Let’s explore the differences between cohesion and coupling and how they impact software design, using Python examples to illustrate these concepts.</p><h3>Cohesion:</h3><p>Cohesion refers to the degree to which the elements within a module (e.g., a class or a function) work together to achieve a common goal. In other words, it measures how closely the components of a module are related to each other. High cohesion is desirable because it leads to more readable, maintainable, and modular code.</p><h3>Types of Cohesion:</h3><ol><li><strong>Functional Cohesion:</strong></li></ol><ul><li>This occurs when the elements of a module are grouped together because they all contribute to a single, well-defined task.</li></ul><pre>def calculate_area(radius):<br>    pi = 3.14<br>    return pi * radius * radius</pre><p><strong>2. Sequential Cohesion:</strong></p><ul><li>Elements in a module are arranged in a sequence, and the output of one becomes the input of the next.</li></ul><pre>def process_data(data):<br>    result = preprocess(data)<br>    result = analyze(result)<br>    result = visualize(result)<br>    return result</pre><p><strong>3. Communicational Cohesion:</strong></p><ul><li>Elements are grouped together because they operate on the same set of data.</li></ul><pre>def print_report(data):<br>    header = generate_header(data)<br>    body = generate_body(data)<br>    footer = generate_footer(data)<br>    print(header, body, footer)</pre><p>4. <strong>Procedural Cohesion:</strong></p><ul><li>The function process_data contains steps that are part of set of procedure.</li></ul><pre># Procedural Cohesion Example<br>def process_data(data):<br>    validate(data)<br>    clean_data(data)<br>    transform_data(data)<br>    store_data(data)<br><br>def validate(data):<br>    # validation logic<br><br>def clean_data(data):<br>    # cleaning logic<br><br>def transform_data(data):<br>    # transformation logic<br><br>def store_data(data):<br>    # storing logic</pre><p><strong>5. Temporal Cohesion:</strong></p><ul><li>The elements are not necessarily related to a single function or task, but they are related to a specific time or event.</li></ul><pre># Temporal Cohesion Example<br>def perform_tasks_at_midnight():<br>    # tasks to be performed at midnight<br><br># Client code<br>perform_tasks_at_midnight()</pre><p><strong>6. Logical Cohesion:</strong></p><ul><li>​Elements within a module or component are related to a specific logical condition or decision.</li></ul><pre># Logical Cohesion Example<br>def process_data(data):<br>    if is_valid(data):<br>        perform_logic(data)<br>    else:<br>        handle_invalid_data(data)<br><br>def is_valid(data):<br>    # check if data is valid<br><br>def perform_logic(data):<br>    # perform logic on valid data<br><br>def handle_invalid_data(data):<br>    # handle invalid data</pre><p>Here are some key advantages of high cohesion:</p><ol><li><strong>Readability and Understandability:</strong></li></ol><p>When the components within a module are highly cohesive, their functionality is closely related and focused on a specific task. This makes the code more readable and easier to understand. Developers can quickly grasp the purpose and behavior of a module without having to navigate through irrelevant or loosely related code.</p><p><strong>2. Modularity:</strong></p><p>High cohesion promotes modularity by encapsulating related functionality within a single module (such as a class or a function). This modularity allows developers to work on individual components independently, making it easier to manage, update, and maintain the codebase. It also facilitates code reuse as cohesive modules can be employed in different parts of the system without modification.</p><p><strong>3. Maintainability:</strong></p><p>Code with high cohesion is typically easier to maintain. Since each module has a well-defined responsibility, modifications or bug fixes can be localized to specific modules without affecting the entire system. This reduces the risk of introducing unintended side effects and streamlines the debugging and maintenance process.</p><p><strong>4. Flexibility and Adaptability:</strong></p><p>Highly cohesive modules are more flexible and adaptable to changes. When new requirements arise, developers can modify or extend a cohesive module without worrying about impacting other parts of the system. This adaptability is crucial in dynamic software development environments where requirements may evolve over time.</p><p><strong>5. Testability:</strong></p><p>Modules with high cohesion are often more testable. Testing becomes more straightforward because the functionality encapsulated within a module is focused and well-defined. Unit testing, integration testing, and other testing processes can be conducted more effectively when modules have clear and specific responsibilities.</p><p><strong>6. Encapsulation:</strong></p><p>High cohesion encourages encapsulation, which is the bundling of related data and methods into a single unit. This encapsulation helps in hiding the internal details of a module, exposing only what is necessary for external use. This reduces the complexity of the system, enhances security, and facilitates the creation of well-defined interfaces.</p><p><strong>7. Code Reusability:</strong></p><p>Cohesive modules are often designed to perform specific, reusable tasks. This promotes code reusability as these modules can be employed in different parts of the system or even in other projects without modification. Reusing cohesive code reduces redundancy and accelerates development.</p><h3>Coupling:</h3><p>Coupling refers to the degree of interdependence between modules. Low coupling is desirable as it promotes reusability and maintainability. If modules are loosely coupled, changes in one module are less likely to affect others.</p><h3>Types of Coupling:</h3><ol><li><strong>Data Coupling:</strong></li></ol><ul><li>Modules are independent and communicate by passing minimal data between them.</li></ul><pre>def calculate_area(radius):<br>    return pi_times_radius_squared(radius)<br><br>def pi_times_radius_squared(radius):<br>    pi = 3.14<br>    return pi * radius * radius</pre><p><strong>2. Control Coupling:</strong></p><ul><li>Modules share information by controlling each other’s behavior.</li></ul><pre>def process_data(data):<br>    if validate(data):<br>        result = analyze(data)<br>        visualize(result)<br><br>def validate(data):<br>    # validation logic<br>    return valid</pre><p><strong>3. Stamp Coupling:</strong></p><ul><li>Modules share a complex data structure, like a record or object.</li></ul><pre>class Report:<br>    def __init__(self, header, body, footer):<br>        self.header = header<br>        self.body = body<br>        self.footer = footer<br><br>def generate_report(data):<br>    header = generate_header(data)<br>    body = generate_body(data)<br>    footer = generate_footer(data)<br>    return Report(header, body, footer)</pre><p><strong>4. Content Coupling:</strong></p><ul><li>ModuleA accesses the internal data of ModuleB, demonstrating content coupling.</li></ul><pre># Content Coupling Example<br>class ModuleA:<br>    def get_data(self):<br>        # access internal data of ModuleB<br>        module_b_data = ModuleB().data<br>        return module_b_data<br><br>class ModuleB:<br>    def __init__(self):<br>        self.data = &quot;Some data&quot;</pre><p><strong>5. Message Coupling:</strong></p><ul><li>Here, ModuleA and ModuleB communicate through messages, showcasing message coupling. This is a more loosely coupled approach, as modules interact through defined messages or signals.</li></ul><pre># Message Coupling Example<br>class ModuleA:<br>    def send_message(self, message):<br>        # ModuleA sends a message to ModuleB<br>        ModuleB().receive_message(message)<br><br>class ModuleB:<br>    def receive_message(self, message):<br>        # message handling logic<br>        pass</pre><p>Here are some key advantages of low coupling:</p><ol><li><strong>Modifiability:</strong></li></ol><p>Low coupling reduces the interdependence between modules. As a result, making changes to one module is less likely to impact other modules. This modifiability is crucial in dynamic software development environments where requirements may change frequently. Developers can modify or replace one module without affecting the entire system.</p><p><strong>2. Maintainability:</strong></p><p>Systems with low coupling are typically easier to maintain. When modules are loosely connected, changes can be isolated to specific modules, reducing the risk of unintended side effects in other parts of the system. Maintenance becomes more straightforward, and debugging is less complex because the scope of impact is limited.</p><p><strong>3. Scalability:</strong></p><p>Low coupling facilitates system scalability. As the size and complexity of a software system grow, loosely coupled modules allow for easier integration of new components or features. Developers can add or replace modules without disrupting the existing functionality, making it easier to scale the system to meet evolving requirements.</p><p><strong>4. Flexibility and Adaptability:</strong></p><p>Systems with low coupling are more flexible and adaptable to changes. New features or modules can be added, and existing ones can be modified or replaced with minimal impact on the rest of the system. This adaptability is essential in environments where the software needs to evolve in response to changing business needs or technological advancements.</p><p><strong>5. Parallel Development:</strong></p><p>Low coupling enables parallel development by allowing teams to work on different modules independently. Teams can develop, test, and deploy modules concurrently without extensive coordination. This parallel development approach can significantly reduce time-to-market and increase overall development efficiency.</p><p><strong>6. Reusability:</strong></p><p>Loosely coupled modules are often more reusable. Since modules are designed to be independent, they can be reused in different contexts or projects without significant modification. This reusability reduces redundancy, accelerates development, and ensures that well-tested and reliable components are leveraged across various parts of the system.</p><p><strong>7. Testability:</strong></p><p>Low coupling enhances testability. With loosely coupled modules, it’s easier to isolate and test individual components independently. This facilitates unit testing, integration testing, and other testing processes, leading to more effective and comprehensive testing of the entire system.</p><p><strong>8. Dependency Management:</strong></p><p>Low coupling reduces the number and strength of dependencies between modules. This simplifies dependency management and makes it easier to understand and control the relationships between different components. Reduced dependencies also minimize the ripple effects of changes, making the system more robust.</p><h3><strong>Conclusion</strong></h3><p>In summary, high cohesion is a crucial design principle that leads to more maintainable, modular, and readable code. It enhances the flexibility of the software system, making it easier to adapt to changes and reducing the likelihood of introducing errors during development and maintenance.</p><p>Low coupling is a critical design principle that promotes modifiability, maintainability, scalability, flexibility, and other positive attributes in a software system. It facilitates a more agile and responsive development process, allowing teams to adapt to changing requirements and maintain high-quality software over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5154f6db4148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying coroutines, multi-threads, and multi-processing for concurrency and parallelism]]></title>
            <link>https://anuragbisht12.medium.com/demystifying-coroutines-multi-threads-and-multi-processing-for-concurrency-and-parallelism-587a53519d32?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/587a53519d32</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[python-multiprocessing]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[multithreading-in-python]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 09:31:58 GMT</pubDate>
            <atom:updated>2023-03-18T09:32:54.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTMvLopVo_9ArdKmr8SZig.png" /><figcaption>image courtesy: internet</figcaption></figure><h3>Program vs Process vs Thread</h3><p><strong>Program</strong>: It is a set of instructions that tell a computer what to do. A program can be composed of one or more modules or files, and it can be compiled or interpreted. When a program is executed, it runs in its own address space and has access to its own memory and resources.</p><p><strong>Process</strong>: It is an instance of a running program. When a program is executed, it creates a process in memory that contains all the data structures needed to execute the program. Each process has its own memory space, which means that data cannot be shared between processes without special mechanisms such as inter-process communication. Processes are managed by the operating system, which provides services such as memory management, scheduling, and inter-process communication.</p><p><strong>Thread</strong>: It is a unit of execution within a process. A process can have one or more threads, which share the same memory space as the other threads in the process. Threads are managed by the operating system’s scheduler, which decides which thread to run at any given time. Multiple threads in a process can execute simultaneously on different CPUs or CPU cores, but this depends on the operating system and the hardware.</p><p>Thread states: <br>In Python 3.9, the possible thread states are:</p><ul><li>&quot;RUNNING&quot;: The thread is currently running.</li><li>&quot;FINISHED&quot;: The thread has finished executing its run method.</li><li>&quot;CANCELLED&quot;: The thread was canceled before it started running.</li><li>&quot;NEW&quot;: The thread has been created but has not yet started running.</li><li>&quot;STARTING&quot;: The thread has started but is not yet running.</li><li>&quot;WAITING&quot;: The thread is waiting for a lock or condition to become available.</li><li>&quot;LOCKED&quot;: The thread is waiting for a lock or condition to become available and has acquired the lock or condition.</li><li>&quot;TERMINATED&quot;: The thread has been terminated due to an unhandled exception.</li></ul><p>The “runnable” state is a common thread state in many programming languages and operating systems, but it is not one of the thread states in Python. In Python, the “runnable” state is considered to be part of the “waiting” state, which includes threads that are waiting for a lock or condition to become available. Once the lock or condition becomes available, the thread transitions to the “running” state and begins executing.</p><pre>import threading<br>import time<br><br>def worker():<br>    print(f&quot;Worker thread {threading.get_ident()} started&quot;)<br>    time.sleep(2)<br>    print(f&quot;Worker thread {threading.get_ident()} finished&quot;)<br><br>t = threading.Thread(target=worker)<br>print(f&quot;Thread {t.ident} created, state: {t.is_alive()}&quot;)<br><br>t.start()<br>print(f&quot;Thread {t.ident} started, state: {t.is_alive()}&quot;)<br><br>time.sleep(1)<br>print(f&quot;Thread {t.ident} state: {t.is_alive()}&quot;)<br><br>t.join()<br>print(f&quot;Thread {t.ident} joined, state: {t.is_alive()}&quot;)</pre><p>In summary, a program is a set of instructions that define how a computer should behave, a process is an instance of a running program that has its own memory space and resources, and a thread is a unit of execution within a process that shares the same memory space as the other threads in the process.</p><h3>Concurrency vs Parallelism:</h3><blockquote><strong>Concurrency</strong> refers to the ability of a system to handle multiple tasks or processes simultaneously, by interleaving them in time. This can be achieved through various techniques such as multitasking, multithreading, or event-driven programming.</blockquote><p>Concurrency does not necessarily mean that the tasks are running in parallel or at the same time; instead, they may be executed in overlapping time intervals, with each task making progress independently of the others using context switching.</p><p>Concurrency can be achieved through various techniques and programming models, depending on the requirements of the system and the programming language used. Here are some common techniques for achieving concurrency:</p><p><strong>Multithreading:</strong> This technique involves running multiple threads within a single process, with each thread executing a different task. Threads share the same memory space and can communicate with each other directly. Multithreading is commonly used in applications that require concurrent I/O operations, such as web servers or database applications.</p><pre>import time<br>from threading import Thread<br><br>def task1():<br>    for i in range(5):<br>        print(&quot;Task 1 is running&quot;)<br>        time.sleep(1)<br>def task2():<br>    for i in range(5):<br>        print(&quot;Task 2 is running&quot;)<br>        time.sleep(1)<br>if __name__ == &#39;__main__&#39;:<br>    # Run tasks concurrently using multithreading<br>    t1 = Thread(target=task1)<br>    t2 = Thread(target=task2)<br>    t1.start()<br>    t2.start()<br>    t1.join()<br>    t2.join()</pre><p><strong>Coroutines</strong>: This technique involves using cooperative multitasking within a single thread, by dividing a task into small, asynchronous sub-tasks that can yield control to other sub-tasks when they are waiting for I/O or other blocking operations to complete. Coroutines are commonly used in Python, as well as in other languages that support them, such as Lua and Go.</p><p>Async and await are keywords in Python that are used to define asynchronous operations and manage coroutines.</p><p>Async is used to define a coroutine function, which is a special type of function that can be paused and resumed later, allowing other parts of the program to run in the meantime.</p><p>Await is used within an async function to wait for the result of another coroutine or async operation to complete before continuing with the rest of the function. When the await keyword is used, and the event loop is free to switch to another task, allowing the program to perform other operations while waiting for the async operation to complete.</p><pre>import asyncio<br><br>async def task1():<br>    for i in range(5):<br>        print(&quot;Task 1 is running&quot;)<br>        await asyncio.sleep(1)<br><br>async def task2():<br>    for i in range(5):<br>        print(&quot;Task 2 is running&quot;)<br>        await asyncio.sleep(1)<br><br>if __name__ == &#39;__main__&#39;:<br>    # Run tasks concurrently using event-driven programming<br>    loop = asyncio.get_event_loop()<br>    loop.run_until_complete(asyncio.gather(task1(), task2()))<br>    loop.close()</pre><h4>Some known challenges with concurrency:</h4><p>Concurrency can introduce a number of challenges when developing software, some of which include:</p><ol><li><strong>Race conditions</strong>: When multiple threads or processes access the same data concurrently, it can lead to race conditions where the final result depends on the order in which the threads or processes are executed. This can result in unpredictable behavior, data corruption, or crashes.</li><li><strong>Deadlocks</strong>: When two or more threads or processes are blocked waiting for each other to release a resource, it can lead to a deadlock where none of the threads or processes can proceed. This can result in the program hanging or crashing.</li><li><strong>Starvation</strong>: When a thread or process is prevented from making progress because it cannot acquire a necessary resource, it can lead to starvation where the thread or process is effectively blocked indefinitely. This can result in poor performance or a hang.</li><li><strong>Synchronization overhead</strong>: When multiple threads or processes need to coordinate access to shared resources, it can introduce synchronization overhead in the form of locks, semaphores, or other synchronization primitives. This can result in decreased performance and increased complexity.</li><li><strong>Debugging complexity</strong>: When multiple threads or processes are executing concurrently, it can make debugging more difficult, as it can be challenging to reproduce and isolate concurrency-related bugs.</li></ol><p>To solve synchronization issues we use some primitives to coordinate access to the shared resource.</p><h3>Semaphore vs Mutex vs Monitor vs Barrier</h3><p><strong>Mutex</strong>: A mutex (short for mutual exclusion) is a synchronization primitive used to protect shared resources from simultaneous access. A mutex can be in one of two states: locked or unlocked. A thread or process that wants to access the shared resource must first acquire the mutex. If the mutex is already locked, the thread or process will be blocked until the mutex is released by the thread or process that currently holds it.</p><pre>from threading import Thread<br>from threading import Lock<br><br>class Counter:<br>    def __init__(self):<br>        self.value = 0<br>        self.lock = Lock()<br><br>    def increment(self):<br>        # use context manage to acquire and release lock<br>        with self.lock:<br>            self.value += 1<br><br>def worker(counter):<br>    for i in range(10000):<br>        counter.increment()<br><br>if __name__ == &#39;__main__&#39;:<br>    # Create a Counter object<br>    counter = Counter()<br>    # Create two worker threads<br>    threads = [Thread(target=worker, args=(counter,))<br>               for i in range(2)]<br>    # Start the worker threads<br>    for thread in threads:<br>        thread.start()<br>    # Wait for the worker threads to finish<br>    for thread in threads:<br>        thread.join()<br>    # Print the final value of the counter<br>    print(&#39;Counter value:&#39;, counter.value)</pre><p><strong>Semaphore</strong>: A semaphore is a counter that can be used to control access to a shared resource. A semaphore can be either binary or counting. A binary semaphore can have only two values (0 or 1) and is typically used to indicate whether a resource is available or not. A counting semaphore can have an arbitrary positive value and is used to limit the number of concurrent accesses to a resource.</p><pre>from threading import Thread, Semaphore<br><br>class Resource:<br>    def __init__(self):<br>        self.available = Semaphore(3)<br><br>    def use(self):<br>        # acquire and release before accessing shared reosurce<br>        self.available.acquire()<br>        print(&#39;Resource used&#39;)<br>        self.available.release()<br><br>def worker(resource):<br>    for i in range(5):<br>        resource.use()<br><br>if __name__ == &#39;__main__&#39;:<br>    # Create a Resource object<br>    resource = Resource()<br>    # Create three worker threads<br>    threads = [Thread(target=worker, args=(resource,))<br>               for i in range(3)]<br>    # Start the worker threads<br>    for thread in threads:<br>        thread.start()<br>    # Wait for the worker threads to finish<br>    for thread in threads:<br>        thread.join()</pre><p><strong>Barrier</strong>: A barrier is a synchronization primitive used in concurrent programming to ensure that a group of threads or processes reach a certain point in their execution before continuing further.</p><pre>from threading import Thread, Barrier<br><br>def worker(barrier):<br>    print(&#39;Worker would for 3 threads to reach barrier wait&#39;)<br>    barrier.wait()<br>    print(&#39;Will execute only after 3 threads have reached barrier wait&#39;)<br><br>if __name__ == &#39;__main__&#39;:<br>    # Create a Barrier object with a threshold of 3<br>    barrier = Barrier(3)<br>    # Create three worker threads<br>    threads = [Thread(target=worker, args=(barrier,))<br>               for i in range(3)]<br>    # Start the worker threads<br>    for thread in threads:<br>        thread.start()<br>    # Wait for the worker threads to finish<br>    for thread in threads:<br>        thread.join()</pre><p><strong>Monitor</strong>: A monitor is a synchronization construct that combines a mutex with a condition variable. A monitor provides a higher-level abstraction than a mutex and is typically used to protect a collection of related resources. A monitor guarantees that only one thread or process can access the protected resources at any given time, and provides a mechanism for threads or processes to wait for a particular condition to be satisfied before accessing the resources.</p><pre>from threading import Thread, Lock, Condition<br><br>class Monitor:<br>    def __init__(self):<br>        self.lock = Lock()<br>        self.condition = Condition(self.lock)<br>        self.data = []<br><br>    def read(self):<br>        with self.condition:<br>            while not self.data:<br>                self.condition.wait()<br>            return self.data.pop(0)<br><br>    def write(self, value):<br>        with self.condition:<br>            self.data.append(value)<br>            self.condition.notify()<br><br>def writer(monitor):<br>    for i in range(10):<br>        monitor.write(i)<br>        print(f&#39;Writer wrote {i}&#39;)<br><br>def reader(monitor):<br>    for i in range(10):<br>        value = monitor.read()<br>        print(f&#39;Reader read {value}&#39;)<br><br>if __name__ == &#39;__main__&#39;:<br>    monitor = Monitor()<br>    threads = [<br>        Thread(target=writer, args=(monitor,)),<br>        Thread(target=reader, args=(monitor,))<br>    ]<br>    for thread in threads:<br>        thread.start()<br>    for thread in threads:<br>        thread.join()</pre><p>In summary, concurrency can be achieved through various techniques, depending on the requirements of the system and the programming language used. Each technique has its own trade-offs in terms of performance, complexity, and ease of use.</p><blockquote>Parallelism means that multiple processes are executing code simultaneously on different CPUs or CPU cores. Each process has its own memory space and can execute code independently of the other processes, which allows for true parallelism.</blockquote><p>Multiprocessing achieves true parallelism, meaning that multiple processes are executing code simultaneously on different CPUs or CPU cores. Each process has its own memory space and can execute code independently of the other processes, which allows for true parallelism.</p><pre>from multiprocessing import Pool<br><br>def mapper(data):<br>    # mapping function - takes a data item and returns a list of key-value pairs<br>    return [(word, 1) for word in data.split()]<br><br>def reducer(key_value_pairs):<br>    # reducing function - takes a key-value pair and returns a new key-value pair<br>    key, values = key_value_pairs<br>    return (key, sum(values))<br><br>if __name__ == &#39;__main__&#39;:<br>    # create a list of data items<br>    data = []<br>    for i in range(100):<br>        data = data + [<br>        &#39;hello world&#39;,<br>        &#39;hello python&#39;,<br>        &#39;python is great&#39;,<br>        &#39;hello world&#39;<br>    ]<br><br>    # map phase - parallelize the mapping function across multiple processes<br>    with Pool(processes=10) as pool:<br>        intermediate_data = pool.map(mapper, data)<br><br>    # flatten the intermediate data list<br>    intermediate_data = [item for sublist in intermediate_data for item in sublist]<br><br>    # group by key - create a dictionary of key-value pairs<br>    grouped_data = {}<br>    for key, value in intermediate_data:<br>        if key not in grouped_data:<br>            grouped_data[key] = []<br>        grouped_data[key].append(value)<br><br>    # reduce phase - apply the reducing function to each group of key-value pairs<br>    with Pool(processes=10) as pool:<br>        result = pool.map(reducer, grouped_data.items())<br><br>    # print the final output<br>    print(result)</pre><p>Multiprocessing in Python can also face some challenges, including:</p><ol><li><strong>Increased overhead</strong>: Creating and managing multiple processes can be more computationally expensive than using threads or a single process.</li><li><strong>Memory usage</strong>: Each process has its own memory space, which can increase the total amount of memory used by the application.</li><li><strong>Communication overhead</strong>: Interprocess communication (IPC) can be slower and more complicated than communication between threads in the same process.</li><li><strong>Difficulty in sharing data</strong>: Because each process has its own memory space, sharing data between processes requires explicit communication and synchronization mechanisms, such as pipes, queues, and shared memory.</li><li><strong>Scalability limitations</strong>: The performance gains from multiprocessing are limited by the number of available CPU cores, and scaling beyond a certain number of processes may not result in additional performance gains.</li><li><strong>Debugging complexity</strong>: Debugging multiprocessing code can be more complex than debugging single-threaded code due to the added complexity of managing multiple processes and potential race conditions.</li></ol><p>To overcome these challenges, it is important to carefully design the multiprocessing approach, taking into account the specific requirements of the application and the hardware resources available. This may involve optimizing the number of processes used, minimizing data transfers between processes, and implementing efficient synchronization mechanisms. Additionally, testing and debugging multiprocessing code thoroughly can help ensure its correctness and performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=587a53519d32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using and Optimizing your SQL queries for cloud MPP : Bigquery]]></title>
            <link>https://anuragbisht12.medium.com/using-and-optimizing-your-sql-queries-for-cloud-mpp-bigquery-30f04a43abd9?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f04a43abd9</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[cloud-data-warehouse]]></category>
            <category><![CDATA[mpp]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 13:24:17 GMT</pubDate>
            <atom:updated>2023-03-02T13:24:17.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using and Optimizing your SQL queries for cloud MPP : Bigquery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1b4w6KqjFKWZqzMTv6U00A.png" /><figcaption>Source Internet</figcaption></figure><p>SQL queries in BigQuery can be optimized in several ways to improve their performance and reduce the overall cost. Here are some ways to optimize SQL queries in BigQuery:</p><ol><li><strong>Use partitioned tables:</strong> Partitioning tables in BigQuery can significantly improve query performance, especially for large datasets. Partitioning tables in BigQuery allows you to split large tables into smaller parts, making it easier for BigQuery to scan only the relevant data. Let’s say you have a table of customer orders that is growing larger over time. By partitioning the table by order date, you can split the table into smaller parts based on the date range of the orders. This can speed up queries that only need to access a certain date range of orders.</li></ol><pre>CREATE TABLE mydataset.mytable<br>PARTITION BY DATE(order_date)<br>AS SELECT * FROM source_table</pre><p>Here are three ways to do partitioning in BigQuery:</p><p><strong>Date-based partitioning:</strong></p><p>One common approach is to partition data by date or timestamp. This can be useful for tables that have a time component, such as transactional or event data. To partition a table by date, you can create a new table with a partitioned column that corresponds to the date field in your data. For example:</p><pre>CREATE TABLE my_table<br>PARTITION BY DATE(timestamp)<br>AS<br>SELECT *<br>FROM my_source_table</pre><p>This creates a new table my_table that is partitioned by the timestamp column. BigQuery automatically creates a new partition for each day, based on the date in the timestamp column.</p><p><strong>Integer-based partitioning:</strong></p><p>You can also partition tables by integer values, such as a customer ID or product ID. This can be useful for tables that have a natural grouping based on a numeric identifier. To partition a table by integer, you can use the RANGE_BUCKET() function to assign each row to a specific partition based on the value of the integer column. For example:</p><pre>CREATE TABLE my_table<br>PARTITION BY RANGE_BUCKET(customer_id, GENERATE_ARRAY(0, 1000000, 10000))<br>AS<br>SELECT *<br>FROM my_source_table</pre><p>This creates a new table my_table that is partitioned into 100 partitions based on the customer_id column. Each partition contains rows with customer_id values that fall within a specific range.</p><p><strong>Ingestion-time partitioning:</strong></p><p>Ingestion-time partitioning is a feature in BigQuery that automatically partitions data based on the time it was ingested into the table. This can be useful for tables that are constantly being updated with new data. To enable ingestion-time partitioning, you can set the timePartitioning option when creating a new table. For example:</p><pre>CREATE TABLE my_table<br>PARTITION BY ingestion_time<br>OPTIONS(<br>  partition_expiration_days=7<br>)<br>AS<br>SELECT *<br>FROM my_source_table</pre><p>This creates a new table my_table that is partitioned based on the time the data was ingested. Each partition corresponds to a specific ingestion time, and partitions older than seven days are automatically deleted to prevent the table from becoming too large.</p><p>These are just a few examples of how partitioning can be done in BigQuery. There are many other ways to partition tables based on specific criteria, and the optimal partitioning strategy depends on the nature of your data and your query patterns.</p><p>2. <strong>Use clustered tables:</strong> Clustering tables is another way to improve query performance. Clustering involves organizing data within a partition based on one or more columns. This can help BigQuery to group related data together, reducing the amount of data scanned and improving query performance.</p><p>Clustering tables in BigQuery groups related data together, which can improve query performance by reducing the amount of data scanned. For example, if you have a table of customer orders and you often query by customer_id and order_date, clustering the table by these columns can speed up those queries.</p><p>Here are some ways clustering can help improve query performance in BigQuery:</p><ol><li>Reduced Data Scanning: When data is clustered, BigQuery can skip over large chunks of data that are not relevant to the query, reducing the amount of data that needs to be scanned. This can significantly reduce the time it takes to complete a query.</li><li>Reduced Costs: By scanning less data, clustered tables can reduce the cost of running queries in BigQuery, as you only pay for the data that is actually processed.</li><li>Faster Aggregation: When querying large datasets with aggregation functions like SUM, AVG, or COUNT, clustering can improve query performance by reducing the amount of data that needs to be processed.</li><li>Faster Joins: When joining two or more tables, clustering can improve query performance by ensuring that the data is physically sorted in a way that can optimize the join process.</li></ol><p>To take advantage of clustering in BigQuery, you should carefully choose the columns on which to cluster, as this can have a significant impact on query performance. You should also consider the size of the dataset and the types of queries you plan to run, as clustering may not always be necessary or beneficial for smaller datasets or certain types of queries.</p><pre>CREATE TABLE mydataset.mytable<br>CLUSTER BY customer_id, order_date<br>AS SELECT * FROM source_table</pre><p>Let’s say you have a large e-commerce dataset with millions of rows, including a transactions table with the following columns:</p><ul><li>transaction_id</li><li>user_id</li><li>timestamp</li><li>product_id</li><li>product_price</li><li>category</li></ul><p>To improve query performance on this table, you could create a clustered table using the user_id and timestamp columns, like this:</p><pre>CREATE TABLE transactions_clustered<br>CLUSTER BY user_id, timestamp<br>AS<br>SELECT *<br>FROM transactions</pre><p>Now, when you run a query that filters on user_id and/or timestamp, BigQuery can skip reading large portions of the data that do not match the filter criteria. For example, if you want to calculate the total revenue per user for a specific date range, you could run a query like this:</p><pre>SELECT user_id, SUM(product_price) AS total_revenue<br>FROM transactions_clustered<br>WHERE timestamp &gt;= &#39;2022-01-01&#39; AND timestamp &lt; &#39;2022-02-01&#39;<br>GROUP BY user_id</pre><p>Because the transactions_clustered table is sorted and stored based on user_id and timestamp, BigQuery can skip over most of the data that does not match the date range filter, resulting in faster query times and lower costs. This can be especially beneficial for large datasets with complex queries that would otherwise require scanning a significant amount of data.</p><p>3. <strong>Use caching:</strong> BigQuery provides caching capabilities that can help to speed up query performance. When a query is executed, BigQuery caches the results for a certain period of time. Subsequent queries can then retrieve the cached results, reducing query execution time and cost. Caching query results in BigQuery can reduce query execution time and cost. If you have a query that is frequently run with the same parameters, caching the results can speed up subsequent runs of the query. By default, BigQuery caches results for 24 hours.</p><pre>SELECT COUNT(*) FROM mydataset.mytable WHERE order_date = &#39;2022-01-01&#39;</pre><p>If you run this query multiple times with the same date parameter, BigQuery will cache the results for subsequent runs.</p><p><strong>4. Use appropriate join types:</strong> BigQuery supports several join types, including inner join, outer join, and cross join. Choosing the appropriate join type can significantly impact query performance. Inner join is usually the fastest and most efficient join type, while outer join and cross join can be slower.</p><pre>SELECT a.*, b.*<br>FROM table_a a<br>INNER JOIN table_b b<br>ON a.id = b.id</pre><p><strong>5. Use appropriate data types: </strong>Choosing the appropriate data types can also impact query performance. Using smaller data types wherever possible can help to reduce the amount of data scanned and improve query performance.</p><pre>CREATE TABLE mydataset.mytable<br>(order_id INT64, order_date DATE, customer_id INT64, order_amount NUMERIC)</pre><p>In this example, using INT64 for order_id and customer_id and DATE for order_date can help to reduce the amount of data scanned.</p><p><strong>5. Optimize subqueries:</strong> Subqueries can be useful for complex queries, but they can also be a performance bottleneck. To optimize subqueries, try to avoid using correlated subqueries and instead use join operations wherever possible.</p><pre>SELECT a.*<br>FROM table_a a<br>WHERE a.id IN (SELECT b.id FROM table_b b WHERE b.amount &gt; 100)</pre><p>In this example, using a join instead of a subquery can improve query performance:</p><pre>SELECT a.*<br>FROM table_a a<br>JOIN table_b b<br>ON a.id = b.id<br>WHERE b.amount &gt; 100</pre><p><strong>6. Use query optimization techniques:</strong> BigQuery provides several query optimization techniques, such as query plan explanation, query plan caching, and query prioritization. These techniques can help to improve query performance and reduce cost.</p><p>For example, you can use the EXPLAIN keyword to analyze the query plan and identify potential performance issues:</p><pre>EXPLAIN SELECT *<br>FROM mydataset.mytable<br>WHERE order_date &gt;= &#39;2022-01-01&#39;</pre><p><strong>7. Use efficient SQL code:</strong> Finally, writing efficient SQL code can also improve query performance. This includes avoiding unnecessary columns, using appropriate indexing, and using simple and efficient SQL syntax.</p><pre>-- Instead of this<br>SELECT *<br>FROM mydataset.mytable<br>WHERE order_date &gt;= &#39;2022-01-01&#39;<br><br>-- Use this<br>SELECT order_id, order_date, customer_id<br>FROM mydataset.mytable<br>WHERE order_date &gt;= &#39;2022-01-01&#39;</pre><p>Using simple and efficient SQL syntax can improve query performance by reducing the amount of data scanned and the time it takes to process the query. Avoid using complex queries and nested subqueries whenever possible.</p><pre>-- Instead of this complex query<br>SELECT a.*, b.*<br>FROM table_a a<br>WHERE a.id IN (SELECT b.id FROM table_b b WHERE b.amount &gt; 100)<br><br>-- Use this simple query with a join instead<br>SELECT a.*, b.*<br>FROM table_a a<br>JOIN table_b b<br>ON a.id = b.id<br>WHERE b.amount &gt; 100</pre><p><strong>8. Use WHERE clause instead of HAVING clause:</strong></p><p>In SQL, the WHERE clause is used to filter rows before aggregation, while the HAVING clause is used to filter groups after aggregation. Since the WHERE clause is executed before the aggregation, it is generally faster than the HAVING clause. Therefore, try to use the WHERE clause wherever possible to filter rows before aggregation.</p><pre>SELECT customer_id, SUM(order_amount) as total_amount<br>FROM mydataset.mytable<br>WHERE order_date &gt;= &#39;2022-01-01&#39;<br>GROUP BY customer_id<br>HAVING total_amount &gt; 1000</pre><p>In this example, the WHERE clause can be used to filter rows before aggregation and improve query performance:</p><pre>SELECT customer_id, SUM(order_amount) as total_amount<br>FROM mydataset.mytable<br>WHERE order_date &gt;= &#39;2022-01-01&#39;<br>AND order_amount &gt; 0<br>GROUP BY customer_id<br>HAVING total_amount &gt; 1000</pre><p><strong>9. Use LIMIT clause:</strong></p><p>If you only need a certain number of rows, using the LIMIT clause can improve query performance by reducing the amount of data scanned. The LIMIT clause limits the number of rows returned by a query.</p><pre>SELECT *<br>FROM mydataset.mytable<br>WHERE order_date &gt;= &#39;2022-01-01&#39;<br>LIMIT 100</pre><p>The limit clause might help only in cases where you would like to limit the data to the consumer application and wont have any impact on the data consumed by your query before limiting it. Hence limiting the data is partially helpful in optimizing the query performance.</p><p>There are some limitations with Bigquery, topic of discussion any other day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f04a43abd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Native and Cloud Agnostic Terminologies in Cloud Computing]]></title>
            <link>https://anuragbisht12.medium.com/cloud-native-and-cloud-agnostic-terminologies-in-cloud-computing-2b55877a0060?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b55877a0060</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-agnostic]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud-native]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 17:09:34 GMT</pubDate>
            <atom:updated>2023-02-28T17:09:34.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*m2EYROfJI5miiC2jMR7bAA.jpeg" /><figcaption>internet</figcaption></figure><p>In the world of software engineering, cloud computing has become an increasingly popular way to build and deploy applications. As cloud computing has evolved, two terms have emerged to describe different approaches to developing and deploying software in the cloud: cloud native and cloud agnostic.</p><p><strong>Cloud Native:</strong> Cloud native refers to a set of principles and practices that are designed to take full advantage of the capabilities of cloud computing. Cloud native applications are built using cloud services and resources, such as containers, serverless functions, and microservices. These applications are also designed to be highly scalable, fault-tolerant, and resilient, allowing them to operate in dynamic and unpredictable cloud environments.</p><p>One of the key benefits of a cloud native approach is that it allows software engineers to develop and deploy applications quickly and efficiently. By leveraging cloud services and resources, developers can focus on building the features and functionality that their applications require, rather than spending time managing infrastructure and other low-level details.</p><p>Another key advantage of cloud native applications is that they are designed to be highly portable. This means that they can be deployed across multiple cloud platforms, such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). This flexibility allows organizations to choose the cloud provider that best meets their needs, while also avoiding vendor lock-in.</p><p><strong>Cloud Agnostic:</strong> Cloud agnostic, on the other hand, refers to an approach that is designed to be independent of any specific cloud platform. Cloud agnostic applications are built using standard technologies and APIs, allowing them to be deployed on any cloud provider, or even on-premises infrastructure.</p><p>The main advantage of a cloud agnostic approach is that it allows organizations to avoid vendor lock-in. By building applications using standard technologies and APIs, organizations can deploy their applications on any cloud provider that supports those standards, without having to rewrite or modify their code.</p><p>However, the downside of a cloud agnostic approach is that it may not take full advantage of the capabilities of any particular cloud platform. Because cloud agnostic applications are designed to be platform-independent, they may not be able to leverage some of the advanced features and functionality that are available on specific cloud providers.</p><p>Which approach is right for your organization? The choice between a cloud native and cloud agnostic approach ultimately depends on the specific needs and goals of your organization. If you need to develop and deploy applications quickly and efficiently, and you want to take full advantage of the capabilities of cloud computing, a cloud native approach may be the right choice for you.</p><p>On the other hand, if you value flexibility and want to avoid vendor lock-in, a cloud agnostic approach may be a better fit. This approach can also be useful if you need to deploy your applications on-premises or on a variety of different cloud platforms.</p><p>In conclusion, the decision to adopt a cloud native or cloud agnostic approach should be based on a careful evaluation of your organization’s needs and goals. By taking the time to understand the advantages and disadvantages of each approach, you can make an informed decision that will help you build and deploy software that meets your organization’s unique requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b55877a0060" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data-structures and Algorithms using Python: Programming Series 101–3]]></title>
            <link>https://anuragbisht12.medium.com/data-structures-and-algorithms-using-python-programming-series-101-3-6eb72d0d4e7f?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eb72d0d4e7f</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[linked-lists]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Sun, 03 Jan 2021 20:01:07 GMT</pubDate>
            <atom:updated>2021-01-03T20:01:07.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Ps7hO7YL7VfZRvlsAnrmpA.png" /></figure><p>In the past post, we discussed stacks and queues as data structures, their major operations along with time and space complexity. To implement them we used list /array using python. If you don’t have any idea about stacks and queue, here is a link to the articles. <a href="https://medium.com/towards-artificial-intelligence/data-structures-and-algorithms-using-python-programming-series-101-dbd41d48ab4d">Link1</a> <a href="https://anuragbisht12.medium.com/data-structures-and-algorithms-using-python-programming-series-101-2-48eb3122a83e">Link2</a></p><p>Arrays are used in scenarios where memory utilization of the resources is continuous. But in cases where memory allocation can’t be continuous or the chance of insertion /removal of elements from the middle of the list is frequent, this might lead to shuffling of the elements or increased time of operation.</p><p>To overcome some of the challenges with the use of fixed linear data structure like the inability to efficiently insert or remove elements in the constant time since the memory allocation is continuous, we would today learn a new data structure linked list.</p><p><strong>LinkedList:</strong></p><p>This data structure allows constant time insertion and deletion from the list and dynamic allocation of the pointers avoiding the need for continuous memory space to store elements and hence avoiding fragmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6dheaFlUytGPgqfJhyckg.png" /><figcaption>Source:Internet</figcaption></figure><p>The best way to visualize a linked list data structure is a train.</p><p><strong>Node</strong>: Like the coaches of a train node can store data and has a <strong>next</strong> pointer which either points nowhere or to the next node.</p><p><strong>Linked List: </strong>Consider<strong> </strong>this a train with a <strong>head</strong> pointer (similar to the engine of a train).</p><p>Based on the implementation we can also have a tail pointer but for our case, we will always refer to the linked list using the head pointer.</p><p>We will also implement some of the operations /functions for the linked list.</p><ol><li><strong>print_list():</strong> O(n) time | O(1) space : This function will iteratively print elements of the linked list.</li><li><strong>append(): </strong>O(n) time | O(1) space :<strong> </strong>This function will append data at the end of the lined list.</li><li><strong>prepend(): </strong>O(1) time | O(1) space<strong>: </strong>Add the element at the beginning of the linked list.</li><li><strong>insert_after_node(): </strong>O(n) time | O(1) space: insert the element after specified element</li><li><strong>delete_node(): </strong>O(n) time | O(1) space: delete the element from the linked list.</li><li><strong>delete_node_at_pos(): </strong>O(n) time | O(1) space: delete the element from a position.</li><li><strong>len_iterative(): </strong>O(n) time | O(1) space: find the length of the linked list iteratively.</li><li><strong>len_recursive():</strong> O(n) time | O(n) space: find the length of the linked list recursively.</li></ol><p>The use of tail pointer could have helped in having constant time complexity in some cases like the append function, but for the scope of this post, we will focus more on implementation without considering the tail pointer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3af0951cf31dd2ecf26314657b860be/href">https://medium.com/media/f3af0951cf31dd2ecf26314657b860be/href</a></iframe><p>There are various pros and cons of using the linked list :</p><p><strong>Pros:</strong></p><ol><li>Dynamic memory allocation: Grows as new elements are added, no need to initialize with a fixed size in contrast to arrays.</li><li>Efficiently memory usage.</li><li>Easy to insert and remove elements when compared with continuous size data structures like arrays.</li></ol><p><strong>Cons:</strong></p><ol><li>Requires more space to implement and reside in comparison to arrays.</li><li>Random access to the elements is not available, unlike arrays that can be accessed using indexes.</li><li>The memory is allocated at run time rather than compiled time, as a result, the performance may marginally suffer against an array, but that’s insignificant due to computational power these days.</li></ol><p><strong>Applications in the real world:</strong></p><p>Any computer application that requires sequential access of the data/ work will internally use a linked list data structure due to the dynamic nature of the application. A simple example you can create is a calendar note app where each day note is displayed back in sequential order back to the user.</p><p>In the next post, we will discuss certain variations of a linked list that can help us overcome some of the traversal limitations of the linked lists.</p><p>I hope you enjoyed this post. Let me know your thoughts if you have any queries or suggestions, would love to hear more from you.</p><p>You can follow me for tutorials on AI/machine learning, programming, data analytics, and BI. You can connect with me on <a href="https://www.linkedin.com/in/anurag-bisht-39935a59/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eb72d0d4e7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Product Recommendation Engine on Google Cloud’s Platform]]></title>
            <link>https://pub.towardsai.net/building-a-product-recommendation-engine-on-google-clouds-platform-cf559abafe6a?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf559abafe6a</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 01:02:20 GMT</pubDate>
            <atom:updated>2020-12-29T01:02:20.860Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/cloud-computing">Cloud Computing</a></h4><h4>Using DataProc, Cloud SQL, and Cloud Storage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zl3GsjjEMwQIb966SzXmMA.png" /><figcaption>Image courtesy: Google</figcaption></figure><p>In my last post, I discussed how you could easily create an end to end recommendation engine using Amazon Sagemaker.<br>Today we will leverage the Google Cloud Platform and Apache Spark to create a recommendation engine that you can easily integrate with the data engineering pipeline. You can use the same mechanism and deploy it on AI platform notebooks.</p><p><strong>Prerequisites:</strong></p><ol><li>You need a Google Cloud Platform subscription <a href="https://cloud.google.com/pricing/?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=japac-IN-all-en-dr-bkws-all-all-trial-e-dr-1009137&amp;utm_content=text-ad-none-none-DEV_c-CRE_438601541971-ADGP_Hybrid%20%7C%20AW%20SEM%20%7C%20BKWS%20~%20T1%20%7C%20EXA%20%7C%20Pricing%20%7C%20M%3A1%20%7C%20IN%20%7C%20en%20%7C%20google%20cloud-KWID_43700036927608605-kwd-277810791968&amp;userloc_9302223-network_g&amp;utm_term=KW_try%20google%20cloud&amp;gclid=EAIaIQobChMIvKCJ1_Sp7QIViR0rCh3x0wVbEAAYASAAEgJMu_D_BwE">link</a>.</li><li>Access to google cloud services: cloud storage, dataproc, cloud SQL.</li><li>Knowledge of PySpark and SQL.</li></ol><p>Before we dive deep, let’s discuss a few terms.</p><p><strong>Matrix Factorization:</strong></p><p>It’s a collaborative filtering technique where user embedding and item embedding matrices are generated. The matrix product of both the matrix gives a close approximation of the user feedback for product recommendation. These matrix embeddings are learned over a period of time.</p><p>For more information, you can check my last <a href="https://medium.com/towards-artificial-intelligence/building-an-end-to-end-recommendation-engine-using-matrix-factorization-with-cloud-deployment-using-f878d43c1005">post</a> or check Google developer <a href="https://developers.google.com/machine-learning/recommendation/collaborative/matrix">documentation</a>.</p><p>Mathematically it can be represented using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*qQmY43D5RFSzVoklexvJkQ.png" /></figure><p>Where U and V are user embedding and item embedding matrix.</p><p>A is the dot product you want to represent close to the actual representation of user-item interaction. The distance is also known as the Frobenius distance.<br>In the real world, we also need to consider unobserved pairs into consideration, e.g., say a user is new and has never shown interest in a certain type of product than an existing user who has shown interest in more categories products.</p><p>Hence the objective function takes the below form, also called weighted matrix factorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUZ2UE02X0g3AxcS6WIdMA.png" /></figure><p>Where w0 is the hyperparameter, which is tuned and is important to balance out the sum over observed and unobserved entities.</p><p>There are 2 algorithms to minimize the above objective functions:</p><p><strong>SGD(stochastic gradient descent)</strong>: generalized technique</p><p><strong>pros</strong>: flexible and can be parallelized</p><p><strong>cons</strong>: slower to converge, handling unobserved entries is difficult.</p><p><strong>WALS(Weighted Alternating Least Squares):</strong> specialized for our objective.</p><p><strong>Pros</strong>: fast to converge, parallelization, handles unobserved entries.</p><p><strong>Cons</strong>: relies on loss square function.</p><p>Now let’s jump into the real-world problem.</p><ol><li>Open the google cloud console following this <a href="https://console.cloud.google.com/">link</a>. Make sure to create or select a project for your work. Organization -&gt;project -&gt;folders is the folder hierarchy followed in the google cloud platform.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiDPQsZCyBg_T1Jg8z0CcA.png" /></figure><p>2. Open the navigation menu and create a Cloud SQL instance by navigating to database-&gt;SQL-&gt;create instance -&gt;mySQL</p><p>Make sure to select a unique instance ID and root password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLJQ6Zo5O6Ryo6WtELkyrQ.png" /></figure><p>3. Now, let’s create tables within MySQL.</p><p>Once the instance is ready, you can use google cloud shell to connect to the database.</p><p>At the top right, you will notice an icon to activate the cloud shell. Click the cloud shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttBINrGnq7undw-Ns2zajg.png" /></figure><p>Now let’s connect to our newly created database using a cloud shell.</p><pre>gcloud sql connect rentals --user=root --quiet</pre><p>If you are prompted to enable the SQL admin API, enable it following the link in error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shoKQ4NMGiYVR2fZsmzmdw.png" /></figure><p>It might take up to 5 minutes to whitelist your IP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hw5D_V7JKcrk6mg-tARoUA.png" /></figure><p>4. Once you are in the MySQL console, create a database and 3 tables which will store the data for the recommendation.</p><pre>CREATE DATABASE IF NOT EXISTS recommendation_spark;</pre><pre>USE recommendation_spark;</pre><pre>DROP TABLE IF EXISTS Recommendation;</pre><pre>DROP TABLE IF EXISTS Rating;</pre><pre>DROP TABLE IF EXISTS Accommodation;</pre><pre>CREATE TABLE IF NOT EXISTS Accommodation</pre><pre>(</pre><pre>id varchar(255),</pre><pre>title varchar(255),</pre><pre>location varchar(255),</pre><pre>price int,</pre><pre>rooms int,</pre><pre>rating float,</pre><pre>type varchar(255),</pre><pre>PRIMARY KEY (ID)</pre><pre>);</pre><pre>CREATE TABLE IF NOT EXISTS Rating</pre><pre>(</pre><pre>userId varchar(255),</pre><pre>accoId varchar(255),</pre><pre>rating int,</pre><pre>PRIMARY KEY(accoId, userId),</pre><pre>FOREIGN KEY (accoId)</pre><pre>REFERENCES Accommodation(id)</pre><pre>);</pre><pre>CREATE TABLE IF NOT EXISTS Recommendation</pre><pre>(</pre><pre>userId varchar(255),</pre><pre>accoId varchar(255),</pre><pre>prediction float,</pre><pre>PRIMARY KEY(userId, accoId),</pre><pre>FOREIGN KEY (accoId)</pre><pre>REFERENCES Accommodation(id)</pre><pre>);</pre><pre>SHOW DATABASES;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iHlZchv4Vyp_WYq_1DfAg.png" /></figure><p>Right now, the tables will be empty. You will stage the data in cloud SQL and then pull it to the cloud SQL.</p><p>5. Create a new window in the cloud shell and create buckets and pull data into cloud storage buckets.</p><pre>echo “Creating bucket: gs://$DEVSHELL_PROJECT_ID”</pre><pre>gsutil mb gs://$DEVSHELL_PROJECT_ID</pre><pre>echo “Copying data to our storage from public dataset”</pre><pre>gsutil cp gs://cloud-training/bdml/v2.0/data/accommodation.csv gs://$DEVSHELL_PROJECT_ID</pre><pre>gsutil cp gs://cloud-training/bdml/v2.0/data/rating.csv gs://$DEVSHELL_PROJECT_ID</pre><pre>echo “Show the files in our bucket”</pre><pre>gsutil ls gs://$DEVSHELL_PROJECT_ID</pre><pre>echo “View some sample data”</pre><pre>gsutil cat gs://$DEVSHELL_PROJECT_ID/accommodation.csv</pre><p>You can check the content by going to the navigation menu -&gt; storage -&gt; browser -&gt; project ID.</p><p>6. Let’s load the data from the cloud storage bucket to cloud SQL.</p><p>Navigate to SQL-&gt;rentals-&gt;import data</p><p>Specify the bucket, database, and table name and click import.</p><p>Repeat the above steps for rating data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRNDu4Chge1-j4Bq3ipAWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suIy2ppK5VtsFKbg_vOa1g.png" /></figure><p>7. Explore the data using cloud shell and running a few commands</p><pre>SELECT</pre><pre>userId,</pre><pre>COUNT(rating) AS num_ratings</pre><pre>FROM Rating</pre><pre>GROUP BY userId</pre><pre>ORDER BY num_ratings DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gn-W17ynJCdOiKY1O-A99w.png" /></figure><p>8. Let’s create a recommendation engine using dataproc.</p><p>Enable the dataproc API by navigating to the API and services-&gt;dashboard-&gt; search Cloud Dataproc API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*up5lYezn1zRd0ixtVt8JAw.png" /></figure><p>Once done navigate to BigData-&gt; Dataproc-&gt;Cluster-&gt;create cluster</p><p>Make sure to keep the zone the same as your cloud SQL instance.</p><p>Also, note the name, zone, and total worker nodes in your cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fj9G5wq064H10WZKhpd66g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAF2M0rdjAIno3L5CFS52Q.png" /></figure><p>8. Authorize dataproc to connect to the cloud SQL instance</p><p>Use the below script in the cloud shell. Make sure to check the cluster name, zone, and a number of workers.</p><pre>echo “Authorizing Cloud Dataproc to connect with Cloud SQL”</pre><pre>CLUSTER=cluster-a20f</pre><pre>CLOUDSQL=rentals</pre><pre>ZONE=us-central1-f</pre><pre>NWORKERS=2</pre><pre>machines=”$CLUSTER-m”</pre><pre>for w in `seq 0 $(($NWORKERS — 1))`; do</pre><pre>machines=”$machines $CLUSTER-w-$w”</pre><pre>done</pre><pre>echo “Machines to authorize: $machines in $ZONE … finding their IP addresses”</pre><pre>ips=””</pre><pre>for machine in $machines; do</pre><pre>IP_ADDRESS=$(gcloud compute instances describe $machine — zone=$ZONE — format=’value(networkInterfaces.accessConfigs[].natIP)’ | sed “s/\[‘//g” | sed “s/’\]//g” )/32</pre><pre>echo “IP address of $machine is $IP_ADDRESS”</pre><pre>if [ -z $ips ]; then</pre><pre>ips=$IP_ADDRESS</pre><pre>else</pre><pre>ips=”$ips,$IP_ADDRESS”</pre><pre>fi</pre><pre>done</pre><pre>echo “Authorizing [$ips] to access cloudsql=$CLOUDSQL”</pre><pre>gcloud sql instances patch $CLOUDSQL — authorized-networks $ips</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPI8g9LChAfaKUT1fSaCEA.png" /></figure><p>9. Copy the ML model to the datarproc cluster and edit it using cloud shell.</p><pre>gsutil cp gs://cloud-training/bdml/v2.0/model/train_and_apply.py train_and_apply.py</pre><pre>cloudshell edit train_and_apply.py</pre><p>Below is the pyspark code snippet</p><pre>import os</pre><pre>import sys</pre><pre>import pickle</pre><pre>import itertools</pre><pre>from math import sqrt</pre><pre>from operator import add</pre><pre>from os.path import join, isfile, dirname</pre><pre>from pyspark import SparkContext, SparkConf, SQLContext</pre><pre>from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating</pre><pre>from pyspark.sql.types import StructType, StructField, StringType, FloatType</pre><pre># MAKE EDITS HERE</pre><pre>CLOUDSQL_INSTANCE_IP = ‘104.155.188.32’ # ← — CHANGE (database server IP)</pre><pre>CLOUDSQL_DB_NAME = ‘recommendation_spark’ # ←- leave as-is</pre><pre>CLOUDSQL_USER = ‘root’ # ←- leave as-is</pre><pre>CLOUDSQL_PWD = ‘root’ # ← — CHANGE</pre><pre># DO NOT MAKE EDITS BELOW</pre><pre>conf = SparkConf().setAppName(“train_model”)</pre><pre>sc = SparkContext(<em>conf</em>=conf)</pre><pre>sqlContext = SQLContext(sc)</pre><pre>jdbcDriver = ‘com.mysql.jdbc.Driver’</pre><pre>jdbcUrl = ‘jdbc:mysql://%s:3306/%s?user=%s&amp;password=%s’ % (CLOUDSQL_INSTANCE_IP, CLOUDSQL_DB_NAME, CLOUDSQL_USER, CLOUDSQL_PWD)</pre><pre># checkpointing helps prevent stack overflow errors</pre><pre>sc.setCheckpointDir(‘checkpoint/’)</pre><pre># Read the ratings and accommodations data from Cloud SQL</pre><pre>dfRates = sqlContext.read.format(‘jdbc’).options(<em>driver</em>=jdbcDriver, <em>url</em>=jdbcUrl, <em>dbtable</em>=’Rating’, <em>useSSL</em>=’false’).load()</pre><pre>dfAccos = sqlContext.read.format(‘jdbc’).options(<em>driver</em>=jdbcDriver, <em>url</em>=jdbcUrl, <em>dbtable</em>=’Accommodation’, <em>useSSL</em>=’false’).load()</pre><pre>print(“read …”)</pre><pre># train the model</pre><pre>model = ALS.train(dfRates.rdd, 20, 20) # you could tune these numbers, but these are reasonable choices</pre><pre>print(“trained …”)</pre><pre># use this model to predict what the user would rate accommodations that she has not rated</pre><pre>allPredictions = None</pre><pre>for USER_ID in range(0, 100):</pre><pre>dfUserRatings = dfRates.filter(dfRates.userId == USER_ID).rdd.map(<em>lambda</em> <em>r</em>: r.accoId).collect()</pre><pre>rddPotential = dfAccos.rdd.filter(<em>lambda</em> <em>x</em>: x[0] not in dfUserRatings)</pre><pre>pairsPotential = rddPotential.map(<em>lambda</em> <em>x</em>: (USER_ID, x[0]))</pre><pre>predictions = model.predictAll(pairsPotential).map(<em>lambda</em> <em>p</em>: (<em>str</em>(p[0]), <em>str</em>(p[1]), <em>float</em>(p[2])))</pre><pre>predictions = predictions.takeOrdered(5, <em>key</em>=<em>lambda</em> <em>x</em>: -x[2]) # top 5</pre><pre>print(“predicted for user={0}”.format(USER_ID))</pre><pre>if (allPredictions == None):</pre><pre>allPredictions = predictions</pre><pre>else:</pre><pre>allPredictions.extend(predictions)</pre><pre># write them</pre><pre>schema = StructType([StructField(“userId”, StringType(), True), StructField(“accoId”, StringType(), True), StructField(“prediction”, FloatType(), True)])</pre><pre>dfToSave = sqlContext.createDataFrame(allPredictions, schema)</pre><pre>dfToSave.write.jdbc(<em>url</em>=jdbcUrl, <em>table</em>=’Recommendation’, <em>mode</em>=’overwrite’)</pre><p>When prompted, click open in a new window.</p><p>Change the cloud instance IP and root password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yy9_MD1ilUY_-FE8IlG-Xg.png" /></figure><p>Now save and copy it to the bucket. We will use dataproc to pick the code from the storage location.</p><pre>gsutil cp train_and_apply.py gs://$DEVSHELL_PROJECT_ID</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cz1HswWPdUJcaSZ1eTre9A.png" /></figure><p>10. Time to submit ML job to the dataproc cluster</p><p>Navigate to dataproc-&gt;job-&gt; submit job</p><p>Specify job id, cluster, job type as pyspark, main python file bucket path, and click submit the job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2g-jjwUdrXx86uo48FhvXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewYoYVdF2rnL6jA6lB3I1g.png" /></figure><p>11. Query the recommendation table</p><p>Once the job completes successfully, you can query the MySQL table recommendation for a specific recommendation based on user_id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuXkRwgSNQkxGPvgXQL4bA.png" /></figure><p>Note: Make sure to delete resources and shut down services to avoid any surprises in the billing from google cloud.</p><p>Do let me know your thoughts. You can follow me for tutorials on AI/machine learning, data analytics, and BI. You can connect with me on <a href="https://www.linkedin.com/in/anurag-bisht-39935a59/">LinkedIn</a>.</p><p><strong>References</strong></p><p>_<a href="http://yifanhu.net/PUB/cf.pdf">http://yifanhu.net/PUB/cf.pdf</a></p><p>_<a href="https://spark.apache.org/docs/latest/ml-collaborative-filtering.html">https://spark.apache.org/docs/latest/ml-collaborative-filtering.html</a></p><p>_<a href="http://stanford.edu/~rezab/classes/cme323/S15/notes/lec14.pdf">http://stanford.edu/~rezab/classes/cme323/S15/notes/lec14.pdf</a></p><p>_<a href="https://developers.google.com/machine-learning/recommendation/collaborative/matrix">https://developers.google.com/machine-learning/recommendation/collaborative/matrix</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf559abafe6a" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/building-a-product-recommendation-engine-on-google-clouds-platform-cf559abafe6a">Building a Product Recommendation Engine on Google Cloud’s Platform</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data-structures and Algorithms using Python: Programming Series 101–2]]></title>
            <link>https://anuragbisht12.medium.com/data-structures-and-algorithms-using-python-programming-series-101-2-48eb3122a83e?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/48eb3122a83e</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Sun, 13 Dec 2020 16:54:27 GMT</pubDate>
            <atom:updated>2020-12-13T16:54:27.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*w4eDgpTUcexPBmZLRlym9A.png" /></figure><p>Hope you guys are having fun learning python and getting acquainted with data-structures using python. Soon we will start designing algorithms using python but let’s build our fundamentals first.</p><p>In the last session I discussed why it is important to understand data structures and algorithms, what are the basic data-structures and how can we use those basic data-structures to build complex ones(eg. stack). We also discussed the time and space complexity. If you haven’t checked that post and are new to data-structures, feel free to check that post <a href="https://medium.com/towards-artificial-intelligence/data-structures-and-algorithms-using-python-programming-series-101-dbd41d48ab4d">here</a>.</p><p>Today we will develop data-structures that you already have implemented in real-life scenarios. We will also discuss their functions and readymade python packages for them as well as their time and space complexity.</p><p><strong>Queue:</strong></p><p>This is a non-primitive data-structure where data is stored in sequential order on a first come first serve basis. As the data storage follows sequential order in FIFO(first in first out order), it finds application in algorithms where data is accessed in this fashion.</p><p>This data-structure has the following functions:</p><ol><li>enqueue(): add elements to the queue.</li><li>dequeue(): remove the elements from the queue.</li><li>size(): get the number of elements in the queue.</li><li>is_empty(): check if the queue is empty or not.</li><li>front(): peek through the first element of the queue.</li><li>back():peek through the last element of the queue.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee0dd1c81c8e75187ce30367f9fadc80/href">https://medium.com/media/ee0dd1c81c8e75187ce30367f9fadc80/href</a></iframe><p>Below are the time and space complexity for queue data-structure.</p><p><strong>Time and Space Complexity:</strong></p><p>Insertion: O(1)</p><p>Deletion/ Retrieval: O(1)</p><p>Space Complexity: O(n)</p><p><strong>Pros and Cons:</strong></p><p>The FIFO pattern of storage of elements is useful in certain applications — Eg. designing customer care support application, input-output based interrupts(typing from the keyboard) that needs to be registered by computer, task schedulers, etc.</p><p>Cons is that the data storage and access cannot be random, hence not suitable for the applications where memory management cannot be continuous.</p><p>You can follow me for tutorials on AI/machine learning, programming, data analytics, and BI. For any queries or doubts, I am available on <a href="https://www.linkedin.com/in/anurag-bisht-39935a59/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48eb3122a83e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data-structures and Algorithms using Python: Programming Series 101]]></title>
            <link>https://pub.towardsai.net/data-structures-and-algorithms-using-python-programming-series-101-dbd41d48ab4d?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd41d48ab4d</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Mon, 07 Dec 2020 13:03:03 GMT</pubDate>
            <atom:updated>2020-12-07T13:03:03.355Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/programming">Programming</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5__HCmQnUOJ6tms1QiQYKA.png" /><figcaption>Image by the author.</figcaption></figure><p>For folks who have started learning to program or willing to learn and pursue their career in fields that require programming knowledge, this post will help you guys understand the fundamentals of data structures and algorithms.<br>Data-structures and algorithms are one of the most fundamental aspects of programming taught in any computer science lecture. You can learn any programming language, but to be a good programmer, you have to develop a grip over data-structures and algorithms. So what is a data structure, what is an algorithm, why should we learn it?</p><p>A data structure, as the name suggests, is the building block of any programming /coding you do to design any approach to solve any problem using a programming language. That approach is also known as an algorithm in computer science terminology.</p><p>For e.g., If you are given a list of students in sorted order and asked to find whether a given student name is present in that class using programming within the least amount of time and computational resources.<br>To solve this programming problem, you will start thinking about the approach, which is referred to as an algorithm. Once you have an approach to solve the problem(whether or not in the least amount of time and computational resources), you will also start thinking about how to store the input in an optimal way, which is referred to as data structure.</p><p>To our problem, we can use a searching algorithm (say binary search as the input is sorted) and any suitable data structure like a list in python.<br>Different programming languages have different ways to implement data structures for use.</p><p>The broad categories of data structures are as follows:</p><h3>Types of data-structure:</h3><ol><li><strong>Primitive :</strong></li></ol><p>These are the most fundamental data-structures present at the machine level.</p><p>E.g., integer, float, character, pointer, etc.</p><p><strong>2. Non-primitive:</strong></p><p>These are data-structures that are derived from primitive data-structures.</p><p><strong>2.1 Array:</strong></p><p>An array consists of a collection of homogenous elements in the continuous allocation of memory.</p><p><strong>2.2. Files:</strong></p><p>This is a collection of records primarily used to manage a large number of records.</p><p><strong>2.3. Lists:</strong></p><p>This data-structure consists of dynamic memory allocation of primitive data-structure.</p><p><strong>2.3.1. Linear lists:</strong></p><p>The elements are stored in sequential order.</p><p><strong>Stack: </strong>This data-structure stores and retrieves the elements in the last in first out( LIFO) format.</p><p><strong>Queue: </strong>This data-structure stored and retrieves the elements in the first in, first out format (FIFO).</p><p><strong>2.3.2. Non-linear lists:</strong></p><p>The elements are not stored in sequential order.</p><p><strong>Trees</strong>: Data-structure is stored in tree-based format with nodes and vertices connected in tree-based structure. It is a special case of a graph.</p><p><strong>Graph</strong>: Data-structure is stored with nodes and vertices where nodes with data are connected to vertices.</p><h3><strong>Stack:</strong></h3><p>To design a stack data-structure, we will use a fundamental python data-structure <strong>list</strong>.</p><p>The different functions in the stack are:</p><ol><li><strong>push():</strong> To store elements in the stack.</li><li><strong>pop(): </strong>To retrieve elements from the stack.</li><li><strong>is_empty(): </strong>To check if the stack is empty.</li><li><strong>size(): </strong>To get the size of the stack.</li><li><strong>top (): </strong>To return the top element of the stack.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be2125f21e7682acb4add0e023463970/href">https://medium.com/media/be2125f21e7682acb4add0e023463970/href</a></iframe><h3><strong>Time and Space Complexity:</strong></h3><p>The time and space complexity of the algorithm is an important aspect to be calculated while coding any algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*_tU871NT3uNzNgCZQO6kpg.png" /><figcaption>Image courtesy: Google</figcaption></figure><p>Big Oh notation (denoted by O): It measures the longest time/case taken by the algorithm to complete execution. While calculating the time/ space complexity of the algorithm, we look at the worst-case possible or the worst time/case required by the algorithm to complete any execution.</p><p>To learn more, you can visit this <a href="https://www.tutorialspoint.com/data_structures_algorithms/asymptotic_analysis.htm">link</a>.</p><p>While analyzing any algorithm, we try to calculate both time and space complexity in the worst possible scenarios.</p><p><strong>Insertion</strong>: O(1)</p><p><strong>Deletion/ Retrieval</strong>: O(1)</p><p><strong>Search</strong>: O(n)</p><p><strong>Space Complexity</strong>: O(n)</p><h3><strong>Pros and Cons:</strong></h3><p>The LIFO pattern of storage of elements is useful in certain applications—Eg. Calculators where operators take certain precedence.</p><p>Cons is that the data storage and access cannot be random, hence not suitable for the applications where memory management cannot be continuous.</p><p>I hope you enjoyed this post. Let me know your thoughts if you have any queries or suggestions, would love to hear more from you.</p><p>You can follow me for tutorials on AI/machine learning, programming, data analytics, and BI. You can connect with me on <a href="https://www.linkedin.com/in/anurag-bisht-39935a59/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd41d48ab4d" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/data-structures-and-algorithms-using-python-programming-series-101-dbd41d48ab4d">Data-structures and Algorithms using Python: Programming Series 101</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big QueryML:  Machine Learning for Data Scientists using SQL on Google Cloud Platform Quick Start…]]></title>
            <link>https://pub.towardsai.net/big-queryml-machine-learning-for-data-scientists-using-sql-on-google-cloud-platform-quick-start-d9eec7b8641?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9eec7b8641</guid>
            <category><![CDATA[google-big-query]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 13:02:55 GMT</pubDate>
            <atom:updated>2020-12-01T13:02:55.361Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/cloud-computing">Cloud Computing</a></h4><h3>Big QueryML: Machine Learning for Data Scientists using SQL on Google Cloud Platform Quick Start Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afZUCqsL-nk4Nshxdbps4w.png" /><figcaption>Source: <a href="https://blog.google/products/google-cloud/cloud-covered-what-was-new-with-google-cloud-in-october-2019/">Google</a></figcaption></figure><p>I hope you are doing well. It’s been a late post as I struggled through my health. I have managed to upgrade my skills by learning new technologies and platforms and would be eager to share my knowledge with you all. Without wasting any more time, let’s learn something new today.</p><p>Cloud computing has been around for a while, but the pace of adoption has improved exponentially nowadays thanks to the pandemic and IT companies realizing the benefits and trade-offs. There are 3 major cloud services providers: AWS, Microsoft, and GCP.</p><p>Google cloud computing services had been around for a while, but the rate of adoption had been slow due to n number of reasons, say a limited number of services offered. Although Google had pioneered and was the first to innovate something on the cloud, e.g., Big table for big data, Kubernetes for serverless orchestration, and so on, it has always been slow in marketing itself(GCP services).</p><p>Now that said, if you are new to cloud computing and confused about which platform to learn, you might not realize the differences, but after using all the cloud services (AWS, GCP, Azure), I have realized the pros and cons of each platform. If you ask me, I would say AWS has an excellent go-to-marketing strategy to cloud services and know-how to be one step ahead while reaching out to customers, and it’s easy to use. Google Cloud Platform is an equally mature ecosystem and does provide services that are quick to deploy and create than other platforms, although the platform will suit the geeky crowd more when compared to AWS, which has better guidelines and documentation resources at each step.</p><p>Now someone with a background in data will recognize the importance of data-warehouse for improving business decisions. GCP offers a compelling data-warehouse service, BigQuery. BigQuery allows storage and querying of petabytes of data in seconds for analysis.</p><p>As a data scientist, you can now directly create and run your models to answer business questions using SQL on BigQuery. Today’s tutorial is all about that, so let’s get started.</p><p><strong>Prerequisites:</strong></p><p>You need access to BigQuery services. You can try it for free. Check out this <a href="https://cloud.google.com/bigquery">link.</a></p><p>You also need access to the dataset which we will create. Please note that big-query charges for the amount of data processed when you run an SQL query, so be cautious about what you query.</p><p>You also need some familiarity with SQL to understand what data is queried.</p><p><strong>Steps:</strong></p><ol><li>Open the google platform console and navigate to BigQuery service: <a href="https://console.cloud.google.com/bigquery">Link</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f32jOO9hXb0_aXLiP118Ow.png" /><figcaption>screenshot 1</figcaption></figure><p>2. Add the data-to-insights dataset by clicking this <a href="https://console.cloud.google.com/bigquery?p=data-to-insights&amp;d=ecommerce&amp;t=web_analytics&amp;page=table">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8OdTnZ42hBAp9ZBTMc_B5A.png" /><figcaption>screenshot 2</figcaption></figure><p><strong>3. Let’s do some data exploration:</strong></p><p>Let’s try to find out of the total visitors who visited our website, what % made a purchase?</p><p>Paste the following SQL query in query editor:</p><pre>WITH visitors AS</pre><pre>( SELECT</pre><pre>COUNT(DISTINCT fullVisitorId) AS total_visitors</pre><pre>FROM `data-to-insights.ecommerce.web_analytics`</pre><pre>),</pre><pre>purchasers AS(</pre><pre>SELECT</pre><pre>COUNT(DISTINCT fullVisitorId) AS total_purchasers</pre><pre>FROM `data-to-insights.ecommerce.web_analytics`</pre><pre>WHERE totals.transactions IS NOT NULL</pre><pre>)</pre><pre>SELECT</pre><pre>total_visitors,</pre><pre>total_purchasers,</pre><pre>total_purchasers / total_visitors AS conversion_rate</pre><pre>FROM visitors, purchasers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQuHLs7fXIY3Vxama0mC_w.png" /><figcaption>screenshot 3</figcaption></figure><p>Let’s try to figure out the top 5 selling products in the market using e-commerce data.</p><pre>SELECT</pre><pre>p.v2ProductName,</pre><pre>p.v2ProductCategory,</pre><pre>SUM(p.productQuantity) AS units_sold,</pre><pre>ROUND(SUM(p.localProductRevenue/1000000),2) AS revenue</pre><pre>FROM `data-to-insights.ecommerce.web_analytics`,</pre><pre>UNNEST(hits) AS h,</pre><pre>UNNEST(h.product) AS p</pre><pre>GROUP BY 1, 2</pre><pre>ORDER BY revenue DESC</pre><pre>LIMIT 5;</pre><p>We will not discuss each syntax of SQL, but if you know SQL, then you might find it pretty easy to understand. UNNEST keyword flattens out the array to separate records in the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZxYkJE-_MpQV_srcIy0CA.png" /><figcaption>screenshot 4</figcaption></figure><p>Can we answer how many visitors bought products on the next visits to the website?</p><pre>WITH all_visitor_stats AS (</pre><pre>SELECT</pre><pre>fullvisitorid, </pre><pre>IF(COUNTIF(totals.transactions &gt; 0 AND totals.newVisits IS NULL) &gt; 0, 1, 0) AS will_buy_on_return_visit</pre><pre>FROM `data-to-insights.ecommerce.web_analytics`</pre><pre>GROUP BY fullvisitorid</pre><pre>)</pre><pre>SELECT</pre><pre>COUNT(DISTINCT fullvisitorid) AS total_visitors,</pre><pre>will_buy_on_return_visit</pre><pre>FROM all_visitor_stats</pre><pre>GROUP BY will_buy_on_return_visitcontent</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGLegl6Q09UR24ukZ5m6Og.png" /><figcaption>screenshot 5</figcaption></figure><p>Only a small proportion of visitors visit again to buy the products, making sense when we relate to real-world scenarios: you might visit a website to browse or compare products but may not buy them.</p><p><strong>4. Let’s make a feature selection to answer a machine learning problem:</strong></p><p>Predict whether or not a user is likely to purchase in the future.</p><p>Let’s create a baseline model using a few features in big-query. For this domain, expertise is required or prior work with google analytics e-commerce data. Suppose we pick 2 features, for now, bounces and time_on_site, which are correlated to buying decisions. Now you can add more features, but that’s beyond the scope of our fundamental learnings. For our case, we need a logistic regression model.</p><p>We will create a dataset of ours where we will save the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPgAEC8pk9kA_ceeGM5JDg.png" /><figcaption>screenshot 6</figcaption></figure><p>After we have created the dataset, we will create a logistic regression model.</p><pre>CREATE OR REPLACE MODEL `mydataset.classification_model`<br>OPTIONS<br>(<br>model_type=’logistic_reg’,<br>labels = [‘will_buy_on_return_visit’]<br>)<br>AS</pre><pre>#standardSQL<br>SELECT<br> * EXCEPT(fullVisitorId)<br>FROM</pre><pre># features<br> (SELECT<br> fullVisitorId,<br> IFNULL(totals.bounces, 0) AS bounces,<br> IFNULL(totals.timeOnSite, 0) AS time_on_site<br> FROM<br> `data-to-insights.ecommerce.web_analytics`<br> WHERE<br> totals.newVisits = 1<br> AND date BETWEEN ‘20160801’ AND ‘20170430’) # train on first 9 months<br> JOIN<br> (SELECT<br> fullvisitorid,<br> IF(COUNTIF(totals.transactions &gt; 0 AND totals.newVisits IS NULL) &gt; 0, 1, 0) AS will_buy_on_return_visit<br> FROM<br> `data-to-insights.ecommerce.web_analytics`<br> GROUP BY fullvisitorid)<br> USING (fullVisitorId);</pre><p>Once the model is created, you can explore the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iaqiwc_5o0GJYxm-pIJUGQ.png" /><figcaption>screenshot 7</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmbBUBXAp7cMbYJRMVkgwA.png" /><figcaption>screenshot 8</figcaption></figure><p><strong>5. Model Evaluation:</strong></p><p>You can evaluate the model using the following query and checking the roc_auc.</p><pre>SELECT<br> roc_auc,<br> CASE<br> WHEN roc_auc &gt; .9 THEN ‘good’<br> WHEN roc_auc &gt; .8 THEN ‘fair’<br> WHEN roc_auc &gt; .7 THEN ‘not great’<br> ELSE ‘poor’ END AS model_quality<br>FROM<br> ML.EVALUATE(MODEL mydataset.classification_model, (</pre><pre>SELECT<br> * EXCEPT(fullVisitorId)<br>FROM</pre><pre># features<br> (SELECT<br> fullVisitorId,<br> IFNULL(totals.bounces, 0) AS bounces,<br> IFNULL(totals.timeOnSite, 0) AS time_on_site<br> FROM<br> `data-to-insights.ecommerce.web_analytics`<br> WHERE<br> totals.newVisits = 1<br> AND date BETWEEN ‘20170501’ AND ‘20170630’) # eval on 2 months<br> JOIN<br> (SELECT<br> fullvisitorid,<br> IF(COUNTIF(totals.transactions &gt; 0 AND totals.newVisits IS NULL) &gt; 0, 1, 0) AS will_buy_on_return_visit<br> FROM<br> `data-to-insights.ecommerce.web_analytics`<br> GROUP BY fullvisitorid)<br> USING (fullVisitorId)));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0JwURYady5T4JDIl-JipQ.png" /><figcaption>screenshot 9</figcaption></figure><p><strong>6. Feature Engineering:</strong></p><p>Now we can try to improve the model by adding some more features.</p><pre>CREATE OR REPLACE MODEL `mydataset.classification_model_2`<br>OPTIONS<br> (model_type=’logistic_reg’, labels = [‘will_buy_on_return_visit’]) AS</pre><pre>WITH all_visitor_stats AS (<br>SELECT<br> fullvisitorid,<br> IF(COUNTIF(totals.transactions &gt; 0 AND totals.newVisits IS NULL) &gt; 0, 1, 0) AS will_buy_on_return_visit<br> FROM `data-to-insights.ecommerce.web_analytics`<br> GROUP BY fullvisitorid<br>)</pre><pre># add in new features<br>SELECT * EXCEPT(unique_session_id) FROM (</pre><pre>SELECT<br> CONCAT(fullvisitorid, CAST(visitId AS STRING)) AS unique_session_id,</pre><pre># labels<br> will_buy_on_return_visit,</pre><pre>MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress,</pre><pre># behavior on the site<br> IFNULL(totals.bounces, 0) AS bounces,<br> IFNULL(totals.timeOnSite, 0) AS time_on_site,<br> totals.pageviews,</pre><pre># where the visitor came from<br> trafficSource.source,<br> trafficSource.medium,<br> channelGrouping,</pre><pre># mobile or desktop<br> device.deviceCategory,</pre><pre># geographic<br> IFNULL(geoNetwork.country, “”) AS country</pre><pre>FROM `data-to-insights.ecommerce.web_analytics`,<br> UNNEST(hits) AS h</pre><pre>JOIN all_visitor_stats USING(fullvisitorid)</pre><pre>WHERE 1=1<br> # only predict for new visits<br> AND totals.newVisits = 1<br> AND date BETWEEN ‘20160801’ AND ‘20170430’ # train 9 months</pre><pre>GROUP BY<br> unique_session_id,<br> will_buy_on_return_visit,<br> bounces,<br> time_on_site,<br> totals.pageviews,<br> trafficSource.source,<br> trafficSource.medium,<br> channelGrouping,<br> device.deviceCategory,<br> country<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*261X4u2El1aGjt3p7nQyCQ.png" /><figcaption>screenshot 10</figcaption></figure><p>Let’s evaluate the model.</p><pre>SELECT<br> roc_auc,<br> CASE<br> WHEN roc_auc &gt; .9 THEN ‘good’<br> WHEN roc_auc &gt; .8 THEN ‘fair’<br> WHEN roc_auc &gt; .7 THEN ‘not great’<br> ELSE ‘poor’ END AS model_quality<br>FROM<br> ML.EVALUATE(MODEL mydataset.classification_model_2, (</pre><pre>WITH all_visitor_stats AS (<br>SELECT<br> fullvisitorid,<br> IF(COUNTIF(totals.transactions &gt; 0 AND totals.newVisits IS NULL) &gt; 0, 1, 0) AS will_buy_on_return_visit<br> FROM `data-to-insights.ecommerce.web_analytics`<br> GROUP BY fullvisitorid<br>)</pre><pre># add in new features<br>SELECT * EXCEPT(unique_session_id) FROM (</pre><pre>SELECT<br> CONCAT(fullvisitorid, CAST(visitId AS STRING)) AS unique_session_id,</pre><pre># labels<br> will_buy_on_return_visit,</pre><pre>MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress,</pre><pre># behavior on the site<br> IFNULL(totals.bounces, 0) AS bounces,<br> IFNULL(totals.timeOnSite, 0) AS time_on_site,<br> totals.pageviews,</pre><pre># where the visitor came from<br> trafficSource.source,<br> trafficSource.medium,<br> channelGrouping,</pre><pre># mobile or desktop<br> device.deviceCategory,</pre><pre># geographic<br> IFNULL(geoNetwork.country, “”) AS country</pre><pre>FROM `data-to-insights.ecommerce.web_analytics`,<br> UNNEST(hits) AS h</pre><pre>JOIN all_visitor_stats USING(fullvisitorid)</pre><pre>WHERE 1=1<br> # only predict for new visits<br> AND totals.newVisits = 1<br> AND date BETWEEN ‘20170501’ AND ‘20170630’ # eval 2 months</pre><pre>GROUP BY<br> unique_session_id,<br> will_buy_on_return_visit,<br> bounces,<br> time_on_site,<br> totals.pageviews,<br> trafficSource.source,<br> trafficSource.medium,<br> channelGrouping,<br> device.deviceCategory,<br> country<br>)<br>));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDIRanxviYj4Ra0QmACB9A.png" /><figcaption>screenshot 11</figcaption></figure><p>The model has improved a lot.</p><p><strong>7. Prediction:</strong></p><p>Now let’s predict all the new visitors who will become customers.</p><pre>SELECT</pre><pre>*</pre><pre>FROM</pre><pre>ml.PREDICT(MODEL `ecommerce.classification_model_2`,</pre><pre>(</pre><pre>WITH all_visitor_stats AS (</pre><pre>SELECT</pre><pre>fullvisitorid,</pre><pre>IF(COUNTIF(totals.transactions &gt; 0 AND totals.newVisits IS NULL) &gt; 0, 1, 0) AS will_buy_on_return_visit</pre><pre>FROM `data-to-insights.ecommerce.web_analytics`</pre><pre>GROUP BY fullvisitorid</pre><pre>)</pre><pre>SELECT</pre><pre>CONCAT(fullvisitorid, ‘-’,CAST(visitId AS STRING)) AS unique_session_id,</pre><pre><em># labels</em></pre><pre>will_buy_on_return_visit,</pre><pre>MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress,</pre><pre><em># behavior on the site</em></pre><pre>IFNULL(totals.bounces, 0) AS bounces,</pre><pre>IFNULL(totals.timeOnSite, 0) AS time_on_site,</pre><pre>totals.pageviews,</pre><pre><em># where the visitor came from</em></pre><pre>trafficSource.source,</pre><pre>trafficSource.medium,</pre><pre>channelGrouping,</pre><pre><em># mobile or desktop</em></pre><pre>device.deviceCategory,</pre><pre><em># geographic</em></pre><pre>IFNULL(geoNetwork.country, “”) AS country</pre><pre>FROM `data-to-insights.ecommerce.web_analytics`,</pre><pre>UNNEST(hits) AS h</pre><pre>JOIN all_visitor_stats USING(fullvisitorid)</pre><pre>WHERE</pre><pre><em># only predict for new visits</em></pre><pre>totals.newVisits = 1</pre><pre>AND date BETWEEN ‘20170701’ AND ‘20170801’ <em># test 1 month</em></pre><pre>GROUP BY</pre><pre>unique_session_id,</pre><pre>will_buy_on_return_visit,</pre><pre>bounces,</pre><pre>time_on_site,</pre><pre>totals.pageviews,</pre><pre>trafficSource.source,</pre><pre>trafficSource.medium,</pre><pre>channelGrouping,</pre><pre>device.deviceCategory,</pre><pre>country</pre><pre>)</pre><pre>)</pre><pre>ORDER BY</pre><pre>predicted_will_buy_on_return_visit DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gqVXfpdARzxxA9-fiOwDQ.png" /><figcaption>screenshot 12</figcaption></figure><p>Isn’t it easy and fun?</p><p>I hope you enjoyed this post. Let me know your thoughts if you have any queries or suggestions, would love to hear more from you. Stay tuned for future posts.</p><p>You can follow me for tutorials on AI/machine learning, data analytics, and BI. You can connect with me on <a href="https://www.linkedin.com/in/anurag-bisht-39935a59/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9eec7b8641" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/big-queryml-machine-learning-for-data-scientists-using-sql-on-google-cloud-platform-quick-start-d9eec7b8641">Big QueryML:  Machine Learning for Data Scientists using SQL on Google Cloud Platform Quick Start…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an End to End Recommendation Engine using Matrix Factorization with Cloud Deployment using…]]></title>
            <link>https://pub.towardsai.net/building-an-end-to-end-recommendation-engine-using-matrix-factorization-with-cloud-deployment-using-f878d43c1005?source=rss-97bc9eb0b784------2</link>
            <guid isPermaLink="false">https://medium.com/p/f878d43c1005</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Anurag Bisht]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 00:02:50 GMT</pubDate>
            <atom:updated>2020-10-12T00:02:50.471Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/cloud-computing">Cloud Computing</a>, <a href="https://towardsai.net/p/category/machine-learning">Machine Learning</a></h4><h3>Building an End to End Recommendation Engine using Matrix Factorization with Cloud Deployment using Amazon SageMaker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*SkpUQEZzj3NDYfiKhXRhbQ.png" /><figcaption>Image Courtesy: Google Cloud</figcaption></figure><p>How many times have you visited any shopping website and purchased anything, have you noticed that the website personalizes as per your purchase history?</p><p>You all must have watched YouTube videos. Does the app start suggesting videos in a certain fashion as per the type of content you watch?</p><p>What about watching a movie or browsing the internet, does the ads look familiar?</p><p>Recommendation engines are one of the most important applications of machine learning, they have changed how businesses interact with their customers. It helps users find related content, explore new items, and improve decision making, but it also helps content producers to learn user behavior and increase user engagement.</p><p>This not only helps businesses target their customers with the right kind of products, but it also helps users personalize their user experience based on their interests and consumption.</p><p>Types of Recommendation Systems:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibnaqByrkTCY_dRPc6OIbg.png" /><figcaption>Image courtesy: Google Cloud</figcaption></figure><ol><li><strong>Content-based filtering:</strong></li></ol><p>Content-based filtering uses attributes of the items to recommend new items to a user. The recommendation is purely based on the content consumption history of the user. For eg. If a user watches 2 movies and rates a sci/fi movie high and a horror movie as low, the content-based recommendation engine will start recommending more sci/fi movies to that user.</p><p>Below is a user-item interaction matrix where the recommendation for the second user will only be based on the items rated by that user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*UeutJNm6xo0JRrhng6VYNQ.png" /><figcaption>Image courtesy: Google</figcaption></figure><p><strong>Cons: Cold start</strong>- Suppose a user has not rated enough movies, the recommendation engine would not take the unrated movies into account as it considers only the user history.</p><p><strong>Used when</strong>: Enough user history is available.</p><p><strong>2. Collaborative filtering:</strong></p><p>It uses similarities between users and items simultaneously to determine what to recommend. This considers the whole user-item interaction matrix to recommend items to a user. For eg if 2 users show similar purchasing behavior of items, there is a high chance that both will buy similar types of items.</p><p>Below is an example where the whole matrix would be considered to recommend items to the second user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*_yjXFdhwzrnSlMrD35MaGA.png" /><figcaption>Image courtesy: Google Cloud</figcaption></figure><p><strong>Advantage:</strong> It overcomes the cold start problem as long as the similarity is detected between users.</p><p><strong>Used when:</strong> There are high chances that the user interaction matrix will be sparse (the user may or may not rate most of the items).</p><p><strong>Cons: </strong>In rare cases where users rarely interact with any item(eg. purchasing any super-luxury item), collaborative filtering might not help much.</p><p><strong>3. Knowledge-based filtering:</strong></p><p>In this explicit knowledge about the user is used to create a recommendation. For eg. asking some questions in the beginning in the form of a quiz or form.</p><p><strong>Advantages:</strong> It overcomes the above problems.</p><p><strong>Hybrid-based filtering: </strong>In a real-world scenario, a combination of all three techniques is used to build a recommendation engine. Hence it’s called hybrid-based filtering.</p><p>Today we will cover collaborative filtering for building our recommendation engine. We can follow 2 approaches to build our recommendation engine:</p><ol><li><strong>Matrix Factorization:</strong></li></ol><p>The idea is to factorize the user-interaction matrix into user-factors and item-factors. Using the given user id, the product of both the matrix will result in a prediction rating. Using these top k rating users will get the recommendations of k items. In this blog, we will build our recommendation using matrix factorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtjTph3usvRWL17boqZJng.png" /><figcaption>Source: Google Cloud</figcaption></figure><p>The model can be represented mathematically using this equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*fa1PhMrcLogzV5P1mfG2Jw.png" /><figcaption>Source: AWS</figcaption></figure><p>The three terms in this equation correspond respectively to the three components of the model:</p><ul><li>The w0 term represents the global bias.</li><li>The wi linear terms model the strength of the ith variable.</li><li>The &lt;vi,vj&gt; factorization terms model the pairwise interaction between the ith and jth variable.</li></ul><p>The model is trained to be reducing the loss metric.</p><p>For <strong>classification </strong>the log loss function has the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*Z_KXItpBomHQELIH8s9N5g.png" /><figcaption>Source: AWS</figcaption></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*hG_CElZ5TTHx01P8Ved-7g.png" /><figcaption>Source: AWS</figcaption></figure><p>ŷn: model prediction</p><p>yn: target value</p><p>For the <strong>regression </strong>task, the square loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*8KjmtKKEc4seayzBLpchow.png" /><figcaption>Source: AWS</figcaption></figure><p>You can read more about factorization machines using this <a href="https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf">whitepaper</a>.</p><p><strong>2. Neural Collaborative Filtering (NCF):</strong></p><p>Before we jump into what neural collaborative filtering is we should understand 2 terms:</p><p><strong>Explicit feedback</strong>: It is explicitly provided to the system by the user, for example like or dislike or rating to a video. This data may or may not be present based on user interaction.</p><p><strong>Implicit feedback</strong>: This data is collected implicitly through the user’s usage pattern, eg watch time, click, views of a video. It is more readily available.</p><p>NCF goes one step beyond the traditional matrix factorization technique by using implicit feedback from the user-item interaction. For this NCF utilizes a multi-layer perceptron to introduce non-linearity in the solution.</p><p><strong>Prerequisites:</strong></p><p>For building our model, we need an AWS account and access to AWS SageMaker services. The dataset will be an opensource dataset. We will use AWS services like S3 to store the model artifacts and use AWS sagemaker hosting services to deploy our model end to end.</p><p><strong>Note</strong>: Although you might be using AWS free tier services, AWS Sagemaker service may incur you charges if not under free trial to use Sagemaker services. So keep a watch on how long you use SageMaker services to avoid any surprises related to billing.</p><p>We will start with a bucket creation to store the model artifacts. For this, we will use the Amazon S3 service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgtOmbSs4B1RhFiVwQDAzg.png" /><figcaption>Screenshot1</figcaption></figure><p>Make sure you keep block all public access checked.</p><p>Once the bucket is created, go to Amazon SageMaker service to create a notebook instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ljw5XfSeKvXYNOcNqjQY4g.png" /><figcaption>Screenshot2</figcaption></figure><p>Once the instance is ready you can open jupyterlab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUitricnSD5rU5AKeeNCDA.png" /><figcaption>Screenshot3</figcaption></figure><ol><li><strong>Download the dataset from the public repository using the following commands:</strong></li></ol><pre>!wget <a href="http://files.grouplens.org/datasets/movielens/ml-100k.zip">http://files.grouplens.org/datasets/movielens/ml-100k.zip</a><br>!unzip -o ml-100k.zip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ms8DnmtrrTjfUOIH5cmMwg.png" /><figcaption>Screenshot4</figcaption></figure><p><strong>2. Inspect the dataset:</strong></p><p>The next task is to inspect the downloaded dataset.</p><pre>%cd ml-100k<br>!shuf ua.base -o ua.base.shuffled<br>!head -10 ua.base.shuffled</pre><pre>!head -10 ua.test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*mlpWpBVq8n_gbSAoD6z5YQ.png" /><figcaption>Screenshot5</figcaption></figure><p><strong>3. Build training and testing dataset:</strong></p><p>In this step, we will import necessary libraries and create a training and testing datasets.</p><pre>import sagemaker<br>import sagemaker.amazon.common as smac<br>from sagemaker import get_execution_role<br>from sagemaker.predictor import json_deserializer</pre><pre>import boto3, csv, io, json<br>import numpy as np<br>from scipy.sparse import lil_matrix</pre><pre>nbUsers=943<br>nbMovies=1682<br>nbFeatures=nbUsers+nbMovies</pre><pre>nbRatingsTrain=90570<br>nbRatingsTest=9430</pre><pre># For each user, build a list of rated movies.<br># We&#39;d need this to add random negative samples.<br>moviesByUser = {}<br>for userId in range(nbUsers):<br>    moviesByUser[str(userId)]=[]<br> <br>with open(&#39;ua.base.shuffled&#39;,&#39;r&#39;) as f:<br>    samples=csv.reader(f,delimiter=&#39;\t&#39;)<br>    for userId,movieId,rating,timestamp in samples:<br>        moviesByUser[str(int(userId)-1)].append(int(movieId)-1)</pre><pre>def loadDataset(filename, lines, columns):<br>    # Features are one-hot encoded in a sparse matrix<br>    X = lil_matrix((lines, columns)).astype(&#39;float32&#39;)<br>    # Labels are stored in a vector<br>    Y = []<br>    line=0<br>    with open(filename,&#39;r&#39;) as f:<br>        samples=csv.reader(f,delimiter=&#39;\t&#39;)<br>        for userId,movieId,rating,timestamp in samples:<br>            X[line,int(userId)-1] = 1<br>            X[line,int(nbUsers)+int(movieId)-1] = 1<br>            if int(rating) &gt;= 4:<br>                Y.append(1)<br>            else:<br>                Y.append(0)<br>            line=line+1<br>            <br>    Y=np.array(Y).astype(&#39;float32&#39;)<br>    return X,Y</pre><pre>X_train, Y_train = loadDataset(&#39;ua.base.shuffled&#39;, nbRatingsTrain, nbFeatures)<br>X_test, Y_test = loadDataset(&#39;ua.test&#39;,nbRatingsTest,nbFeatures)</pre><pre>print(X_train.shape)<br>print(Y_train.shape)<br>assert X_train.shape == (nbRatingsTrain, nbFeatures)<br>assert Y_train.shape == (nbRatingsTrain, )<br>zero_labels = np.count_nonzero(Y_train)<br>print(&quot;Training labels: %d zeros, %d ones&quot; % (zero_labels, nbRatingsTrain-zero_labels))</pre><pre>print(X_test.shape)<br>print(Y_test.shape)<br>assert X_test.shape  == (nbRatingsTest, nbFeatures)<br>assert Y_test.shape  == (nbRatingsTest, )<br>zero_labels = np.count_nonzero(Y_test)<br>print(&quot;Test labels: %d zeros, %d ones&quot; % (zero_labels, nbRatingsTest-zero_labels))</pre><p>Once the training and testing dataset is ready, we will move on to the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuVifekXFccQo0ezcmKS9w.png" /><figcaption>Screenshot6</figcaption></figure><p><strong>4. Convert the samples to protobuf format and store in s3:</strong></p><p>In this step, we will convert the dataset to protobuf format as Sagemaker accepts this format for a training job for the factorization machine and save it to s3.</p><pre>bucket = &#39;movierecommendationdemo&#39;<br>prefix = &#39;sagemaker/fm-movielens&#39;</pre><pre>train_key      = &#39;train.protobuf&#39;<br>train_prefix   = &#39;{}/{}&#39;.format(prefix, &#39;train3&#39;)</pre><pre>test_key       = &#39;test.protobuf&#39;<br>test_prefix    = &#39;{}/{}&#39;.format(prefix, &#39;test3&#39;)</pre><pre>output_prefix  = &#39;s3://{}/{}/output&#39;.format(bucket, prefix)</pre><pre>def writeDatasetToProtobuf(X, Y, bucket, prefix, key):<br>    buf = io.BytesIO()<br>    smac.write_spmatrix_to_sparse_tensor(buf, X, Y)<br>    buf.seek(0)<br>    obj = &#39;{}/{}&#39;.format(prefix, key)<br>    boto3.resource(&#39;s3&#39;).Bucket(bucket).Object(obj).upload_fileobj(buf)<br>    return &#39;s3://{}/{}&#39;.format(bucket,obj)<br>    <br>train_data = writeDatasetToProtobuf(X_train, Y_train, bucket, train_prefix, train_key)    <br>test_data  = writeDatasetToProtobuf(X_test, Y_test, bucket, test_prefix, test_key)    <br>  <br>print(train_data)<br>print(test_data)<br>print(&#39;Output: {}&#39;.format(output_prefix))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ww7cgTuIaV-cqQuQeqa3AQ.png" /><figcaption>Screenshot7</figcaption></figure><p>Once the artifacts are saved you can see them in the s3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7EiUFvF2xJSQQ7A5bb3Mw.png" /><figcaption>Screenshot8</figcaption></figure><p>5. Run the training job:</p><p>The next step is to create a training job and run it using predefined hyperparameters.</p><p>The following code will trigger the training job.</p><pre>containers = {&#39;us-west-2&#39;: &#39;174872318107.dkr.ecr.us-west-2.amazonaws.com/factorization-machines:latest&#39;,<br>              &#39;us-east-1&#39;: &#39;382416733822.dkr.ecr.us-east-1.amazonaws.com/factorization-machines:latest&#39;,<br>              &#39;us-east-2&#39;: &#39;404615174143.dkr.ecr.us-east-2.amazonaws.com/factorization-machines:latest&#39;,<br>              &#39;eu-west-1&#39;: &#39;438346466558.dkr.ecr.eu-west-1.amazonaws.com/factorization-machines:latest&#39;}</pre><pre>fm = sagemaker.estimator.Estimator(containers[boto3.Session().region_name],<br>                                   get_execution_role(), <br>                                   train_instance_count=1, <br>                                   train_instance_type=&#39;ml.c4.xlarge&#39;,<br>                                   output_path=output_prefix,<br>                                   sagemaker_session=sagemaker.Session())</pre><pre>fm.set_hyperparameters(feature_dim=nbFeatures,<br>                      predictor_type=&#39;binary_classifier&#39;,<br>                      mini_batch_size=1000,<br>                      num_factors=64,<br>                      epochs=100)</pre><pre>fm.fit({&#39;train&#39;: train_data, &#39;test&#39;: test_data})</pre><p>Once the training job starts, the user can track it from the dashboard under the training job section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wT0di2oDYQGPzIenR6bGAw.png" /><figcaption>Screenshot9</figcaption></figure><p>Once the training job is completed you can start using the trained model. Also, you can tune the hyperparameters using hyperparameter jobs. You can refer back to my <a href="https://medium.com/towards-artificial-intelligence/building-an-end-to-end-deep-learning-model-with-deployment-on-aws-cloud-using-amazon-sagemaker-6b8584c9c6e7">post </a>where I showed how to use hyperparameter tuning jobs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0CjzgE0ol_fB49WAwxywQ.png" /><figcaption>Screenshot10</figcaption></figure><p><strong>6. Deploy the baseline model:</strong></p><p>Now we can deploy our model by invoking the API programmatically or deploying it using the sagemaker dashboard.</p><pre>fm_predictor = fm.deploy(instance_type=&#39;ml.c4.xlarge&#39;, initial_instance_count=1)</pre><pre>def fm_serializer(data):<br>    js = {&#39;instances&#39;: []}<br>    for row in data:<br>        js[&#39;instances&#39;].append({&#39;features&#39;: row.tolist()})<br>    #print js<br>    return json.dumps(js)</pre><pre>fm_predictor.content_type = &#39;application/json&#39;<br>fm_predictor.serializer = fm_serializer<br>fm_predictor.deserializer = json_deserializer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnHyKja2O1_hBNmvgux38A.png" /><figcaption>Screenshot11</figcaption></figure><p>Once the endpoint is created, you can run the predictions to get recommendations on the movie for the set of users.</p><pre>result = fm_predictor.predict(X_test[1000:1010].toarray())<br>print(result)<br>print (Y_test[1000:1010])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mkvtphvhVpZRjSBZH-jRdw.png" /><figcaption>Screenshot12</figcaption></figure><p>Here predicted label (0 or 1) represents whether the user should watch movies or not with confidence scores.</p><p><strong>7. Clean up activities:</strong></p><p>To avoid any incurring charges, it is a good practice to delete endpoints, artifacts in the s3 bucket.</p><pre>sagemaker.Session().delete_endpoint(fm_predictor.endpoint)</pre><p>You also need to delete any endpoint configuration along with endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPE6NoTAJLSkcWKiDeEJ5w.png" /><figcaption>Screenshot13</figcaption></figure><p>Delete any created models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XVJ7brQvGIL-rdAo79Z9g.png" /><figcaption>Screenshot14</figcaption></figure><p><strong>Note</strong>: Stop any running notebook instances (delete if necessary after termination)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rAN5EWTlEZjmqvG-nKkLQ.png" /><figcaption>Screenshot15</figcaption></figure><p>You can also delete any artifacts in the S3 bucket.</p><p>You can find the full jupyter notebook <a href="https://github.com/anuragbisht12/AWS-SageMaker-Deployment/tree/master/Recommendation%20Engine">here</a>.</p><p>Hope you enjoyed this post, let me know about your thoughts if you have any queries or suggestions, would love to hear more from you. If you are enjoying the AI journey, stay tuned its going to be fun in future posts.</p><p>You can follow me for tutorials on AI/machine learning, data analytics, and BI. You can connect with me on <a href="https://www.linkedin.com/in/anurag-bisht-39935a59/">LinkedIn</a>.</p><p><strong>References:</strong></p><ol><li>Amazon Web Services Training</li><li>Google Cloud Training</li><li>Algorithm <a href="https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf">whitepaper</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f878d43c1005" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/building-an-end-to-end-recommendation-engine-using-matrix-factorization-with-cloud-deployment-using-f878d43c1005">Building an End to End Recommendation Engine using Matrix Factorization with Cloud Deployment using…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>