<?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 Jabezkassa on Medium]]></title>
        <description><![CDATA[Stories by Jabezkassa on Medium]]></description>
        <link>https://medium.com/@jabezkassa2022?source=rss-d458394c7447------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*B0Q9KmtAZF9uqwte8uwqZw.jpeg</url>
            <title>Stories by Jabezkassa on Medium</title>
            <link>https://medium.com/@jabezkassa2022?source=rss-d458394c7447------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:36:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jabezkassa2022/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[Semantic Image and Text Alignment: Automated Storyboard Synthesis for Digital Advertising]]></title>
            <link>https://medium.com/@jabezkassa2022/semantic-image-and-text-alignment-automated-storyboard-synthesis-for-digital-advertising-2d4948a0a06d?source=rss-d458394c7447------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d4948a0a06d</guid>
            <dc:creator><![CDATA[Jabezkassa]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 10:01:28 GMT</pubDate>
            <atom:updated>2024-07-15T16:28:35.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_sK-bnKVWhAsY7cr.jpg" /></figure><h3>Business objective</h3><p>Recent advancements in machine learning, natural language processing, and computer vision, alongside the development of Large Language Models (LLMs), have ushered in a new era of capabilities in the digital domain. These technologies enable the intricate processing and interpretation of data, facilitating the creation of detailed, dynamic content that <strong>bridges the gap between textual concepts and visual storytelling</strong>. The integration of these technologies not only simplifies<strong> the translation of complex ideas into tangible visuals</strong> but also enhances creativity and <strong>efficiency in content generation</strong>. The business objective of the challenge is to harness these capabilities to transform textual descriptions of advertisement concepts and assets into detailed storyboards. <em>This transformation process aims to visually depict</em><strong><em> the narrative flow and user interaction </em></strong><em>within advertisements</em><strong><em>,</em></strong><em> making the conceptualization of digital campaigns both more intuitive and impactful.</em></p><p><a href="https://www.adludio.com/">Adludio</a> is at the forefront of online mobile advertising, specialising in the creation of interactive ads that resonate with viewers through dynamic content such as mini-games, videos, texts, and images. Adludio offers its clients a suite of services designed to maximise engagement and campaign performance:</p><ul><li>Collection of comprehensive briefs detailing brand identity, advertising objectives, guidelines, KPIs, objectives, and budget.</li><li>Design of interactive advertisements, leveraging a rich media creative toolkit.</li><li>Distribution of these creatives to targeted audiences via sophisticated real-time bidding for impressions on the open market.</li><li>Optimization of the creative design and targeting process through advanced machine learning algorithms to ensure maximum impact.</li></ul><p>In this transformative era of advertising and recognizing the potential for technology to streamline and enhance the ad creation process, Adludio is embarking on an ambitious initiative to automate the end-to-end process of advertising production. This automation aims to significantly expedite the ideation and execution phases, enabling clients to swiftly launch their campaigns with minimal expenditure of time and resources. A key component of this automation involves the generation of potential creative concepts based on the client’s brief. By leveraging advanced machine learning algorithms, Adludio intends to present clients with viable creative options rapidly, thereby reducing the traditional turnaround time from over a week to mere days. Your task, as part of this transformative process, is to architect and develop a cutting-edge machine learning solution that automates the conversion of textual advertisement concepts, assets descriptions into visually compelling storyboards. This solution should intelligently interpret the provided concepts and assets, generate relevant visual and textual assets, compose these assets into individual ad frames, and ultimately synthesize a cohesive storyboard that encapsulates the essence of the proposed ad campaign.</p><h3>Objective</h3><p>The primary objective of this project is to develop an advertising frame that achieves a high engagement rate and click-through rate, utilizing the provided assets as an initial step. The assets include images and text that will comprise the advertising frame. This is accomplished by leveraging computer vision techniques and an AI multi-agent framework called Autogen.</p><h3>Data Provided</h3><h4>Performance data</h4><p>This data contains a list of advertisements with their associated engagement rate and click-through rate values. The purpose of this data is to expose the large language model (LLM) to examples of successful advertisements, in order to drive the desired metrics when generating new advertising content. The model will learn from the characteristics of the high-performing ads and use that knowledge to critically evaluate and improve the generated advertising material.</p><h4>Assets</h4><p>This directory contains different advertising content. Each directory contains images, text, and video assets that can be used to compose advertising frames. The goal is to determine the optimal combination of these assets to create an advertisement frame that will have a higher engagement rate.</p><h3>Tech Stack</h3><h4>AutoGen</h4><p>AutoGen is a framework for multi AI agents. While there are many definitions of agents, in AutoGen, an agent is an entity that can send messages, receive messages and generate a reply using models, tools, human inputs or a mixture of them. This abstraction not only allows agents to model real-world and abstract entities, such as people and algorithms, but it also simplifies implementation of complex workflows as collaboration among agents.</p><p>This project uses AutoGen to create two types of agents — one that composes an image, and another that critiques the created image. There is a feedback loop between the image composition agent and the image critique agent. The image composition agent re-composes the image based on the feedback provided by the critique agent. Additionally, a user proxy is utilized to execute a function suggested by these two interacting agents.</p><h4>OpenCV</h4><p>OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products.</p><p>In this project I used OpenCV to blend the assets together. The LLM will set position, brightness, and layer parameters to generate the advertising frame.</p><h4><strong>YOLO</strong></h4><p>Ultralytics YOLOv8 is a cutting-edge object detection and image segmentation model that builds upon the success of previous YOLO versions. It introduces new features and improvements to enhance performance, flexibility, and efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*rUkAkJVScaFEWKXJu49XCA.png" /><figcaption>YOLO object detection</figcaption></figure><p>In this project, the YOLOv8 object detection model is used to identify objects within each asset . However, the OpenAI API has shown more promise in this use case, as it is able to not only detect the objects, but also provide detailed descriptions of each object, including information about its color, position, and size.</p><h4>OPENAI API Vision</h4><p>Both GPT-4o and GPT-4 Turbo have vision capabilities, meaning the models can take in images and answer questions about them. Historically, language model systems have been limited by taking in a single input modality, text.</p><p>In this project, the vision capabilities of this models are utilized to provide detailed information about each asset to an “image blending” and “image critic” agent. The purpose is for the image blending agent is to read the assets provide and set the parameters to blend the aseets. The critic agent on the another hand is to analyze the detailed object-level descriptions of the generated image and provide suggestions on how to improve the advertising frame.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*wdZoaBGdG4Nz501ugoa7qQ.png" /></figure><p>OPENAI API Vision models description:</p><pre> &#39;The image appears to be an advertisement or informational graphic for a Lexus dealership. Here are the elements present in the image:\n\n1.<br> **Logo and Branding:**\n   - The top left corner features the Lexus logo and the text &quot;L/Certified by Lexus.&quot;\n\n2. **Dealership Information:**\n <br>  - The name of the dealership, &quot;Lexus of Lehigh Valley.&quot;\n   - The address of the dealership: 4500 Broadway, Allentown, PA.\n\n3. **Map:**\n   <br>- A small map is shown highlighting the location of the dealership.\n   - Nearby landmarks indicated on the map:\n     - Cetronia Ambulance Corps\n    <br> - St. Luke’s West End Medical Center\n\n4. **Car Image:**\n   - There is an image of a Lexus car, likely to promote the brand.<br>\n\nThe provided information is a mixture of text and visual elements meant to guide potential customers to the dealership location.</pre><h3>Agents Assignment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOx5wU1LK-F_gtmOEtrx2Q.png" /></figure><p>This project employs two distinct AIagents working collaboratively. The first agent is the Image Blending Agent, which is responsible for taking the available image assets and composing them into an advertising frame designed to achieve higher user engagement.</p><p>The Image Blending Agent receives feedback and suggestions from a second agent, the Image Critic Agent. The Image Critic Agent analyzes the advertising frame generated by the Image Blending Agent and provides recommendations on how to improve it. Based on the Image Critic Agent’s feedback, the Image Blending Agent then re-generates the advertising frame, iterating on the parameters to optimize it for greater user engagement.</p><p>The collaboration between these two agents, with the Image Blending Agent creating advertising frames and the Image Critic Agent providing guidance, is the core of this project’s approach to generating effective advertising content.</p><p>Additionally, a User Proxy Agent is defined to execute the functions recommended by the two primary agents.</p><h3>Creating Tools</h3><p>The two agents in this project, the Image Blending Agent and the Image Critic Agent, utilize different functions to properly achieve their assigned tasks.</p><h4>Image Blending Agent</h4><p>The Image Blending Agent uses a key function called describe_images_from_json(). This function receives a JSON file that specifies the file paths for each asset to be used in the advertising frame. It then leverages the OpenAI GPT-4 model to describe each of the listed assets in detail, including parameters like the obejcts position, brightness, layer, and other characteristics in each asset that will be useful for blending the images together. By using the GPT-4 model to extract these detailed descriptions of the individual assets, the Image Blending Agent can then intelligently compose and blend the assets into a cohesive and effective advertising frame.</p><pre>def describe_images_from_json(json_file_path: str) -&gt; Dict:<br>    &quot;&quot;&quot;<br>    Describes images specified in a JSON file.<br><br>    Parameters:<br>    - json_file_path (str): Path to the JSON file containing image paths.<br><br>    Returns:<br>    - dict: Dictionary containing descriptions for the larger image and small images.<br>    &quot;&quot;&quot;<br>    with open(json_file_path, &#39;r&#39;) as file:<br>        data = json.load(file)<br><br>    larger_image_path = data.get(&#39;larger_image_path&#39;)<br>    small_images_paths = data.get(&#39;small_images_paths&#39;, [])<br><br>    # Describe larger image<br>    larger_image_description = describe_image(larger_image_path)<br><br>    # Describe small images<br>    small_images_descriptions = [<br>        {<br>            &quot;image_path&quot;: image_path,<br>            &quot;description&quot;: describe_image(image_path)<br>        }<br>        for image_path in small_images_paths<br>    ]<br><br>    return {<br>        &quot;larger_image_description&quot;: larger_image_description,<br>        &quot;small_images_descriptions&quot;: small_images_descriptions<br>    }</pre><p>Output:</p><pre>{&quot;base_image_description&quot;: &quot;The image shows a teapot pouring hot water into a glass containing a tea bag. The tea bag has a label with the brand name \&quot;OFFBLAK.\&quot; <br>Underneath the glass, there is text that reads, \&quot;Enjoy tea delivered to your door.\&quot; This suggests an advertisement for a tea delivery service.&quot;, &quot;small_images_descriptions&quot;:<br> [{&quot;image_path&quot;: &quot;/home/jabez/week_12/Semantic-Image-and-Text-Alignment/data/015efcdd8de3698ffc4dad6dabd6664a/cta.jpg&quot;, &quot;description&quot;: &quot;The image contains the text \&quot;SHOP NOW\&quot; <br>in bold, black uppercase letters on a white background.&quot;}, {&quot;image_path&quot;: &quot;/home/jabez/week_12/Semantic-Image-and-Text-Alignment/data/015efcdd8de3698ffc4dad6dabd6664a/discover.png&quot;,<br> &quot;description&quot;: &quot;The image contains text that says, \&quot;Discover 12 unique tea flavours delivered to your door.\&quot;&quot;}, {&quot;image_path&quot;: &quot;/home/jabez/week_12/Semantic-Image-and-Text-Alignment<br>/data/015efcdd8de3698ffc4dad6dabd6664a/endframe_3.jpg&quot;, &quot;description&quot;: &quot;The image features promotional materials for Offblak, a tea brand. It includes two boxes labeled \&quot;Taster Pack,\&quot; <br>a couple of individual tea sachets, a teacup with a tea bag, and some lifestyle accessories such as sunglasses and possibly part of a leather jacket. The text in the image reads: <br>\&quot;Subscribe to Taster Pack Combo today and get 50% OFF!\&quot;&quot;}, {&quot;image_path&quot;: &quot;/home/jabez/week_12/Semantic-Image-and-Text-Alignment/data/015efcdd8de3698ffc4dad6dabd6664a/engagement_animation_1.png&quot;, <br>&quot;description&quot;: &quot;The image is a simple black and white graphic depicting a hand with an extended index finger pointing upwards, touching or pressing a circular button or icon. This is often used to<br>symbolize or indicate interaction with a touchscreen or click action.&quot;}, {&quot;image_path&quot;: &quot;/home/jabez/week_12/Semantic-Image-and-Text-Alignment/data/015efcdd8de3698ffc4dad6dabd6664a/engagement_instruction_1.png&quot;, <br>&quot;description&quot;: &quot;This image contains the text \&quot;TAP\&quot; in large, bold letters, followed by the smaller text \&quot;To get Letterbox Delivery of Tea.\&quot; It appears to be a call-to-action, possibly for a service that delivers tea to your mailbox.&quot;},<br>{&quot;image_path&quot;: &quot;/home/jabez/week_12/Semantic-Image-and-Text-Alignment/data/015efcdd8de3698ffc4dad6dabd6664a/landing_endframe.jpg&quot;, &quot;description&quot;: &quot;The image displays the logo for \&quot;OFFBLAK,\&quot; followed by the phrase \&quot;GENERATION T\&quot; underneath it.&quot;}]}</pre><p>By using this description the blending function will figureout a way on how to compose this given assets to produce the advertising frame.</p><p>The second key function utilized by the Image Blending Agent is the blend_images() function. This function receives the position, brightness, and layer parameters for each asset, and then uses the OpenCV Python library to adjust these parameters and blend the images together.</p><p>To effectively use this blending function, the assets are classified. The first asset isthe base image. This is the larger image that will serve as the background for the entire advertising frame. The other smaller assets, such as text and additional images, are then blended on top of this base frame using the position, brightness, and layer adjustments made by the blend_images() function.</p><p>By starting with a designated base image and then strategically layering the other assets on top of it, the Image Blending Agent is able to compose a cohesive and visually compelling advertising frame that is designed to maximize user engagement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*GsCgspuBFyZ1a63IPAPY-Q.png" /></figure><p>Image Blending agent first output:</p><pre>We have six smaller images to be blended on the larger image. After analyzing the content of each image, I suggest the following positions, layers and brightness:<br><br>Position names:<br>- For the &#39;SHOP NOW&#39; image: &#39;bottom center&#39; as a call to action.<br>- For the &#39;Discover 12 unique tea flavours delivered to your door&#39; image: &#39;top right&#39;, as an attractive fact.<br>- For the promotional materials for Offblak image: &#39;center center&#39; as the main promotional piece.<br>- For the &#39;TAP&#39; image: &#39;bottom left&#39; as an interactive gesture to the users.<br>- For the image that depicts a hand with an extended index finger: &#39;top left&#39; as a direction cue.<br>- For the &#39;OFFBLAK Generation T&#39; logo: &#39;top center&#39; as a brand identity.<br><br>Layers:<br>- The &#39;SHOP NOW&#39; image should be on top to attract users, so layer 1.<br>- The &#39;Discover&#39; and &#39;TAP&#39; images are equally important for marketing, so layers 2 and 3, respectively.<br>- The promotional materials image should stand out, so layer 4.<br>- The hand extended sign should be slightly hidden as it&#39;s intuitive, so layer 5.<br>- The logo can be a bit more subtle, so layer 6.<br><br>And for brightness values, we&#39;ll go for default values (1.0 each) as each image has different color and contrast requirements. </pre><pre>***** Suggested tool call (call_xxYmZuhtjEFNeNaiyUCnBHeo): blend_images *****<br>Arguments: <br>{<br>&quot;position_names&quot;: [&quot;bottom center&quot;, &quot;top right&quot;, &quot;center center&quot;, &quot;bottom left&quot;, &quot;top left&quot;, &quot;top center&quot;],<br>&quot;layers&quot;: [1, 2, 3, 4, 5, 6],<br>&quot;brightness_values&quot;: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]<br>}</pre><p>Then Image Blending Agent takes the suggestions provided by the Image Critic Agent and then uses the Image Blending Function to regenerate the advertising frame. It adjusts the positions, brightness, and layers, as well as the arrangements of the assets, based on the recommendations from the Image Critic Agent. The Blending agent stops to regenerate when the critic agent rate the generated image 8 out of 10.</p><h4>Image Critic Agent</h4><p>The Image Critic Agent utilizes a function called img_read(), which is similar in concept to the describe_images_from_json() function used by the Image Blending Agent. However, the key difference is that the img_read() function compares two different images and rates their similarity on a scale of 10.</p><p>The purpose of this function is to allow the Image Critic Agent to analyze and compare the generated advertising frame created by the Image Blending Agent against a reference “good” advertising frame. By comparing the characteristics of these two images and rating their similarity, the Image Critic Agent can provide detailed feedback and recommendations to the Image Blending Agent on how to improve the generated frame.</p><p>This comparative analysis is crucial, as the overall goal is for the Image Critic Agent to assess the generated advertising frame and provide guidance to optimize it for higher user engagement, based on the qualities of the reference “good” frame. The img_read() function gives the Image Critic Agent the necessary information to perform this critical evaluation and feedback loop with the Image Blending Agent.</p><pre>### Similarity Rating: 8/10<br><br>### Detailed Comparison:<br><br>#### Objects, Positions, and Layers:<br><br>- **Tea Bags**: Positioned similarly in both images, on the left side.<br>- **Tea Boxes (1 and 2)**: Positioned similarly, with &quot;1&quot; on top and &quot;2&quot; at the bottom. <br>- **Hand Icon**: Present in both images, but at different positions. In Image 1, it is pointing at the lower tea box. In Image 2, it&#39;s pointing at the upper tea box.<br>- **Text (&quot;Subscribe to Taster Pack Combo today and get 50% OFF!&quot;)**: Positioned similarly, centered at the top.<br>- **Sunglasses**: Positioned similarly, at the right edge.<br>- **Tea Cup**: Positioned similarly at the bottom right.<br>- **&quot;Shop Now&quot; Button**: Positioned similarly at the bottom center.<br>- **Leather Item** (possible wallet): Positioned similarly at the bottom left.<br><br>#### Brightness:<br>- Both images have similar brightness and lighting. Minor differences might be due to external factors or slight variations in image capture quality.<br><br>### Suggested Changes to Image 2:<br><br>1. **Hand Icon Position**: Move the hand icon down to point at the lower tea box (similar to Image 1).<br>2. **Header Text**: Remove the &quot;Discover 12 unique tea flavors delivered to your door&quot; text at the top to match Image 1, which doesn&#39;t have this text.</pre><p>The Image Critic Agent, on the other hand, uses an Image Reading Function that leverages the vision capabilities of the OpenAI API. This Image Reading Function takes the advertising frame generated by the Image Composition Agent as input. It then analyzes and describes the current frame by comparing it to a reference advertising image that had high user engagement.</p><p>Based on this comparative analysis, the Image Critic Agent is able to rate the quality of the current advertising frame and provide suggestions to the Image Composition Agent on how to better position and arrange the assets within the frame to improve user engagement.</p><p>Based on the given recommendation:</p><pre>img_blend_assistant (to chat_manager):<br><br>Based on the feedback, here are the revised positions, brightness, and layers for the smaller images:<br><br>position_names:<br>1. The &quot;SHOP NOW&quot; button should be place at the &quot;bottom center&quot;, but with a slightly higher position than before.<br>2. The description, &quot;Discover 12 unique tea flavours delivered to your door&quot;, should retain its position at the &quot;top center&quot;, but leave the &quot;top right&quot; and &quot;top left&quot; corners free of any images.<br>3. For the hand icon, move its position slightly towards the &quot;bottom center&quot;, but still retain its position in the &quot;center&quot;.<br><br>layers: <br>1. &quot;SHOP NOW&quot; button on the topmost layer, but adjust its layer to have less transparency so the text is more bold.<br>2. &quot;Discover 12 unique tea flavours delivered to your door&quot; - retains its position in layer 2.<br>3. Hand icon - retain its position at layer 3.<br><br>brightness_values:<br>1. For the &quot;SHOP NOW&quot; button, increase its brightness to 2.0 to make it even more prominent.<br>2. The &quot;Discover 12 unique tea flavours delivered to your door&quot; - retain its brightness at 1.8.<br>3. For the hand icon image, increase the brightness to 1.4, to ensure it&#39;s not dulled by increased brightness of the &quot;SHOP NOW&quot; button.<br><br>Let&#39;s proceed with blending the images using these revised attributes.<br>***** Suggested tool call (call_Z9hpHkgQ9yUFsgi3xRaLEcVN): blend_images *****<br>Arguments: <br>{<br>&quot;position_names&quot;: [&quot;bottom center&quot;, &quot;top center&quot;, &quot;bottom center&quot;],<br>&quot;layers&quot;: [1, 2, 3],<br>&quot;brightness_values&quot;: [2.0, 1.8, 1.4],<br>&quot;alpha&quot;: 0.5,<br>&quot;output_dir&quot;: &quot;./output&quot;<br>}</pre><p>The User Proxy that is defined to execute the functions required by the agents. Whenever either the Image Composition Agent or the Image Critic Agent needs to call one of the specialized functions, they do so through the User Proxy.</p><h3>Group Chat</h3><p>A group chat is orchestrated by a special agent type GroupChatManager. In the first step of the group chat, the Group Chat Manager selects an agent to speak. Then, the selected agent speaks and the message is sent back to the Group Chat Manager, who broadcasts the message to all other agents in the group. This process repeats until the conversation stops.</p><p>The Group Chat Manager can use several strategies to select the next agent. In this progect the round_robin strategy is followed. First I create a GroupChat object and provide the list of agents.This list would specify the order of the agents to be selected. We also initialize the group chat with an empty message list and a maximum round of 15, which means there will be at most 15iteratiosn of selecting speaker, agent speaks and broadcasting message.</p><pre>groupchat = autogen.GroupChat(<br>    agents=[user_proxy, img_blend_assistant, img_critic_assistant],<br>    messages=[],  # The initial messages in the chat<br>    max_round=15  # Maximum rounds of conversation<br>)<br># Create group chat manager<br>manager = autogen.GroupChatManager(<br>    groupchat=groupchat,<br>    llm_config=llm_config2<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ebq_m-2-iC9rw0UqkWx22A.png" /><figcaption>Generated Image</figcaption></figure><h3>Preview</h3><p>I created a frontend for the project to show how it works. The fronend is not a useful app to be used but it shows how it can be integrated in diffrent applications. The data pipeline can be adjusted as needed.</p><h4>Backend</h4><p>The backend of this system is developed using the Flask web framework. In this backend, a JSON file is defined to hold the file paths for the various assets used in the advertising frame creation process.</p><p>When a user selects the different components needed for the advertising frame, such as:</p><ol><li>The comparison image (used to evaluate the generated frame)</li><li>The background image</li><li>The individual objects or assets (that will be layered on top of the background to create the final ad)</li></ol><p>These user-selected assets are uploaded and stored in a directory on the server. The file paths for these uploaded assets are then updated in the JSON configuration file.</p><p>By maintaining this JSON file that tracks the file paths for all the necessary image assets, the backend can easily retrieve and reference these paths as needed when generating and evaluating the final advertising frame. This centralized JSON configuration helps streamline the overall workflow and ensures the backend has access to the correct image sources at all times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StW9bEogfVqVfdBtyxB1_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8ZphJZ8VnuDQ1T6Ra413Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*F5OJILZkMaSMLOtnOJNekw.png" /></figure><h3>Future Plan</h3><ul><li>Add more function to adjust colot, size, masking, and other parametrs.</li><li>Adding speaker selection function to make the speaker selection more predictive.</li><li>Use other open source models to reduce cost.</li></ul><h3>Referance</h3><ul><li><a href="https://pillow.readthedocs.io/en/stable/">Pillow</a></li><li><a href="https://microsoft.github.io/autogen/docs/Getting-Started/">Getting Started | AutoGen</a></li></ul><p><a href="https://platform.openai.com/docs/guides/vision">https://platform.openai.com/docs/guides/vision</a></p><ul><li><a href="https://opencv.org/">OpenCV - Open Computer Vision Library</a></li><li><a href="https://docs.ultralytics.com/quickstart/">Quickstart</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d4948a0a06d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Precision RAG: Prompt Tuning For Building Enterprise Grade RAG Systems]]></title>
            <link>https://medium.com/@jabezkassa2022/precision-rag-prompt-tuning-for-building-enterprise-grade-rag-systems-ed85d1a1a792?source=rss-d458394c7447------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed85d1a1a792</guid>
            <dc:creator><![CDATA[Jabezkassa]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:13:29 GMT</pubDate>
            <atom:updated>2024-07-13T18:13:29.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>Business objective</h3><p>PromptlyTech is an innovative e-business specializing in providing AI-driven solutions for optimizing the use of Language Models (LLMs) in various industries. The company aims to revolutionize how businesses interact with LLMs, making the technology more accessible, efficient, and effective. By addressing the challenges of prompt engineering, the company plays a pivotal role in enhancing decision-making, operational efficiency, and customer experience across various industries. PromptlyTech’s solutions are designed to cater to the evolving needs of a digitally-driven business landscape, where speed and accuracy are key to staying competitive.The company focuses on key services: Automatic Prompt Generation, Automatic Evaluation Data Generation, and Prompt Testing and Ranking.1. Automatic Prompt Generation Service:This service streamlines the process of creating effective prompts, enabling businesses to efficiently utilize LLMs for generating high-quality, relevant content. It significantly reduces the time and expertise required in crafting prompts manually.2. Automatic Evaluation Data Generation Service:PromptlyTech’s service automates the generation of diverse test cases, ensuring comprehensive coverage and identifying potential issues. This enhances the reliability and performance of LLM applications, saving significant time in the QA(Quality Assurance) process.3. Prompt Testing and Ranking Service:PromptlyTech’s service evaluates and ranks different prompts based on effectiveness, helping Users to get the desired outcome from LLM. It ensures that chatbots and virtual assistants provide accurate, contextually relevant responses, thereby improving user engagement and satisfaction.For this project I build a chatbot that answers a question about the Ethiopian Ccriminal law. In order to do that I used a RAG system. Retrieval Augmented Generation is a system where an LLM is give an augmented prompt to generate a relevant answer to a user question. In this case the chatbot is able to answer a question about the Ethiopian criminal law by using the Ethiopian criminal law document as a context. Here is the breakdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebFbdNGvdhUJRWYO1aeoJg.png" /><figcaption>Figure 1: RAG System</figcaption></figure><p>In this project, the large language model (LLM) I’m using is GPT-3.5 Turbo, but it has not been trained on Ethiopian criminal law. So, it can’t directly answer questions on that specific topic. To work around this, I’ve implemented a Retrieval Augmented Generation (RAG) system.In addition to using the RAG system, I’ve also taken steps to prepare the data to make the retrieval process as smooth as possible. Specifically, I’ve loaded the Ethiopian criminal law document and processed the data in the following ways:I used paragraph-level chunking as a content-aware approach, in order to enable the LLM to provide answers that are grounded in and cite the source material. This helps ensure the responses are wellsupported and transparent about where the information is coming from.</p><pre>def read_word_document(file_path):<br>doc = docx.Document(file_path)<br>full_text = [para.text for para in doc.paragraphs if para.text.strip()]<br>return full_text<br>def clean_text(text):<br>text = re.sub(r&#39;\s+&#39;, &#39; &#39;, text) # Remove extra whitespace<br>text = re.sub(r&#39;\d+\s+&#39;, &#39;&#39;, text) # Remove page numbers or unwanted numbers<br>return text.strip()<br># paragraphs = read_word_document(&#39;C:\Users\jabez\OneDrive - EEIG Construction\Documents\Week_7\RAG-<br>20240605T143203Z-001\RAG\data\ET_Criminal_Code.md&#39;)<br>cleaned_paragraphs = [clean_text(para) for para in paragraphs]<br># print(cleaned_paragraphs)</pre><p>This code preprocesses a legal text, likely the Ethiopian Criminal Code, for further analysis. It first checks if the document is a Markdown file and reads it directly. If it’s a Word document, it uses a function to extract text from each paragraph and store them in a list. Finally, another function cleans the text by removing unnecessary spaces, page numbers, and other unwanted numbers, resulting in a list of prepared paragraphs for further computational steps. This code leverages regular expressions for text manipulation and focuses on handling the two common document formats — Markdown and Word.The I embedded the process data using OpenAI’s embedding. This converts the document into a numerical format that the LLM can understand, and makes the document searchable. But before I could do the embedding, I first had to chunk the document. Chunking the data makes the retrieval process more efficient. There are different techniques that can be used for chunking the data.For this project, I decided to use a “content-aware” chunking approach, which involves taking advantage of the nature of the content I’m chunking and applying more sophisticated chunking techniques. Specifically, I used paragraph chunking.</p><pre># Use the cleaned paragraphs from your data_processing module<br>cleaned_paragraphs = data_processing.cleaned_paragraphs<br># Convert paragraphs to Document objects with metadata<br>documents = [<br>Document(page_content=para, metadata={&quot;source&quot;: f&quot;document_{i}&quot;, &quot;article&quot;: f&quot;Article_{idx}&quot;})<br>for i, doc in enumerate(cleaned_paragraphs) for idx, para in enumerate(doc.split(&quot;\n\n&quot;))<br>]<br>def split_paragraphs(documents: list[Document], chunk_size=1000, overlap=200):<br>chunks = []<br>current_chunk = []<br>current_metadata = {}<br>current_chunk_size = 0<br>for doc in documents:<br>words = doc.page_content.split()<br>if current_chunk_size + len(words) &gt; chunk_size:<br>chunk_content = &#39; &#39;.join(current_chunk)<br>chunks.append(Document(page_content=chunk_content, metadata=current_metadata))<br>current_chunk = words[-overlap:] # Start new chunk with overlap<br>current_metadata = doc.metadata # Inherit metadata<br>current_chunk_size = len(current_chunk)<br>else:<br>if not current_chunk:<br>current_metadata = doc.metadata<br>current_chunk.extend(words)<br>current_chunk_size += len(words)<br>if current_chunk:<br>chunk_content = &#39; &#39;.join(current_chunk)<br>chunks.append(Document(page_content=chunk_content, metadata=current_metadata))<br>print(f&quot;Split {len(documents)} documents into {len(chunks)} chunks.&quot;)<br>return chunks</pre><p>This code prepares legal text for further processing by first converting paragraphs into document objectswith metadata. Then, it splits these documents into smaller, more manageable chunks while ensuring noinformation is lost at the chunk boundaries by overlapping the ends of each chunk with the beginning ofthe next. This creates a chunked format suitable for large-scale text analysis.The reason I took these data processing steps is because I want the LLM to be able to not just answerquestions, but to also cite the specific article or document where it is getting the information from. Bychunking the document based on the individual articles or paragraphs, the RAG system can moreeffectively retrieve the relevant section of the document. This allows the LLM to provide answers that aregrounded in and cite the specific source material.After completing the embedding process to convert the document into a numerical format, I’ve storedthese embeddings in a Chroma DB vector database. Chroma DB is an open-source vector database that isspecifically designed to store and manage high-dimensional vector embeddings like these.These vector embeddings are numerical representations of the data objects, like the text documents, thatcapture their semantic meaning in an efficient way for fast similarity searching. This allows the RAG systemto quickly retrieve the most relevant sections of the document when answering user questions.</p><pre>def save_to_chroma(chunks: list[Document]):<br># Clear out the database first.<br>if os.path.exists(CHROMA_PATH):<br>shutil.rmtree(CHROMA_PATH)<br># Create a new DB from the documents.<br>db = Chroma.from_documents(<br>chunks, OpenAIEmbeddings(), persist_directory=CHROMA_PATH<br>)<br>db.persist()<br>print(f&quot;Saved {len(chunks)} chunks to {CHROMA_PATH}.&quot;)<br>if __name__ == &quot;__main__&quot;:<br>chunks = split_paragraphs(documents)<br>save_to_chroma(chunks)</pre><p>This code saves the preprocessed legal text chunks into a Chroma. It first ensures a clean slate by deleting any existing Chroma database at the designated location. Then, it creates a new Chroma database using the OpenAIEmbeddings function, likely to process the text for efficient retrieval. Finally, it saves this Chroma database containing the legal text chunks for future use.For the retrieval I used similarity_search_with_relevance_scores which searches the database that is similar to the question and retrieve three relevant documents.</p><pre># Prepare the DB.<br>embedding_function = OpenAIEmbeddings()<br>db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embedding_function)<br># Search the DB.<br>results = db.similarity_search_with_relevance_scores(query_text, k=3)<br>if len(results) == 0 or results[0][1] &lt; 0.7:<br>print(&quot;Unable to find matching results.&quot;)<br>return</pre><p>This code searches a specialized legal text database in Chroma. It first sets up the database connection, using text embeddings for efficient retrieval. Then, it searches for documents in the database that are most similar to a given query, aiming to retrieve the top 3 most relevant sections. Finally, it checks the number of results and the relevance score of the top result. If there are no results or the top result’s match isn’t strong enough (based on a set threshold), it informs the user that no matching information was found.Then I did prompt engineering by using the langchain ChatPromptTemplate frame work to instruct the LLM to answer question by using the given context.</p><pre>PROMPT_TEMPLATE = &quot;&quot;&quot;<br>You are a chatbot with expertise in Ethiopian criminal law.<br>Answer the question based only on the following context. Make sure to explicitly mention the article number where you get the<br>information:<br>{context}<br>---<br>Answer the question based on the above context, and include the relevant article numbers explicitly in your response: {question}<br>&quot;&quot;&quot;<br>def process_message(query_text):<br>if not isinstance(query_text, str):<br>query_text = str(query_text) # Convert to string if necessary<br># Prepare the DB.<br>embedding_function = OpenAIEmbeddings()<br>db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embedding_function)<br># Search the DB.<br>results = db.similarity_search_with_relevance_scores(query_text, k=3)<br>if len(results) == 0 or results[0][1] &lt; 0.7:<br>print(&quot;Unable to find matching results.&quot;)<br>return<br># Format the context with article numbers<br>context_pieces = []<br>sources = []<br>for doc, _score in results:<br>source = doc.metadata.get(&quot;source&quot;, &quot;Unknown source&quot;)<br>article = doc.metadata.get(&quot;article&quot;, &quot;Unknown article&quot;)<br>context_pieces.append(f&quot;{doc.page_content} (Article: {article})&quot;)<br>sources.append(article)<br>context_text = &quot;\n\n---\n\n&quot;.join(context_pieces)<br>prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)<br>prompt = prompt_template.format(context=context_text, question=query_text)<br># Generate the response<br>model = ChatOpenAI()<br>response_text = model.predict(prompt)<br># Ensure article numbers are mentioned explicitly<br>for article in sources:<br>if article in response_text:<br>response_text = response_text.replace(article, f&quot;Article {article}&quot;)<br>formatted_response = f&quot;Response: {response_text}\nSources: {&#39;, &#39;.join(sources)}&quot;<br>return formatted_response<br>if __name__ == &quot;__main__&quot;:</pre><pre>query = &quot;What is the procedure for arrest under Ethiopian criminal law?&quot;<br>response = process_message(query)<br>print(response)</pre><p>This code provides a question-answering system for Ethiopian criminal law. It searches a specialized legal text database for relevant sections based on the user’s query. If a match is found, it creates a prompt for a large language model incorporating the retrieved context and the user’s question. The LLM then generates an answer, which is checked to ensure it references the relevant law articles. Finally, the system presents the answer along with the sources (article numbers) used to generate the response.</p><h3>Automatic prompt generation</h3><h4>Example of code that generate prompt automaticallyPrompts</h4><p>RoyalePrompts Prompt engineering is an extremely iterative process. Even when we manage to settle down on a prompt, it’s so difficult to test it against test cases and other possible prompts to make sure we’re giving the best instructions to the model.Prompts Royale is an application that allows you to really easily create many prompt candidates, write your own ones, and make them battle until a clear winner emerges. It makes the process of iterating on a prompt feel much easier and more reliable.You give a description of what you want to accomplish, give it a few scenarios and expected outputs, and then just sit back and watch them battle for #1.I instruct the prompt royale to generate 5 prompts so that the LLM can answer question about the Ethiopian criminal law based on the given context and user question. Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*4_GjsrMcosH4tBXIkoATNA.png" /></figure><h3>Generating Prompts Automatically</h3><p>Then I used prompt engineering and a RAG system to generate a prompt based on the user question and the given context. Since the given context is the Ethiopian criminal law, the LLM generate good prompts based on the given context and the user question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*9jZw5iAaiKVsFOphtMLH_Q.png" /></figure><p>As it seen above the user gives a question then the LLM produce prompts that are relevant to the context and question.</p><h3>Evaluation Data Generation</h3><p>To generate evaluation data set on of the common way is to use Ragas. Ragas is a framework that helps to evaluate a Retrieval Augmented Generation (RAG) pipelines. RAG denotes a class of LLM applications that use external data to augment the LLM’s context. There are existing tools and frameworks that help to build these pipelines but evaluating it and quantifying the pipeline performance can be hard. This is where Ragas (RAG Assessment) comes in.Synthetic test set:</p><pre># generator with openai models<br>generator_llm = ChatOpenAI(model=&quot;gpt-3.5-turbo-16k&quot;)<br>critic_llm = ChatOpenAI(model=&quot;gpt-3.5-turbo-16k&quot;)<br>embeddings = OpenAIEmbeddings()<br>generator = TestsetGenerator.from_langchain(<br>generator_llm,<br>critic_llm,<br>embeddings<br>)<br># generate testset<br>testset = generator.generate_with_langchain_docs(documents, test_size=10, distributions={simple: 0.5, reasoning: 0.25,<br>multi_context: 0.25})<br>df = testset.to_pandas()<br>print(df)</pre><p>This code generates a test set for a question-answering system, related to Ethiopian criminal law. It first sets up different components including large language models (LLMs) for generating and potentially evaluating text, and an embedding tool for text analysis. Then, it uses these components to create a set of test cases. The code aims to generate a diverse set of questions with different difficulty levels, including simple Q&amp;A, questions requiring reasoning, and questions needing information from multiple legal documents. Finally, it presents the test cases in a structured format for further analysis of the questionanswering system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kwREyeGJrZr_mvVDMYtDg.png" /></figure><p>The evaluation dataset includes question, context, ground truth, evolution type, metadata and episode done.</p><h3>My own test data set</h3><p>I used also the prompt generated above to get an answer from the LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*LUmAMgP2kA_pMk7XL8DD4g.png" /></figure><h3>Automatic evaluation</h3><p>Once the test set is ready (whether the data set I created or used the synthetic test set generation module), it’s time to evaluate the RAG pipeline. But I am testing not only the Rag pipe line but the generated prompt using Ragas.</p><h4>Metrics</h4><p>Ragas provides several metrics to evaluate various aspects of your RAG systems: Retriever: Offers context_precision and context_recall that measure the performance of yourretrieval system. Generator (LLM): Provides faithfulness that measures hallucinations and answer_relevancy thatmeasures how relevant the answers are to the question.</p><pre>from ragas import evaluat<br>result = evaluate(<br>dataset = dataset,<br>metrics=[<br>context_precision,<br>context_recall,<br>],<br>)<br>result<br>df2 = result.to_pandas()</pre><p>This code evaluates a question-answering system, likely for Ethiopian criminal law. It uses a function from the Ragas library, possibly designed for RAG systems, to assess the system’s performance on a test set (potentially generated earlier). The evaluation focuses on metrics like context precision and recall, which measure how effectively the system retrieves relevant information from the legal documents to answer user questions. Finally, the results are converted into a Pandas DataFrame for easier analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*oZDtMy_7ChCm3OjMjqES0g.png" /></figure><h3>Reference</h3><ul><li><a href="https://www.pinecone.io/learn/chunking-strategies/">Chunking Strategies for LLM Applications | Pinecone</a></li><li><a href="https://github.com/meistrari/prompts-royale">GitHub - meistrari/prompts-royale: Automatically create prompts and make them fight each other to know which is the best</a></li><li><a href="https://python.langchain.com/v0.2/docs/tutorials/rag/">Build a Retrieval Augmented Generation (RAG) App | 🦜️🔗 LangChain</a></li><li><a href="https://docs.ragas.io/en/latest/getstarted/testset_generation.html#documents">Generate a Synthetic Test Set | Ragas</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed85d1a1a792" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contract Advisor RAG: Towards Building A High-Precision Legal Expert LLM APP]]></title>
            <link>https://medium.com/@jabezkassa2022/contract-advisor-rag-towards-building-a-high-precision-legal-expert-llm-app-aaeb14d72ce8?source=rss-d458394c7447------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaeb14d72ce8</guid>
            <dc:creator><![CDATA[Jabezkassa]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 19:25:10 GMT</pubDate>
            <atom:updated>2024-07-24T22:16:59.900Z</atom:updated>
            <content:encoded><![CDATA[<h3>Business objective</h3><p><a href="http://lizzyai.com/">Lizzy AI</a> is an early-stage Israeli startup, developing the next-generation contract AI (see short <a href="https://youtu.be/NFwmptDOsAc">video</a>). We leverage Hybrid LLM technology (edge, private cloud and LLM services), to build the first, fully autonomous, artificial contract lawyer. The first step in our journey is a powerful contract assistant, with the ultimate goal of developing a fully autonomous contract bot, capable of drafting, reviewing, and negotiating contracts, independently, end-to-end, without human assistance.</p><p>Our task is as follows: <strong>build, evaluate and improve</strong> a RAG system for Contract Q&amp;A (chatting with a contract and asking questions about the contract).</p><h3>Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*CyA2YAR-vD3hFHjwX1eWMA.png" /></figure><p>As stated in the business objective the target for this project is to build a rag system for a question and answer contract bot. Which means a user can interact with a bot to get relevant inlevant information from the bot As you can see from the above.</p><p>However, there are different strategies that can improve the effectiveness of a RAG pipeline. The pipeline’s effectiveness depends on several parameters:</p><ul><li>Clear user query</li><li>Context quality and chunking mechanism</li><li>Retrieval mechanism</li><li>Ranking mechanism within retrieval</li></ul><p>By measuring the RAG pipeline’s performance and modifying or changing these parameters based on the results, we can improve the system’s effectiveness.</p><h3>Evaluation Method</h3><p>In this progect we are utilizing RAGS as evaluation mechanism. RAGAS has the following metrics which enable us to measure the performance of RAG pipeline:</p><ul><li>Faithfulness: This measures the factual consistency of the generated answer against the given context. It is calculated from answer and retrieved context. The answer is scaled to (0,1) range. Higher the better.</li><li>Answer Relevance: The evaluation metric, Answer Relevancy, focuses on assessing how pertinent the generated answer is to the given prompt. A lower score is assigned to answers that are incomplete or contain redundant information and higher scores indicate better relevancy.</li><li>Context Recall: Context recall measures the extent to which the retrieved context aligns with the annotated answer, treated as the ground truth. It is computed based on the ground truth and the retrieved context, and the values range between 0 and 1, with higher values indicating better performance.</li><li>Context Precision: Context Precision is a metric that evaluates whether all of the ground-truth relevant items present in the contexts are ranked higher or not. Ideally all the relevant chunks must appear at the top ranks. This metric is computed using the question, ground_truth and the contexts, with values ranging between 0 and 1, where higher scores indicate better precision.</li><li>Context Relevancy:This metric gauges the relevancy of the retrieved context, calculated based on both the question and contexts. The values fall within the range of (0, 1), with higher values indicating better relevancy.</li></ul><h3>Test data</h3><p>The client has provided a test dataset that includes sample questions and their corresponding ground truth answers. We will use this test data to measure the performance of the system we’ve built, which includes the text segmentation, vector embedding, retrieval, and language model components.</p><pre>def adding_answer_to_testdata(test_data, rag_pipeline, vector, retriever):<br>    questions = test_data[&#39;question&#39;].to_list()<br>    ground_truth = test_data[&#39;ground_truth&#39;].to_list()<br>    data = {&#39;question&#39;: [], &#39;answer&#39;: [], &#39;contexts&#39;: [], &#39;ground_truth&#39;: ground_truth}<br>    <br>    for query in questions:<br>        data[&#39;question&#39;].append(query)<br>        <br>        # Generate the chatbot response<br>        data[&#39;answer&#39;].append(rag_pipeline(vector, query))<br>        <br>        # Retrieve relevant documents<br>        data[&#39;contexts&#39;].append([doc.page_content for doc in retriever.get_relevant_documents(query)])<br>    <br>    df = pd.DataFrame(data)<br>    dataset = Dataset.from_pandas(df)<br>    return dataset</pre><p>Specifically, we will add the answer generated by the RAG (Retrieval-Augmented Generation) pipeline to the test data. Then, we will evaluate the performance of our system by comparing the RAG pipeline’s answer to the ground truth provided in the test dataset. This will allow us to assess the accuracy and effectiveness of our overall approach.</p><pre>def ragas_evaluator(dataset):<br>    from ragas.metrics import (<br>        answer_relevancy,<br>        faithfulness,<br>        context_recall,<br>        context_precision,<br>    )<br><br>    from ragas import evaluate<br><br>    result = evaluate(<br>        dataset = dataset,<br>        metrics=[<br>            context_precision,<br>            faithfulness,<br>            answer_relevancy,<br>            context_recall,<br>        ],<br>    )<br>    result<br>    evaluation_result = result.to_pandas()<br>    return evaluation_result</pre><h3>Simple RAG system</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*qUbqR5jvsFCxWSRx8hXb5g.png" /><figcaption>Simple RAG</figcaption></figure><p>First let’s start by simple RAG pipeline. We begin by loading the contents of a legal document into a variable. Then, we use the RecursiveCharacterTextSplitter from the LangChain to split the text into smaller chunks, each with a maximum size of 200 characters. This process divides the original document into a list of manageable text segments that can be more easily processed.</p><pre>def doc_loader(file_path):<br>    loader = Docx2txtLoader(file_path)<br>    docs = loader.load()<br>    return docs<br>    <br># Function to split documents into smaller chunks and create a vector store<br>def text_splitter(docs):<br>    # Initialize the text splitter with desired chunk size and overlap<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=250, chunk_overlap=200)<br>    splits = text_splitter.split_documents(docs)<br>    <br>    # Create embeddings using OpenAI<br>    embeddings = OpenAIEmbeddings()<br>    <br>    # Create a Chroma vector store from the document chunks and embeddings<br>    vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)<br>    return vectorstore</pre><p>After segmenting the document into manageable chunks, we’ll utilize OpenAI’s embedding model to generate vector representations for each segment. These vector embeddings will then be persisted within the Chroma vector database.</p><p>Once the vectors have been saved to the database, we will use a retriever that can search the vector database to find the most relevant context for a user’s query. This is accomplished through a similarity search, which allows the retriever to identify the top 6 chunks that are most similar to the user’s input.</p><pre>def simple_pipeline(vectorstore, question):<br>    retriever = vectorstore.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 6})<br>    <br>    # Define the prompt template<br>    prompt_template = PromptTemplate(<br>        input_variables=[&quot;context&quot;, &quot;question&quot;],<br>        template=&quot;&quot;&quot;<br>        You are a contract assistant.<br>        Use the following contract as a context to answer the question. Do not use any outside knowledge. <br>        If the answer is not in the context, simply state &quot;The information is not available in the provided context.&quot;<br><br>        Context:<br>        {context}<br><br>        Question:<br>        {question}<br><br>        Answer:<br>        &quot;&quot;&quot;<br>    )<br>    <br>    llm = ChatOpenAI(model=&quot;gpt-4&quot;, temperature=0.5)<br><br>    def format_docs(docs):<br>        return &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br><br>    # Create the chain with the prompt template<br>    rag_chain = (<br>        {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>        | RunnableLambda(lambda inputs: prompt_template.format(**inputs))<br>        | llm<br>        | StrOutputParser()<br>    )<br><br>    # Invoke the chain with the question<br>    answer = rag_chain.invoke(question)<br>    return answer</pre><p>Finally, we will utilize GPT-4 as the large language model and construct a prompt that instructs the model to answer the user’s question based on the provided context. We will then implement a RAG (Retrieval-Augmented Generation) pipeline, which will pass both the prompt and the relevant context to the LLM to generate the final answer.</p><h3>Evaluation Result</h3><p>This is the mean value of the metrics for the test data:</p><pre>context_recall: 38%<br>faithfulness: 48%<br>answer_relevancy: 81%<br>context_precision: 48%</pre><p>As we can see from the result the retrival mechanism is not effective since the context retrived is not a good match to the ground truth. Context precision and faithfulness are also low indicating the retrived context is not well suited to the user query. Therefore it is better to apply other strategies to improve the effectivness.</p><h3><strong>Multiquery RAG</strong></h3><p>In the simple RAG system we discussed earlier, the retrieved document was not relevant to the user’s query and the ground truth. One possible reason for this is that sinve we are retrieving chunks based on the user’s query, If the user’s query is unclear or ambiguous, we are likely to retrieve irrelevant context. To address this, we can consider using user query translation. This involves translating the user’s query in some way to make it clearer or more specific, with the goal of improving the relevance of the retrieved information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JppvGD1NnJIDMbKswBGK_w.png" /><figcaption>Multiquery</figcaption></figure><p>In this step, we are going to rewrite the user’s query in different ways to address different perspectives. We won’t just create a single rewritten query, but instead generate multiple queries. Then, we will retrieve relevant chunks by performing a similarity search in the vector database, using each of the rewritten queries. Finally, we will combine the retrieved chunks in some way to perform the overall RAG process.</p><p>All the process upuntil indexing is similar to the simple RAG pipeline. Then we are going to create a RAG pipeline to produce multi query.</p><pre> retriever = vectorstore.as_retriever()<br>    template = &quot;&quot;&quot;You are an AI language model assistant. Your task is to generate five <br>    different versions of the given user question to retrieve relevant documents from a vector <br>    database. By generating multiple perspectives on the user question, your goal is to help<br>    the user overcome some of the limitations of the distance-based similarity search. <br>    Provide these alternative questions separated by newlines. Original question: {question}&quot;&quot;&quot;<br>    prompt_perspectives = ChatPromptTemplate.from_template(template)<br><br>    from langchain_core.output_parsers import StrOutputParser<br>    from langchain_openai import ChatOpenAI<br><br>    generate_queries = (<br>        prompt_perspectives <br>        | ChatOpenAI(temperature=0) <br>        | StrOutputParser() <br>        | (lambda x: x.split(&quot;\n&quot;))<br>         )</pre><p>We are going to write a prompt to instruct the model to create query which is 5 diffrent version of the user original query. Then we are going to pass the prompt to the LLM.</p><pre> def get_unique_union(documents: list[list]):<br>        &quot;&quot;&quot; Unique union of retrieved docs &quot;&quot;&quot;<br>        # Flatten list of lists, and convert each Document to string<br>        flattened_docs = [dumps(doc) for sublist in documents for doc in sublist]<br>        # Get unique documents<br>        unique_docs = list(set(flattened_docs))<br>        # Return<br>        return [loads(doc) for doc in unique_docs]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sf6t5KhEu-0DhcRk8QKstw.png" /><figcaption>Langsmith Trace</figcaption></figure><p>As we can see from langsmith project trace the model produced 5 diffrent query from the user query. And then retrived document chunk for each question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzjy1K6jG5ly69nS-xfsKQ.png" /><figcaption>Retrived chunk document</figcaption></figure><p>Then from the retrived document the above function will create a unique union of the retrived document.</p><p>Finally we are going to pass this unique union document along with a prompt to the LLM to get the final answer.</p><pre>retrieval_chain = generate_queries | retriever.map() | get_unique_union<br>    docs = retrieval_chain.invoke({&quot;question&quot;:question})<br># RAG<br>    template = &quot;&quot;&quot;Answer the following question based on this context:<br>    {context}<br>    Question: {question}<br>    &quot;&quot;&quot;<br>    prompt = ChatPromptTemplate.from_template(template)<br>    llm = ChatOpenAI(model=&quot;gpt-4&quot;,temperature=0.8)<br>    final_rag_chain = (<br>        {&quot;context&quot;: retrieval_chain, <br>        &quot;question&quot;: itemgetter(&quot;question&quot;)} <br>        | prompt<br>        | llm<br>        | StrOutputParser()<br>    )<br>    answer = final_rag_chain.invoke({&quot;question&quot;:question})</pre><p>Evaluation Result</p><pre>context_recall: 53%<br>faithfulness: 57%<br>answer_relevancy: 89%<br>context_precision: 57%</pre><p>As we can see, there is an improvment in every metrics from the simple RAG pipeline. Context recall increased by 15%, faithfulness increased by 9%, answer relevancy and context precision both increase by 8%. Therefore we can conclude that multiquery strategy definately increase the overall performance of the RAG pipeline. However, other strategies should be explored to improve the system even more.</p><h3>RAG Fusion</h3><p>To further improve the evluation result from multiquery we can add another strategy called RAG fusion. The diffrence of RAG fusion from multiquery is its capability of reranking. All the process including rephrasing user query in diffrent perspective and retriving documents for each query is all the same. The diffrence or the additional step is after the retrival of the document for each translated query will be rancked to produce the final top documents.</p><pre>for docs in results:<br>          # Iterate through each document in the list, with its rank (position in the list)<br>          for rank, doc in enumerate(docs):<br>              # Convert the document to a string format to use as a key (assumes documents can be serialized to JSON)<br>              doc_str = dumps(doc)<br>              # If the document is not yet in the fused_scores dictionary, add it with an initial score of 0<br>              if doc_str not in fused_scores:<br>                  fused_scores[doc_str] = 0<br>              # Retrieve the current score of the document, if any<br>              previous_score = fused_scores[doc_str]<br>              # Update the score of the document using the RRF formula: 1 / (rank + k)<br>              fused_scores[doc_str] += 1 / (rank + k)<br><br>      # Sort the documents based on their fused scores in descending order to get the final reranked results<br>      reranked_results = [<br>          (loads(doc), score)<br>          for doc, score in sorted(fused_scores.items(), key=lambda x: x[1], reverse=True)<br>      ]</pre><p>Then this reranked documet will be given as an input to the final RAG pipeline.</p><h3>Evaluation</h3><pre>context_recall:38%<br>faithfulness: 49.8%<br>answer_relevancy: 36.6%<br>context_precision: 49.8%</pre><p>Unfortunately, the evaluation metrics result were not as good as expected. All the metrics decreased compared to the results from the multi-query and simple RAG approaches. This suggests that the reranking process implemented was ultimately unsuccessful in improving the RAG pipeline performance.</p><h3>Autogen</h3><p>Alternetive strategy to enhance a RAG pipeline is to use AI agent. We can create agents that enhances the retrival part of a RAG system. One of the known, open source and effective framework for building AI agent is Microsoft Autogen.</p><p>The first approach involves using two agents — an assistant agent and a user proxy agent. The assistant agent utilizes a function called “contract” that employs a multiquery method to return unique union chunks. When a user asks a question, the assistant agent receives the query, calls the contract function, and passes the user’s question as an argument.</p><pre><br>class ContractRetriver():<br>    def contract(question: str):<br>        file_path = &#39;/home/jabez/week_11 Presentation/data/Raptor Contract.docx&#39;<br>        loader = Docx2txtLoader(file_path)<br>        docs = loader.load()<br>        text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br>        splits = text_splitter.split_documents(docs)<br>        vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())<br>        retriever = vectorstore.as_retriever()<br>        template = &quot;&quot;&quot;You are an AI language model assistant. Your task is to generate five <br>        different versions of the given user question to retrieve relevant documents from a vector <br>        database. By generating multiple perspectives on the user question, your goal is to help<br>        the user overcome some of the limitations of the distance-based similarity search. <br>        Provide these alternative questions separated by newlines. Original question: {question}&quot;&quot;&quot;<br>        prompt_perspectives = ChatPromptTemplate.from_template(template)<br>        generate_queries = (<br>            prompt_perspectives <br>            | ChatOpenAI(temperature=0) <br>            | StrOutputParser() <br>            | (lambda x: x.split(&quot;\n&quot;))<br>        )<br>        def get_unique_union(documents: List[List[Any]]) -&gt; List[Any]:<br>            flattened_docs = [dumps(doc) for sublist in documents for doc in sublist]<br>            unique_docs = list(set(flattened_docs))<br>            return [loads(doc) for doc in unique_docs]<br>        retrieval_chain = generate_queries | retriever.map() | get_unique_union<br>        docs = retrieval_chain.invoke({&quot;question&quot;: question})<br>        return &quot;\n&quot;.join(doc.page_content for doc in docs), retriever<br><br>    def get_retriever(question: str):<br>        file_path = &#39;/home/jabez/week_11 Presentation/data/Raptor Contract.docx&#39;<br>        loader = Docx2txtLoader(file_path)<br>        docs = loader.load()<br>        text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br>        splits = text_splitter.split_documents(docs)<br>        vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())<br>        retriever = vectorstore.as_retriever()<br>        return retriever</pre><p>The user proxy agent then takes the user’s query and executes the contract function. The returned chunks are provided back to the assistant agent. Finally, the assistant agent answers the user’s question based on the retrieved chunks.</p><pre>assistant = autogen.AssistantAgent(<br>        name=&quot;assistant&quot;,<br>        code_execution_config=False,<br>        system_message=<br>        &quot;&quot;&quot;<br>    You are a knowledgeable contract assistant. Answer user questions with concise and accurate information drawn solely from the provided contract.<br>    Always reference the specific section and clause where the information is located. Ensure your responses are brief, precise, and strictly within the given context.&quot;,<br>        &quot;&quot;&quot;,<br><br>        llm_config={<br>            &quot;temperature&quot;: 0,<br>            &quot;timeout&quot;: 600,<br>            &quot;cache_seed&quot;: 42,<br>            &quot;config_list&quot;: config_list,<br>            &quot;functions&quot;: [<br>                {<br>                            &quot;name&quot;: &quot;contract&quot;,<br>                            &quot;description&quot;: &quot; get the contract docs from the contract&quot;,<br>                            &quot;parameters&quot;: {<br>                                &quot;type&quot;: &quot;object&quot;,<br>                                &quot;properties&quot;: {<br>                                    &quot;question&quot;: {<br>                                        &quot;type&quot;: &quot;string&quot;,<br>                                        &quot;description&quot;: &quot;user question&quot;<br>                                    },<br><br>                                },<br>                                &quot;required&quot;: [&quot;question&quot;]<br>                            }<br>                            }<br>            ],<br>        },<br>    )<br>def termination_msg(x):<br>    return isinstance(x, dict) and &quot;TERMINATE&quot; == str(x.get(&quot;content&quot;, &quot;&quot;))[-9:].upper()<br><br><br># create a UserProxyAgent instance named &quot;user_proxy&quot;<br>user_proxy = autogen.UserProxyAgent(<br>    name=&quot;user_proxy&quot;,<br>    is_termination_msg=termination_msg,<br>    human_input_mode=&quot;NEVER&quot;,<br>    max_consecutive_auto_reply=1,<br>    # is_termination_msg=lambda x: &quot;content&quot; in x and x[&quot;content&quot;] is not None and x[&quot;content&quot;].rstrip().endswith(&quot;TERMINATE&quot;),<br>    # code_execution_config={&quot;work_dir&quot;: &quot;planning&quot;},<br>    function_map={&quot;contract&quot;: ContractRetriver.contract},<br>    code_execution_config=False<br>)</pre><p>In this way, the approach leverages the multiquery strategy and the function calling/execution capabilities of AutoGen to enhance the performance of the RAG system.</p><p>Result:</p><pre>[33muser_proxy[0m (to assistant):<br><br>Who are the parties to the Agreement and what are their defined names?<br><br>--------------------------------------------------------------------------------<br>[33massistant[0m (to user_proxy):<br><br>[32m***** Suggested function call: contract *****[0m<br>Arguments: <br>{<br>  &quot;question&quot;: &quot;Who are the parties to the Agreement and what are their defined names?&quot;<br>}<br>[32m*********************************************[0m<br><br>--------------------------------------------------------------------------------<br>[35m<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; EXECUTING FUNCTION contract...[0m<br>[33muser_proxy[0m (to assistant):<br><br>[32m***** Response from calling function (contract) *****[0m<br>Third Parties: The Advisor represents that the performance of the Services and the terms of this Undertaking, do not and will not breach any right, contractual or other, of any employer, customer or other third party. Advisor acknowledges that the Company is relying upon the truthfulness and accuracy of such representations in engaging with the Advisor. Advisor specifically undertakes not to use any proprietary and/or confidential information belonging to the Advisor and/or any third party while performing the Services and in case any Advisor proprietary or confidential information is used, such information will be automatically assigned to the Company and become its full and exclusive property.<br>Governing Law and Jurisdiction:  This Agreement shall be governed by the laws of the State of Israel, without giving effect to the rules respecting conflicts of laws. The parties consent to the exclusive jurisdiction and venue of Tel Aviv courts for any lawsuit filed arising from or relating to this Agreement.   <br><br><br><br>Notices: Notices under this Agreement shall be delivered to the party’s email address as follows: Company: info@cloudcorp.com, Advisor: jackrobinson@gmail.com, or in any the other means with a proof of acceptance by the other party.<br><br><br><br>IN WITNESS WHEREOF the parties have executed this Agreement as of the date first above written.<br><br>Cloud Investments Ltd.    Advisor <br><br><br><br>By: ________________________  By:________________________<br><br>Name: Silvan Joseph    Name: Jack Robinson  <br><br>Title: CEO     <br><br>Confidentiality, None Compete and IP Ownership Undertaking<br><br>Appendix A to Advisory Service Agreement as of June 15th, 2023<br>Entire Agreement; No Waiver or Assignment: This Agreement together with the Exhibits, which are attached hereto and incorporated herein, set forth the entire Agreement between the parties and shall supersede all previous communications and agreements between the parties, either oral or written. This Agreement may be modified only by a written amendment executed by both parties. This Agreement may not be assigned, sold, delegated or transferred in any manner by Advisor for any reason whatsoever. The Company may assign the Agreement to a successor of all or substantially all of its assets or business, provided the assignee has assumed the Company’s obligations under this Agreement.<br>[32m*****************************************************[0m<br><br>--------------------------------------------------------------------------------<br>[33massistant[0m (to user_proxy):<br><br>The parties to the Agreement are Cloud Investments Ltd., referred to as the &quot;Company&quot;, and Jack Robinson, referred to as the &quot;Advisor&quot;. The Company&#39;s representative is Silvan Joseph, who holds the title of CEO. The information can be found in the signature section of the Agreement.<br><br>--------------------------------------------------------------------------------</pre><p>Rag Evaluation:</p><pre>context_recall:46%, <br>faithfulness:63%<br>answer_relevancy:88%<br>context_precision: 61%</pre><p>The second strategy is using the AutoGen RetrieveAssistantAgent and RetrieveUserProxyAgent classes. We can improve the RAG system.</p><pre>assistant = RetrieveAssistantAgent(<br>    name=&quot;assistant&quot;,<br>    system_message=&quot;You are a knowledgeable contract assistant. Your task is to provide precise and accurate answers to user questions based on the content of the contract document. Always refer to the specific section and clause of the contract where the information is found to support your response&quot;,<br>    llm_config=llm_config,<br>    code_execution_config=code_execution_config,<br>    human_input_mode=&quot;NEVER&quot;,  # Never ask for human input<br>)<br><br># Initialize the proxy agent responsible for retrieving documents and handling the Q&amp;A<br>ragproxyagent = RetrieveUserProxyAgent(<br>name=&quot;ragproxyagent&quot;,<br>retrieve_config={<br>    &quot;task&quot;: &quot;qa&quot;,<br>    &quot;docs_path&quot;: &quot;Contract-Advisor-RAG/data/document.docx&quot;,<br>    &quot;chunk_token_size&quot;:250,<br>    &quot;model&quot;: config_list[0][&quot;model&quot;],<br>    # &quot;client&quot;: chromadb.PersistentClient(path=&quot;/tmp/chromadb&quot;),  # deprecated, use &quot;vector_db&quot; instead<br>    &quot;vector_db&quot;: &quot;chroma&quot;,  # to use the deprecated `client` parameter, set to None and uncomment the line above<br>    &quot;overwrite&quot;: True,  # set to True if you want to overwrite an existing collection<br><br>},<br>code_execution_config=code_execution_config,<br>human_input_mode=&quot;NEVER&quot;,  # Never ask for human input.<br>)</pre><p>RetrieveUserProxyAgentwill take the document and chunck it based on the specified token size. Then will save it on chroma vector database. the RetrieveAssistantAgent act as an assistant based on the given instruction as a prompt.</p><p>In my experiments, I found that setting the chunking size to 250 significantly improved the results compared to using higher chunking sizes. This suggests that for this particular use case, decreasing the chunking size was an effective way to improve the performance of the system.</p><p>Finally we will intiate a chat with the assistant using the proxy agent:</p><pre><br>    # Initiate the chat with the assistant using the proxy agent<br>    ragproxyagent.initiate_chat(<br>        assistant, <br>        message=ragproxyagent.message_generator, <br>        problem=question<br>    )<br>    return ragproxyagent.last_message()</pre><p>I was able to see the usage summary for the indevor for a single user query.</p><pre>Agent &#39;assistant&#39;:<br>----------------------------------------------------------------------------------------------------<br>Usage summary excluding cached usage: <br>Total cost: 0.09243<br>* Model &#39;gpt-4-0613&#39;: cost: 0.09243, prompt_tokens: 2867, completion_tokens: 107, total_tokens: 2974<br><br>All completions are non-cached: the total cost with cached completions is the same as actual cost.<br>----------------------------------------------------------------------------------------------------</pre><h3>Backend</h3><p>In this project I used flask API for the backend.</p><pre>@app.route(&#39;/chat&#39;, methods=[&#39;POST&#39;])<br>def execute():<br>    try:<br>        data = request.form<br>        logging.debug(f&quot;Request received: {data}&quot;)<br><br>        if not data or &#39;message&#39; not in data:<br>            raise ValueError(&quot;Invalid input data&quot;)<br><br>        user_input = data.get(&#39;message&#39;)<br>        logging.debug(f&quot;User input: {user_input}&quot;)<br><br>        uploaded_folder = &#39;/home/jabez/Documents/week_11/Contract-Advisor-RAG/uploaded&#39;<br>        clear_uploaded_folder(uploaded_folder)<br><br>        file = request.files.get(&#39;file&#39;)<br>        if file:<br>            # Save the uploaded file temporarily<br>            temp_path = os.path.join(uploaded_folder, file.filename)<br>            file.save(temp_path)<br>            logging.debug(f&quot;Temporary file saved: {temp_path}&quot;)<br><br>            # Convert the Word document to text<br>            text_content = convert_docx_to_text(temp_path)<br><br>            # Save the text content to a .md file<br>            filename = os.path.splitext(file.filename)[0] + &#39;.md&#39;<br>            file_path = os.path.join(uploaded_folder, filename)<br>            with open(file_path, &#39;w&#39;) as md_file:<br>                md_file.write(text_content)<br>            logging.debug(f&quot;File converted and saved as: {file_path}&quot;)<br><br>            # Remove the temporary file<br>            os.remove(temp_path)<br><br>            # Set the file path in the RAGBot instance<br>            rag_bot.set_file_path(file_path)<br>        else:<br>            file_path = os.getenv(&#39;FILE_PATH&#39;, &#39;/home/jabez/Documents/week_11/Contract-Advisor-RAG/data/document.md&#39;)<br>            logging.debug(f&quot;Default file path: {file_path}&quot;)<br>            <br>            # Set the default file path if not already set<br>            if not rag_bot.file_path:<br>                rag_bot.set_file_path(file_path)<br><br>        # Get the response from the bot<br>        result = rag_bot.run(user_input)<br>        logging.debug(f&quot;Chatbot response: {result}&quot;)<br><br>        if not isinstance(result, dict) or &#39;content&#39; not in result or &#39;role&#39; not in result:<br>            raise ValueError(&quot;Invalid response format from autogen_bot&quot;)<br><br>        return jsonify({&#39;response&#39;: result})<br>    except ValueError as ve:<br>        logging.error(f&quot;ValueError: {ve}&quot;, exc_info=True)<br>        return jsonify({&#39;output&#39;: f&quot;ValueError: {str(ve)}&quot;}), 400<br>    except FileNotFoundError as fnf:<br>        logging.error(f&quot;FileNotFoundError: {fnf}&quot;, exc_info=True)<br>        return jsonify({&#39;output&#39;: f&quot;FileNotFoundError: {str(fnf)}&quot;}), 404<br>    except Exception as e:<br>        logging.error(f&quot;Error processing request: {e}&quot;, exc_info=True)<br>        return jsonify({&#39;output&#39;: f&quot;Error: {str(e)}&quot;}), 500</pre><p>This code will take user document and apply the autogen function.</p><h3>Frontend</h3><p>I am using React for the frontend. The front end is interactive platform where a user uploads its contract document and chat with the document by utilizing the contract assistant bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkQHzflH9BavsBpsXaOrCA.png" /><figcaption>Frontend</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wh7Uwm2JQyEsauhl53MrUw.png" /></figure><h3>Future Plan</h3><ul><li>Explore other strategies to improve RAG performance (Reranking mechanisms and other chunking mechanisms)</li><li>Using websocket at the backend to improve responce time</li><li>More test using multiple documents</li><li>Context viewing option on the frontend</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaeb14d72ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crypto Trading Engineering: Scalable Backtesting Infrastructure]]></title>
            <link>https://medium.com/@jabezkassa2022/crypto-trading-engineering-scalable-backtesting-infrastructure-666e8f0fce14?source=rss-d458394c7447------2</link>
            <guid isPermaLink="false">https://medium.com/p/666e8f0fce14</guid>
            <dc:creator><![CDATA[Jabezkassa]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 19:45:20 GMT</pubDate>
            <atom:updated>2024-06-26T19:45:20.213Z</atom:updated>
            <content:encoded><![CDATA[<h3>Business Need</h3><p>A startup called Mela wants to make it simple for everyone to enter the world of cryptocurrencies. It also wants to give investors a reliable source of investment while lowering the risk associated with trading cryptocurrencies. This week’s task is straightforward: design and build a reliable, large-scale trading data pipeline.</p><p>Although the past performance of any financial market is never a reliable indicator of the future, it is important to run backtests that simulate current and past particular situations as well as their trend over time. Having a clear understanding of the financial system, and stock market trading, and recognizing the complex data engineering systems involved in the crypto and general stock market trading systems are essential.</p><h3>Tech stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3a_HyhlajRQFUESiRSitQ.png" /></figure><ul><li><strong>React:</strong> We used react for the interactive frontend development.</li><li><strong>Flask:</strong> This framework helps us connect the user interface (frontend) to the data and processing engine (backend).</li><li><strong>Kafka:</strong> This is an event streaming platform that enables efficient data flow, especially when multiple users need to access the database.</li><li><strong>PostgreSQL:</strong> We use this database management system to store and load our data.</li><li><strong>Backtrader:</strong> This Python library allows us to perform backtesting on our investment strategies.</li><li><strong>PyPortfolioOpt:</strong> This library helps us create well-diversified investment portfolios using optimization techniques.</li><li><strong>Choronos:</strong> This is a time series forecasting tool that leverages a language model.</li><li><strong>Yahoo finance:</strong> We used yahoo finance to get the historical data for cryptocurrency</li></ul><h3>Schema for the database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vBnnwq2lUNeDkKxB" /></figure><p>For this project we used historical data for cryptocurrency between July 20 2023 till July 20 2024.</p><h3>Backtesting</h3><p>Backtesting is the general method for seeing how well a strategy or model would have done after the fact. It assesses the viability of a <a href="https://www.investopedia.com/terms/t/trading-strategy.asp">trading strategy</a> by discovering how it would play out using historical data. Backtesting allows a trader to simulate a trading strategy using <a href="https://www.investopedia.com/terms/h/historical-returns.asp">historical data</a> to generate results and analyze risk and profitability before risking any actual capital.</p><p>A well-conducted backtest that yields positive results assures <a href="https://www.investopedia.com/terms/t/trader.asp">traders</a> that the strategy is fundamentally sound and is likely to yield profits when implemented in reality. In contrast, a well-conducted backtest that yields suboptimal results will prompt traders to alter or reject the strategy.</p><h3>Backtest strategies</h3><p>We used and tested the following strategies in this project.</p><ul><li><strong>SMAStrategy (Simple Moving Average Strategy):</strong> This strategy uses the Simple Moving Average (SMA) of a security’s price to generate buy and sell signals. A buy signal might occur when the price crosses above the SMA, and a sell signal when it falls below.</li><li><strong>EMAStrategy (Exponential Moving Average Strategy):</strong> Similar to SMAStrategy, but it uses the Exponential Moving Average (EMA) which gives more weight to recent prices. This can help capture trends quicker but can also be more prone to whipsaws (false signals).</li><li><strong>RSIStrategy (Relative Strength Index Strategy):</strong> This strategy uses the Relative Strength Index (RSI) indicator, which measures the momentum of price changes. A buy signal might be generated when RSI is low (indicating oversold), and a sell signal when it’s high (indicating overbought).</li><li><strong>BollingerBandsStrategy:</strong> This strategy uses Bollinger Bands, which consist of a moving average (usually the SMA) with two bands above and below it. The bands expand and contract based on volatility. A buy signal might be generated when the price breaks below the lower band (oversold), and a sell signal when it breaks above the upper band (overbought).</li><li><strong>AroonOscillatorStrategy:</strong> This strategy uses the Aroon Oscillator, which identifies the number of periods since a price high (Aroon Up) or low (Aroon Down) occurred. A buy signal might be based on a rising Aroon Up, and a sell signal on a rising Aroon Down.</li><li><strong>StochasticOscillatorStrategy:</strong> This strategy uses the Stochastic Oscillator, which compares the closing price of a security to its price range over a specific period. A buy signal might be generated when the Stochastic Oscillator is low (oversold), and a sell signal when it’s high (overbought).</li></ul><h3>Backtrader</h3><p>Backtrader is a popular open-source Python library specifically designed for backtesting trading strategies. It provides a framework that simplifies the process of developing, testing, and evaluating your algorithmic trading ideas.</p><pre>from itertools import product<br>import datetime<br>import json<br>import backtrader as bt<br>import matplotlib.pyplot as plt<br><br># Define Strategies<br>class SMAStrategy(bt.Strategy):<br>    params = ((&#39;period&#39;, 15), (&#39;stop_loss&#39;, 0.02))<br><br>    def __init__(self):<br>        self.sma = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.period)<br>        self.atr = bt.indicators.ATR(self.data, period=14)<br><br>    def next(self):<br>        if len(self.data) &lt; self.params.period:<br>            return<br>        if not self.position:<br>            if self.data.close[0] &gt; self.sma[0]:<br>                size = int(self.broker.cash / self.data.close[0])<br>                self.buy(size=size)<br>                self.stop_price = self.data.close[0] - self.atr[0] * self.params.stop_loss<br>        else:<br>            if self.data.close[0] &lt; self.sma[0] or self.data.close[0] &lt; self.stop_price:<br>                self.sell(size=self.position.size)<br><br>class EMAStrategy(bt.Strategy):<br>    params = ((&#39;period&#39;, 15), (&#39;stop_loss&#39;, 0.02))<br><br>    def __init__(self):<br>        self.ema = bt.indicators.ExponentialMovingAverage(self.data.close, period=self.params.period)<br>        self.atr = bt.indicators.ATR(self.data, period=14)<br><br>    def next(self):<br>        if len(self.data) &lt; self.params.period:<br>            return<br>        if not self.position:<br>            if self.data.close[0] &gt; self.ema[0]:<br>                size = int(self.broker.cash / self.data.close[0])<br>                self.buy(size=size)<br>                self.stop_price = self.data.close[0] - self.atr[0] * self.params.stop_loss<br>        else:<br>            if self.data.close[0] &lt; self.ema[0] or self.data.close[0] &lt; self.stop_price:<br>                self.sell(size=self.position.size)<br><br>class RSIStrategy(bt.Strategy):<br>    params = ((&#39;rsi_period&#39;, 14), (&#39;stop_loss&#39;, 0.02))<br><br>    def __init__(self):<br>        self.rsi = bt.indicators.RSI(self.data.close, period=self.params.rsi_period)<br>        self.atr = bt.indicators.ATR(self.data, period=14)<br><br>    def next(self):<br>        if not self.position:<br>            if self.rsi[0] &lt; 30:<br>                size = int(self.broker.cash / self.data.close[0])<br>                self.buy(size=size)<br>                self.stop_price = self.data.close[0] - self.atr[0] * self.params.stop_loss<br>        else:<br>            if self.rsi[0] &gt; 70 or self.data.close[0] &lt; self.stop_price:<br>                self.sell(size=self.position.size)<br><br>class BollingerBandsStrategy(bt.Strategy):<br>    params = ((&#39;period&#39;, 20), (&#39;devfactor&#39;, 2.0), (&#39;stop_loss&#39;, 0.02))<br><br>    def __init__(self):<br>        self.bbands = bt.indicators.BollingerBands(self.data.close, period=self.params.period, devfactor=self.params.devfactor)<br>        self.atr = bt.indicators.ATR(self.data, period=14)<br><br>    def next(self):<br>        if not self.position:<br>            if self.data.close[0] &lt; self.bbands.lines.bot[0]:<br>                size = int(self.broker.cash / self.data.close[0])<br>                self.buy(size=size)<br>                self.stop_price = self.data.close[0] - self.atr[0] * self.params.stop_loss<br>        else:<br>            if self.data.close[0] &gt; self.bbands.lines.top[0] or self.data.close[0] &lt; self.stop_price:<br>                self.sell(size=self.position.size)<br><br>class AroonOscillatorStrategy(bt.Strategy):<br>    params = ((&#39;period&#39;, 25), (&#39;stop_loss&#39;, 0.02))<br><br>    def __init__(self):<br>        self.aroon = bt.indicators.AroonOscillator(self.data, period=self.params.period)<br>        self.atr = bt.indicators.ATR(self.data, period=14)<br><br>    def next(self):<br>        if not self.position:<br>            if self.aroon[0] &gt; 0:<br>                size = int(self.broker.cash / self.data.close[0])<br>                self.buy(size=size)<br>                self.stop_price = self.data.close[0] - self.atr[0] * self.params.stop_loss<br>        else:<br>            if self.aroon[0] &lt; 0 or self.data.close[0] &lt; self.stop_price:<br>                self.sell(size=self.position.size)<br><br>class StochasticOscillatorStrategy(bt.Strategy):<br>    params = ((&#39;percK&#39;, 14), (&#39;percD&#39;, 3), (&#39;stop_loss&#39;, 0.02))<br><br>    def __init__(self):<br>        self.stochastic = bt.indicators.Stochastic(self.data, period=self.params.percK, period_dfast=self.params.percD)<br>        self.atr = bt.indicators.ATR(self.data, period=14)<br><br>    def next(self):<br>        if not self.position:<br>            if self.stochastic.percK[0] &gt; self.stochastic.percD[0]:<br>                size = int(self.broker.cash / self.data.close[0])<br>                self.buy(size=size)<br>                self.stop_price = self.data.close[0] - self.atr[0] * self.params.stop_loss<br>        else:<br>            if self.stochastic.percK[0] &lt; self.stochastic.percD[0] or self.data.close[0] &lt; self.stop_price:<br>                self.sell(size=self.position.size)<br><br># Metrics Analyzer (unchanged)<br>class MetricsAnalyzer(bt.Analyzer):<br>    def __init__(self):<br>        self.total_return = 0.0<br>        self.trades = 0<br>        self.winning_trades = 0<br>        self.losing_trades = 0<br>        self.max_drawdown = 0.0<br>        self.sharpe_ratio = 0.0<br><br>    def start(self):<br>        self.init_cash = self.strategy.broker.startingcash<br><br>    def stop(self):<br>        self.total_return = (self.strategy.broker.getvalue() / self.init_cash - 1.0) * 100<br><br>        # Handle strategies with TradeAnalyzer<br>        trade_analysis = self.strategy.analyzers.trade_analyzer.get_analysis()<br>        if trade_analysis:<br>            self.trades = trade_analysis.total.total<br>            self.winning_trades = trade_analysis.won.total<br>            self.losing_trades = trade_analysis.lost.total<br><br>        # Handle max drawdown<br>        drawdown_analysis = self.strategy.analyzers.drawdown.get_analysis()<br>        if drawdown_analysis:<br>            self.max_drawdown = drawdown_analysis[&#39;max&#39;][&#39;drawdown&#39;]<br><br>        # Handle Sharpe ratio<br>        sharpe_ratio_analysis = self.strategy.analyzers.sharpe_ratio.get_analysis()<br>        if sharpe_ratio_analysis:<br>            self.sharpe_ratio = sharpe_ratio_analysis[&#39;sharperatio&#39;]<br><br><br>def run_backtest(strategy_class, strategy_params, data_path, fromdate, todate, cash):<br>    cerebro = bt.Cerebro()<br>    cerebro.addstrategy(strategy_class, **strategy_params)<br>    data = bt.feeds.GenericCSVData(dataname=data_path, nullvalue=0.0, dtformat=(&#39;%Y-%m-%d&#39;), datetime=0, open=1, high=2, low=3, close=4, volume=5, adjclose=6, fromdate=fromdate, todate=todate)<br>    cerebro.adddata(data)<br>    cerebro.broker.setcash(cash)<br>    cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name=&#39;trade_analyzer&#39;)<br>    cerebro.addanalyzer(bt.analyzers.DrawDown, _name=&#39;drawdown&#39;)<br>    cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name=&#39;sharpe_ratio&#39;)<br>    cerebro.addanalyzer(MetricsAnalyzer, _name=&#39;metrics&#39;)<br><br>    try:<br>        result = cerebro.run()<br>        metrics = result[0].analyzers.metrics<br><br>        # Print and display results<br>        print(f&quot;Starting Portfolio Value: {cash}&quot;)<br>        print(f&quot;Ending Portfolio Value: {cerebro.broker.getvalue():.2f}&quot;)<br>        print(f&quot;Total Return: {metrics.total_return:.2f}%&quot;)<br>        print(f&quot;Number of Trades: {metrics.trades}&quot;)<br>        print(f&quot;Winning Trades: {metrics.winning_trades}&quot;)<br>        print(f&quot;Losing Trades: {metrics.losing_trades}&quot;)<br>        print(f&quot;Max Drawdown: {metrics.max_drawdown:.2f}%&quot;)<br>        print(f&quot;Sharpe Ratio: {metrics.sharpe_ratio:.2f}&quot;)<br><br>        # Plot the strategy<br>        cerebro.plot(style=&#39;candle&#39;, volume=False, barup=&#39;lightgreen&#39;, bardown=&#39;red&#39;)<br>    except Exception as e:<br>        print(f&quot;An error occurred during backtesting: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    # Prompt for user input<br>    data_path = input(&quot;Enter data path: &quot;).strip()<br>    cash = float(input(&quot;Enter starting cash amount: &quot;).strip())<br><br>    # Load other configurations from JSON<br>    with open(&#39;../backtest/backtest_config.json&#39;, &#39;r&#39;) as f:<br>        config = json.load(f)<br><br>    for date_range in config[&#39;date_ranges&#39;]:<br>        fromdate = datetime.datetime.strptime(date_range[&#39;fromdate&#39;], &#39;%Y-%m-%d&#39;)<br>        todate = datetime.datetime.strptime(date_range[&#39;todate&#39;], &#39;%Y-%m-%d&#39;)<br><br>        for strategy_conf in config[&#39;strategies&#39;]:<br>            strategy_name = strategy_conf[&#39;name&#39;]<br>            params = strategy_conf.get(&#39;params&#39;, {})<br>            strategy_class = globals().get(strategy_name)<br><br>            if not strategy_class:<br>                print(f&quot;Strategy {strategy_name} not found.&quot;)<br>                continue<br><br>            # Generate all possible combinations of parameters<br>            try:<br>                param_combinations = list(product(*[params[key][&#39;range&#39;] for key in params])) or [()]<br>            except KeyError as e:<br>                print(f&quot;Missing &#39;range&#39; for parameter {e} in strategy {strategy_name}&quot;)<br>                continue<br><br>            for param_set in param_combinations:<br>                strategy_params = {key: value for key, value in zip(params.keys(), param_set)}<br>                print(f&quot;\nTesting {strategy_name} with params: {strategy_params}&quot;)<br>                run_backtest(strategy_class, strategy_params, data_path, fromdate, todate, cash)</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*eJ_4adrU0TnEnmGX" /></figure><h3>Index fund</h3><p>Where able to get the market capitalization for top ten coins using api.coingecko.com.</p><pre>API_URL = &#39;https://api.coingecko.com/api/v3/coins/markets&#39;<br>params = {<br>    &#39;vs_currency&#39;: &#39;usd&#39;,<br>    &#39;order&#39;: &#39;market_cap_desc&#39;,<br>    &#39;per_page&#39;: 100,<br>    &#39;page&#39;: 1,<br>    &#39;sparkline&#39;: &#39;false&#39;<br>}<br>crypto_data = index_fund.fetch_crypto_data()<br>filtered_data = index_fund.filter_stable_coins(crypto_data)<br>top_10_coins = index_fund.get_top_10_coins(filtered_data)<br>for coin in top_10_coins:<br>    print(f&quot;{coin[&#39;name&#39;]} - Market Cap: {coin[&#39;market_cap&#39;]}&quot;)</pre><p>Result:</p><pre>Bitcoin - Market Cap: 1264437167212<br>Ethereum - Market Cap: 430459669984<br>BNB - Market Cap: 90182343844<br>Solana - Market Cap: 61642775876<br>Lido Staked Ether - Market Cap: 33695847115<br>XRP - Market Cap: 27027852604<br>Dogecoin - Market Cap: 17990656167<br>Toncoin - Market Cap: 17527993798<br>Cardano - Market Cap: 13385266286<br>Avalanche - Market Cap: 10858861109</pre><p>Then we calculate an index based on the market capitalization:</p><pre>index = index_fund.rebalance_index()<br>print(&quot;Initial Index Weights:&quot;, index)<br>df = pd.DataFrame(list(index.items()), columns=[&#39;Cryptocurrency&#39;, &#39;Weight&#39;])<br>df.set_index(&#39;Cryptocurrency&#39;, inplace=True)<br><br># Print DataFrame<br>print(df)</pre><p>Result</p><pre>                    Weight<br>Cryptocurrency            <br>bitcoin           0.642757<br>ethereum          0.218818<br>binancecoin       0.045843<br>solana            0.031335<br>staked-ether      0.017129<br>ripple            0.013739<br>dogecoin          0.009145<br>the-open-network  0.008910<br>cardano           0.006804<br>avalanche-2       0.005520</pre><h3>Best Strategy</h3><pre>import sys<br>import os<br>import backtrader as bt<br>import datetime<br>import json<br>import math<br><br>sys.path.append(os.path.join(os.getcwd(), &#39;/home/jabez/Documents/week_9/Crypto-Trading-Engineering/backtest&#39;))<br>from backtest import MetricsAnalyzer<br>from backtest import SMAStrategy <br>from backtest import SMAStrategy <br>from backtest import EMAStrategy<br>from backtest import RSIStrategy<br>from backtest import BollingerBandsStrategy<br>from backtest import AroonOscillatorStrategy<br>from backtest import StochasticOscillatorStrategy<br><br>import backtest<br><br><br># Load configuration<br>with open(&#39;backtest_config.json&#39;, &#39;r&#39;) as f:<br>    config = json.load(f)<br><br>data_path = config[&#39;data_path&#39;]<br>fromdate = datetime.datetime.strptime(config[&#39;fromdate&#39;], &#39;%Y-%m-%d&#39;)<br>todate = datetime.datetime.strptime(config[&#39;todate&#39;], &#39;%Y-%m-%d&#39;)<br>cash = config[&#39;cash&#39;]<br><br>def execute_backtest(strategy, data_path, fromdate, todate, cash, params):<br>    # Placeholder function to execute the backtest<br>    # Replace with actual backtest logic<br>    print(f&quot;Executing backtest for strategy {strategy.__name__}&quot;)<br>    print(f&quot; From: {fromdate}, To: {todate}, Cash: {cash}, Params: {params}&quot;)<br>    # Add the code to actually run the backtest with the given parameters<br><br>def run_strategy(data_path, fromdate, todate, cash):<br>    best_score = float(&#39;-inf&#39;)<br>    best_strategy = None<br>    <br>    for strategy_conf in config[&#39;strategies&#39;]:<br>        strategy_name = strategy_conf[&#39;name&#39;]<br>        params = strategy_conf.get(&#39;params&#39;, {})<br>        strategy = globals().get(strategy_name)<br>        <br>        if strategy is not None:<br>            print(f&quot;Running backtest for {strategy_name}&quot;)<br>            score = backtest.run_backtest(strategy, data_path, fromdate, todate, cash, params)<br>            <br>            if score is not None and score &gt; best_score:<br>                score = backtest.run_backtest(strategy, data_path, fromdate, todate, cash, params)<br>                best_score = score<br>                best_strategy = strategy_name<br>        else:<br>            print(f&quot;Strategy {strategy_name} not found.&quot;)<br>    <br>    if best_strategy is not None:<br>        print(f&quot;Best Strategy: {best_strategy} with Score: {best_score:.2f}&quot;)<br>    else:<br>        print(&quot;No valid strategy found.&quot;)<br>        <br>run_strategy(data_path, fromdate, todate, cash)</pre><p>Result</p><h3>Modern Portfolio</h3><p><em>‘don’t put all your egg in one bascket’</em></p><p>The modern portfolio theory (MPT) is a practical method for selecting investments in order to maximize their overall returns within an acceptable level of risk. This mathematical framework is used to build a portfolio of investments that maximize the amount of expected return for the collective given level of risk.</p><p>A key component of the MPT theory is diversification. Most investments are either high risk and high return or low risk and low return. <a href="https://www.investopedia.com/managing-wealth/modern-portfolio-theory-why-its-still-hip/">Markowitz argued</a> that investors could achieve their best results by choosing an optimal mix of the two based on an assessment of their individual tolerance to risk.</p><p>We used PyPortfolioOpt library to build the modern portfolio.</p><p><strong>PyPortfolioOpt</strong> is a library that implements portfolio optimization methods, including classical efficient frontier techniques and Black-Litterman allocation, as well as more recent developments in the field like shrinkage and Hierarchical Risk Parity, along with some novel experimental features like exponentially-weighted covariance matrices.</p><p>It is <strong>extensive</strong> yet easily <strong>extensible</strong>, and can be useful for both the casual investor and the serious practitioner. Whether you are a fundamentals-oriented investor who has identified a handful of undervalued picks, or an algorithmic trader who has a basket of strategies, PyPortfolioOpt can help you combine your alpha sources in a risk-efficient way.</p><pre>from pypfopt.efficient_frontier import EfficientFrontier<br>from pypfopt import risk_models<br>from pypfopt import expected_returns<br><br>def lowrisk_porfolio(df):<br>    mu = expected_returns.mean_historical_return(df)<br>    sigma = risk_models.sample_cov(df)<br><br>    # Create an Efficient Frontier object<br>    ef_low_risk = EfficientFrontier(mu, sigma)<br><br>    # Optimize for the minimum volatility<br>    weights_low_risk = ef_low_risk.min_volatility()<br><br>    # Clean the weights<br>    cleaned_weights_low_risk = ef_low_risk.clean_weights()<br><br>    # Display the optimized weights<br>    print(&quot;Weights for Lowest Risk Portfolio:&quot;)<br>    print(cleaned_weights_low_risk)<br>    # Portfolio performance<br>    performance_low_risk = ef_low_risk.portfolio_performance(verbose=True)<br>    <br>    expected_return = performance_low_risk[0] * 100  # Converting to percentage<br>    annual_volatility = performance_low_risk[1] * 100  # Converting to percentage<br>    sharpe_ratio = performance_low_risk[2]<br>    expected_return =f&#39;{round(expected_return, ndigits=0)}%&#39;<br>    annual_volatility =f&#39;{round(annual_volatility, ndigits=0)}%&#39;<br>    sharpe_ratio =f&#39;{round(sharpe_ratio, ndigits=0)}%&#39;<br><br>    return {<br>        &quot;weights&quot;: cleaned_weights_low_risk ,<br>        &quot;expected_return&quot;: expected_return,<br>        &quot;annual_volatility&quot;: annual_volatility,<br>        &quot;sharpe_ratio&quot;: sharpe_ratio<br>    }<br><br>def ef_portfolio(df):<br>    mu = expected_returns.mean_historical_return(df)<br>    sigma = risk_models.sample_cov(df)<br>    <br>    # Create an Efficient Frontier object<br>    ef_high_sharpe = EfficientFrontier(mu, sigma)<br>    <br>    # Optimize for the maximal Sharpe ratio<br>    weights_high_sharpe = ef_high_sharpe.max_sharpe()<br>    <br>    # Clean the weights<br>    cleaned_weights_high_sharpe = ef_high_sharpe.clean_weights()<br>    <br>    # Portfolio performance<br>    performance_high_sharpe = ef_high_sharpe.portfolio_performance(verbose=False)<br>    <br>    # Format the performance metrics<br>    <br>    expected_return = performance_high_sharpe[0] * 100  # Converting to percentage<br>    annual_volatility = performance_high_sharpe[1] * 100  # Converting to percentage<br>    sharpe_ratio = performance_high_sharpe[2]<br>    expected_return =f&#39;{round(expected_return, ndigits=0)}%&#39;<br>    annual_volatility =f&#39;{round(annual_volatility, ndigits=0)}%&#39;<br>    sharpe_ratio =f&#39;{round(sharpe_ratio, ndigits=0)}%&#39;<br><br>    return {<br>        &quot;weights&quot;: cleaned_weights_high_sharpe,<br>        &quot;expected_return&quot;: expected_return,<br>        &quot;annual_volatility&quot;: annual_volatility,<br>        &quot;sharpe_ratio&quot;: sharpe_ratio<br>    }<br>print(portfolio.ef_portfolio(df))</pre><p>Result for highest sharp ratio:</p><pre>{&#39;weights&#39;: OrderedDict([(&#39;btc_price&#39;, 0.0),<br>              (&#39;eth_price&#39;, 0.0),<br>              (&#39;bnb_price&#39;, 0.02788),<br>              (&#39;sol_price&#39;, 0.97212),<br>              (&#39;xrp_price&#39;, 0.0)]),<br> &#39;expected_return&#39;: 312.8050244079461,<br> &#39;annual_volatility&#39;: 74.37351390600017,<br> &#39;sharpe_ratio&#39;: 4.178974584968097}</pre><ul><li>Expected Annual Return: 312.8% — This is an extremely high expected return, indicating significant growth potential for this portfolio.</li><li>Annual Volatility: 74.4% — This high volatility represents the significant risk associated with this portfolio. It means the portfolio’s returns can deviate substantially from the expected return.</li><li>Sharpe Ratio: 4.18 — A Sharpe ratio of 4.18 is exceptionally high, suggesting that the portfolio provides a very high return per unit of risk taken.</li></ul><p><strong>Result for low risk:</strong></p><pre>Weights for Lowest Risk Portfolio:<br>OrderedDict([(&#39;btc_price&#39;, 0.55541), (&#39;eth_price&#39;, 0.06774), (&#39;bnb_price&#39;, 0.36069), (&#39;sol_price&#39;, 0.0), (&#39;xrp_price&#39;, 0.01616)])<br>Expected annual return: 75.9%<br>Annual volatility: 36.2%<br>Sharpe Ratio: 2.04</pre><p><strong>Interpretation of Results</strong></p><ul><li>Expected Annual Return: 75.9% — This is a high expected return, indicating that the portfolio has significant growth potential.</li><li>Annual Volatility: 36.2% — This represents the portfolio’s risk, showing how much the returns can deviate from the expected return. A volatility of 36.2% is — — relatively high, reflecting the inherent risk of investing in volatile cryptocurrencies.</li><li>Sharpe Ratio: 2.04 — A Sharpe ratio of 2.04 is very good, indicating that the portfolio offers a high return for each unit of risk taken. Generally, a Sharpe — ratio above 1 is considered good, above 2 is very good, and above 3 is excellent.</li></ul><p><strong>Practical Use of Results</strong></p><ul><li>Portfolio Allocation: The portfolio is almost entirely allocated to Solana (SOL), with a small fraction in Binance Coin (BNB). This suggests that, according to the optimization process, Solana provides the best risk-adjusted return within the context of the available data.</li><li>Investment Decision: While this portfolio offers high potential returns, it is also very risky due to its concentration in a single asset. Investors should carefully consider their risk tolerance and investment horizon before adopting such a strategy.</li></ul><h3>Chronos</h3><p>Chronos is a family of pretrained time series forecasting models based on language model architectures. A time series is transformed into a sequence of tokens via scaling and quantization, and a language model is trained on these tokens using the cross-entropy loss. Once trained, probabilistic forecasts are obtained by sampling multiple future trajectories given the historical context. Chronos models have been trained on a large corpus of publicly available time series data, as well as synthetic data generated using Gaussian processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m_gre7_YFSYHJKfc.png" /><figcaption>High-level depiction of Chronos. (Left) The input time series is scaled and quantized to obtain a sequence of tokens. (Center) The tokens are fed into a language model which may either be an encoder-decoder or a decoder-only model. The model is trained using the cross-entropy loss. (Right) During inference, we autoregressively sample tokens from the model and map them back to numerical values. Multiple trajectories are sampled to obtain a predictive distribution.</figcaption></figure><pre>import pandas as pd<br>import torch<br>from chronos import ChronosPipeline<br>import plotly.graph_objs as go<br>import numpy as np<br><br>def data_preparation(df):<br>    df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;])<br>    df.set_index(&#39;date&#39;, inplace=True)<br>    context = torch.tensor(df[&quot;close&quot;].values, dtype=torch.float32)<br>    return context<br><br>def generate_forecast_dates(df):<br>    last_date = df.index[-1]<br>    forecast_dates = pd.date_range(last_date, periods=12 + 1, freq=&#39;D&#39;)[1:]<br>    return forecast_dates<br><br>def predict(name, df, forecast_dates, context):<br>    pipeline = ChronosPipeline.from_pretrained(<br>        &quot;amazon/chronos-t5-small&quot;,<br>        device_map=&quot;cpu&quot;,<br>        torch_dtype=torch.float32,<br>    )<br>    forecast = pipeline.predict(<br>        context=context.unsqueeze(0),<br>        prediction_length=12,<br>        num_samples=20,<br>    )<br>    forecast_values = forecast[0].cpu().numpy()<br>    low, median, high = np.percentile(forecast_values, [10, 50, 90], axis=0)<br><br>    fig = go.Figure()<br>    fig.add_trace(go.Scatter(x=df.index, y=df[&quot;close&quot;], mode=&#39;lines&#39;, name=&#39;Historical Data&#39;))<br>    fig.add_trace(go.Scatter(x=forecast_dates, y=median, mode=&#39;lines&#39;, name=&#39;Forecast&#39;))<br>    fig.add_trace(go.Scatter(x=forecast_dates, y=low, fill=None, mode=&#39;lines&#39;, line_color=&#39;lightgray&#39;, showlegend=False))<br>    fig.add_trace(go.Scatter(x=forecast_dates, y=high, fill=&#39;tonexty&#39;, mode=&#39;lines&#39;, line_color=&#39;lightgray&#39;, showlegend=False))<br><br>    fig.update_layout(title=f&quot;{name}-USD Close Price Forecast&quot;, xaxis_title=&quot;Date&quot;, yaxis_title=&quot;Price&quot;)<br><br>    return fig</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*RZr3WC7QnxEJJB6jn8h9Qw.png" /></figure><p>In order to see the accurecy we predicted the date that we actually have the ground truth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywNM649fE02P3WB19iMi7Q.png" /></figure><p>For example we can see that for jun 12 2024 the actual closing price is 68,241.19 and the prediction value is 64,886.6 which is off by $ 3,354.4.</p><h3>moirai-1.0-R-large</h3><p>Moirai, the Masked Encoder-based Universal Time Series Forecasting Transformer is a Large Time Series Model pre-trained on <a href="https://huggingface.co/datasets/Salesforce/lotsa_data">LOTSA data</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-DSqNL9oWiG2qwQd.png" /><figcaption>Overall architecture of Moirai. Visualized is a 3-variate time series, where variates 0 and 1 are target variables (i.e. to be forecasted, and variate 2 is a dynamic covariate (values in forecast horizon known). Based on a patch size of 64, each variate is patchified into 3 tokens. The patch embeddings along with sequence and variate id are fed into the Transformer. The shaded patches represent the forecast horizon to be forecasted, whose corresponding output representations are mapped into the mixture distribution parameters.</figcaption></figure><pre>import torch<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>from gluonts.dataset.pandas import PandasDataset<br>from gluonts.dataset.split import split<br>from uni2ts.eval_util.plot import plot_single<br>from uni2ts.model.moirai import MoiraiForecast, MoiraiModule<br>import plotly.graph_objs as go<br><br># Function to plot a single time series with forecast and ground truth<br>def plot_single_interactive(input_data, label_data, forecast_data, context_length, name=&quot;pred&quot;, show_label=True):<br>    # Check if &#39;time&#39; key is present in input_data<br>    if &#39;time&#39; in input_data:<br>        time_idx = pd.date_range(start=input_data[&quot;time&quot;][0], periods=len(input_data[&quot;target&quot;]) + len(forecast_data.samples[0]), freq=&quot;D&quot;)<br>    else:<br>        time_idx = pd.date_range(start=&quot;2024-01-01&quot;, periods=len(input_data[&quot;target&quot;]) + len(forecast_data.samples[0]), freq=&quot;D&quot;)  # Replace with appropriate start date<br>    <br>    # Plotting observed data<br>    trace_observed = go.Scatter(<br>        x=time_idx[:len(input_data[&quot;target&quot;])],<br>        y=input_data[&quot;target&quot;],<br>        mode=&quot;lines+markers&quot;,<br>        name=&quot;Observed&quot;,<br>        line=dict(color=&#39;blue&#39;),<br>    )<br>    <br>    # Plotting ground truth data if available<br>    if label_data is not None:<br>        trace_label = go.Scatter(<br>            x=time_idx[len(input_data[&quot;target&quot;]):],<br>            y=label_data[&quot;target&quot;],<br>            mode=&quot;lines+markers&quot;,<br>            name=&quot;Ground Truth&quot;,<br>            line=dict(color=&#39;green&#39;),<br>        )<br>    else:<br>        trace_label = None<br>    <br>    # Plotting forecasted data<br>    trace_forecast = go.Scatter(<br>        x=time_idx[len(input_data[&quot;target&quot;]):],<br>        y=forecast_data.samples[0],<br>        mode=&quot;lines+markers&quot;,<br>        name=&quot;Forecast&quot;,<br>        line=dict(color=&#39;red&#39;),<br>    )<br>    <br>    # Create plot data list<br>    plot_data = [trace_observed]<br>    if trace_label:<br>        plot_data.append(trace_label)<br>    plot_data.append(trace_forecast)<br>    <br>    # Create layout<br>    layout = go.Layout(<br>        title=&quot;Interactive Forecast Plot&quot;,<br>        xaxis=dict(title=&quot;Time&quot;),<br>        yaxis=dict(title=&quot;Value&quot;),<br>        hovermode=&#39;closest&#39;<br>    )<br>    <br>    # Create figure and plot<br>    fig = go.Figure(data=plot_data, layout=layout)<br>    fig.show()<br><br>def moirai_forecast(df):<br>    # Ensure the &#39;Date&#39; column is in datetime format and set it as index<br>    df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;])<br>    df.set_index(&#39;date&#39;, inplace=True)<br><br>    SIZE = &quot;small&quot;  # model size: choose from {&#39;small&#39;, &#39;base&#39;, &#39;large&#39;}<br>    PDT = 20  # prediction length: any positive integer<br>    CTX = 200  # context length: any positive integer<br>    PSZ = &quot;auto&quot;  # patch size: choose from {&quot;auto&quot;, 8, 16, 32, 64, 128}<br>    BSZ = 32  # batch size: any positive integer<br>    TEST = 100  # test set length: any positive integer<br><br>    # Convert into GluonTS dataset<br>    target_column = df[&#39;close&#39;]  # Use the &#39;close&#39; column as the target<br>    df_gluon = df[[&#39;close&#39;]]  # Create a DataFrame with only the target column for GluonTS<br>    ds = PandasDataset(dict(df_gluon), target=&#39;close&#39;)<br><br>    # Parameters<br>    PDT = 20  # prediction length<br>    CTX = 200  # context length<br>    PSZ = &quot;auto&quot;  # patch size<br>    BSZ = 32  # batch size<br>    TEST = 100  # test set length<br><br>    # Split into train/test set<br>    train, test_template = split(ds, offset=-TEST)<br><br>    # Construct rolling window evaluation<br>    test_data = test_template.generate_instances(<br>        prediction_length=PDT,<br>        windows=TEST // PDT,<br>        distance=PDT,<br>    )<br><br>    # Prepare pre-trained model<br>    model = MoiraiForecast(<br>        module=MoiraiModule.from_pretrained(f&quot;Salesforce/moirai-1.0-R-{SIZE}&quot;),<br>        prediction_length=PDT,<br>        context_length=CTX,<br>        patch_size=PSZ,<br>        num_samples=100,<br>        target_dim=1,<br>        feat_dynamic_real_dim=ds.num_feat_dynamic_real,<br>        past_feat_dynamic_real_dim=ds.num_past_feat_dynamic_real,<br>    )<br><br>    # Create predictor and generate forecasts<br>    predictor = model.create_predictor(batch_size=BSZ)<br>    forecasts = predictor.predict(test_data.input)<br><br>    # Extract data for plotting<br>    input_it = iter(test_data.input)<br>    label_it = iter(test_data.label)<br>    forecast_it = iter(forecasts)<br><br>    inp = next(input_it)<br>    label = next(label_it, None)  # Handling case where label may be None<br>    forecast = next(forecast_it)<br><br>    # Plot using Plotly interactive plot function<br>    plot_single_interactive(inp, label, forecast, context_length=CTX, name=&quot;pred&quot;, show_label=True)</pre><p>Result for bitcoin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ymZFD4vBzPhzhCx3MLTBA.png" /></figure><h3>Frontend</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQxzj3kRVxGYfensVo4XgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RN07MglQBAnBdtlmi4xiFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DA57vcZByzhXws8EJA5giA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Cn_S42MklhmdseIaZziQw.png" /></figure><h3>Furure Plan</h3><ul><li>Fine tuning Choronos model for better accurecy</li><li>Improve frontend for better user interaction</li></ul><h3>Referance</h3><p><a href="https://www.investopedia.com/terms/b/backtesting.asp#:~:text=Backtesting%20is%20the%20general%20method,to%20employ%20it%20going%20forward">https://www.investopedia.com/terms/b/backtesting.asp#:~:text=Backtesting%20is%20the%20general%20method,to%20employ%20it%20going%20forward</a>.</p><p><a href="https://backtrader.com/">https://backtrader.com/</a></p><ul><li><a href="https://www.investopedia.com/terms/m/modernportfoliotheory.asp#:~:text=The%20modern%20portfolio%20theory%20(MPT)%20is%20a%20practical%20method%20for,an%20acceptable%20level%20of%20risk.&amp;text=A%20key%20component%20of%20the,low%20risk%20and%20low%20return.">Modern Portfolio Theory: What MPT Is and How Investors Use It</a></li><li><a href="https://pyportfolioopt.readthedocs.io/en/latest/">PyPortfolioOpt</a></li><li><a href="https://github.com/amazon-science/chronos-forecasting?tab=readme-ov-file">GitHub - amazon-science/chronos-forecasting: Chronos: Pretrained (Language) Models for Probabilistic Time Series Forecasting</a></li><li><a href="https://huggingface.co/Salesforce/moirai-1.0-R-large">Salesforce/moirai-1.0-R-large · Hugging Face</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666e8f0fce14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic optimization: Delivery drivers location optimisation with Causal Inference]]></title>
            <link>https://medium.com/@jabezkassa2022/logistic-optimization-delivery-drivers-location-optimisation-with-causal-inference-3549fc0b643b?source=rss-d458394c7447------2</link>
            <guid isPermaLink="false">https://medium.com/p/3549fc0b643b</guid>
            <dc:creator><![CDATA[Jabezkassa]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 18:52:47 GMT</pubDate>
            <atom:updated>2024-06-15T19:52:46.356Z</atom:updated>
            <content:encoded><![CDATA[<h3>Buisness need</h3><p><a href="https://www.gokada.ng/">Gokada</a> — the largest last mile delivery service in Nigeria. Gokada Works is partnered with motorbike owners and drivers to deliver parcels across Lagos, Nigeria. Gokada has completed more than a million deliveries in less than a year, with a fleet of over 1200 riders.</p><p>One key issue Gokada has faced as it expands its service is the sub-optimal placement of pilots (Gokada calls their motor drivers pilots) and clients who want to use Gokada to send their parcel. This has led to a high number of unfulfilled delivery requests.</p><p>Gokada is asking to help it understand the primary causes of unfulfilled requests as well as come up with solutions that recommend drivers locations that increase the fraction of complete orders. Since drivers are paid based on the number of requests they accept, the solution will help Gokada business grow both in terms of client satisfaction and increased business.</p><h3>Literature review</h3><h3>CasualNex</h3><p>I used CasualNex for this project to discover causality, estimation and do intervention.</p><p>CausalNex is a Python library that uses Bayesian Networks to combine machine learning and domain expertise for causal reasoning. You can use CausalNex to uncover structural relationships in your data, learn complex distributions, and observe the effect of potential interventions.</p><h3>Main features of CausalNex</h3><p>The CausalNex library has the following features:</p><p>Deploys state-of-the-art structure learning method, DAG with NO TEARS, to understand conditional dependencies between variables</p><ul><li>Allows domain knowledge to augment model relationships</li><li>Builds predictive models based on structural relationships</li><li>Understands model probability</li><li>Evaluates model quality with standard statistical checks</li><li>Visualization which simplifies how causality is understood</li><li>Analyses the impact of interventions using Do-calculus</li></ul><h3>Learning About CausalNex</h3><p>In the next few chapters, you will learn how to install and set up CausalNex, and how to use it on your own projects. Once you are set up, to get a feel for CausalNex, we suggest working through our example tutorial project. Advanced users looking for in-depth information should consult the User Guide. You can also check out the resources section for answers to frequently asked questions and the API reference documentation for further, detailed information.</p><h3>Assumptions</h3><p>We have designed the documentation in general, and the tutorial in particular, for beginners to get started using Bayesian Networks on their projects. If you an have elementary knowledge of Python and Bayesian Networks then you may find the CausalNex learning curve more challenging. However, we have simplified the tutorial by providing all the Python functions necessary to create your first CausalNex project.</p><p>There are two data for this project. The first data contains the trip id for accepted orders and other information like trip origin and destination locations, start and end time of the trip. The second data contains the order ID with the driver’s action which can be either accepted or rejection. The data also contain latitude and longitude of the location when the driver get the order and the deriver iD. There was also created at and updated at column but these columns are empty.</p><h3>Dowhy</h3><h3>Introduction to DoWhy</h3><p>DoWhy is a Python library that aims to facilitate causal analysis and reasoning. It provides a range of algorithms and methods for estimating causal effects, learning causal structures, conducting root cause analysis, and exploring counterfactuals. A key feature of DoWhy is its “refutation API” which can test the causal assumptions underlying any estimation method, making causal inference more robust and accessible even to non-experts.</p><p>DoWhy supports various causal identification methods such as backdoor, frontdoor, and instrumental variable approaches. It can also estimate conditional average treatment effects (CATE) through integration with the EconML library. Beyond effect estimation, DoWhy leverages graphical causal models to tackle broader causal questions like root cause analysis and quantifying causal influences.</p><p>Overall, DoWhy seems to be a comprehensive tool for conducting principled causal analysis, going beyond just predictive modeling to facilitate a deeper causal understanding of complex systems and phenomena.</p><h3>Supported causal tasks</h3><p>DoWhy’s API is organized around the key causal analysis tasks it enables users to perform:</p><ol><li>Estimating Causal Effects: Answering questions like “If I change the color of my button to red, how much will this change users’ purchase decisions?”</li><li>Quantifying Causal Influence: Determining the relative contribution of different factors to an outcome.</li><li>Root-Cause Analysis and Explanation: Identifying the underlying causes of an observed effect, such as “Which service in my distributed system has caused the frontend to be slower than usual?”</li><li>Asking and Answering What-If Questions: Exploring the effects of hypothetical interventions.</li><li>Predicting Outcomes for Out-of-Distribution Inputs: Making predictions that are robust to distribution shift.</li></ol><p>To perform these tasks, DoWhy leverages two powerful frameworks: graphical causal models (GCMs) and potential outcomes (PO). Regardless of the specific task, a key requirement is the availability of a causal graph that models the problem domain.</p><p>The breadth of causal analysis tasks supported by DoWhy’s API suggests it is a comprehensive tool for gaining a deeper, causal understanding of complex systems and phenomena, going beyond pure predictive modeling.</p><h3>Testing validity of a causal analysis</h3><p>Since causal tasks often concern interventional data distributions that are not directly observed, standard techniques like cross-validation from predictive modeling cannot be used to evaluate the validity of causal estimates. Therefore, DoWhy incorporates a crucial “refutation” process that tests the validity of causal assumptions at two stages: first, graph refutations challenge the assumptions encoded in the causal graph, which is a critical input for all downstream analysis; second, estimate refutations evaluate whether the causal analysis follows best practices, provides correct answers on special test data, and how robust the final estimate is to assumption violations. This refutation process, which goes beyond just predictive accuracy, is a distinguishing feature of DoWhy that helps ensure the soundness of causal inferences, making it a comprehensive tool for principled causal reasoning and analysis.</p><h3>XGBoost</h3><p>XGBoost is a highly efficient, flexible and portable distributed gradient boosting library that implements machine learning algorithms under the Gradient Boosting framework. It provides a parallel tree boosting (also known as GBDT, GBM) solution that can solve a wide range of data science problems in a fast and accurate manner. The same XGBoost code can run on major distributed environments like Hadoop, SGE, and MPI, and can handle problems with datasets containing billions of examples. XGBoost’s optimized design and ability to scale to large-scale distributed settings make it a powerful tool for tackling complex machine learning challenges across various domains.</p><h3>Overview of the data source and formats</h3><p>For this project, there are two datasets that I have access to. The first dataset contains information about the accepted orders, including the trip ID, the trip origin location, the trip destination location, the start time of the trip, and the end time of the trip.</p><p>The second dataset contains information about the drivers’ actions on the orders. This includes the order ID, whether the driver accepted or rejected the order, the latitude and longitude of the location when the driver received the order, and the driver’s ID. There are also “created at” and “updated at” columns, but those columns are currently empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVRA90sENOuB7OW4AxWVtA.png" /><figcaption>Trip Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJJLdbyZIQjCSfPfYp0-lA.png" /><figcaption>Location data</figcaption></figure><p>The objective of the project is to help Gokada understand the causes of unfulfiled requests and come up with a solution that recommend drivers location that increases the fraction of complete orders.</p><p>To do this I follow the following step:</p><p><strong>Step 1: Meging the two data</strong></p><p>The Trip id and the order id are the same. Therefore by using this common we can merge the two columns. But before the merge I prepared both the datas to have the same columns.</p><p>preparing the df_trip data</p><pre>df_org = df_trip[&#39;Trip Origin&#39;].str.split(&#39;,&#39;, expand=True)<br>df_org.columns = [&#39;lat_org&#39;, &#39;lon_org&#39;]<br><br><br># Combining the new columns with the original DataFrame<br>df_trip = pd.concat([df_trip, df_org], axis=1)<br>df_trip = df_trip.drop(&#39;Trip Origin&#39;, axis=1)<br><br>df_des = df_trip[&#39;Trip Destination&#39;].str.split(&#39;,&#39;, expand=True)<br>df_des.columns = [&#39;lat_des&#39;, &#39;lon_des&#39;]<br><br><br># # Combining the new columns with the original DataFrame<br>df_trip = pd.concat([df_trip, df_des], axis=1)<br>df_trip = df_trip.drop(&#39;Trip Destination&#39;, axis=1)<br><br><br>df_start = df_trip[&#39;Trip Start Time&#39;].str.split(&#39; &#39;, expand=True)<br>df_start.columns = [&#39;Start_date&#39;, &#39;Start_time&#39;]<br><br><br># Combining the new columns with the original DataFrame<br>df_trip = pd.concat([df_trip, df_start], axis=1)<br>df_trip = df_trip.drop(&#39;Trip Start Time&#39;, axis=1)<br><br>df_end = df_trip[&#39;Trip End Time&#39;].str.split(&#39; &#39;, expand=True)<br>df_end.columns = [&#39;End_date&#39;, &#39;End_time&#39;]<br><br># Combining the new columns with the original DataFrame<br>df_trip = pd.concat([df_trip, df_end], axis=1)<br>df_trip = df_trip.drop(&#39;Trip End Time&#39;, axis=1)<br>df_trip.rename(columns={&#39;Trip ID&#39;: &#39;order_id&#39;}, inplace=True)<br>df_trip.head(3)</pre><p>Preparing df_locations data</p><pre>df_locations.rename(columns={&#39;lat&#39;: &#39;lat_org&#39;}, inplace=True)<br>df_locations.rename(columns={&#39;lng&#39;: &#39;lon_org&#39;}, inplace=True)<br>df_trip.rename(columns={&#39;End_date&#39;: &#39;date&#39;}, inplace=True)<br><br># adding features to df_location<br>lat_lon = df_trip[[&#39;order_id&#39;,&#39;lat_des&#39;,&#39;lon_des&#39;,&#39;date&#39;]]<br>df_locations = df_locations.merge(lat_lon, on=&#39;order_id&#39;, how=&#39;left&#39;)<br>df_locations.drop(columns=[&#39;driver_id&#39;], inplace=True)<br>df_locations.drop(columns=[&#39;created_at&#39;], inplace=True)<br>df_locations.drop(columns=[&#39;updated_at&#39;], inplace=True)<br>df_locations.drop(columns=[&#39;id&#39;], inplace=True)<br>df_locations.head(5)</pre><p>further processing the trip data</p><pre>df_trip.drop(columns=[&#39;Start_time&#39;], inplace=True)<br>df_trip.drop(columns=[&#39;Start_date&#39;], inplace=True)<br>df_trip.drop(columns=[&#39;End_time&#39;], inplace=True)<br>df_trip[&#39;driver_action&#39;]= &#39;accepted&#39;<br>df_trip.head(5)</pre><p>Merging the processed data</p><pre><br>df_concatenated = pd.concat([df_trip, df_locations], axis=0, ignore_index=True)<br>df_concatenated.head(5)</pre><p><strong>Step 2: Exploratory data analysis</strong></p><ul><li>Dealing with null values</li></ul><pre>df_concatenated.isnull().sum()</pre><pre>order_id         0<br>lat_org          0<br>lon_org          0<br>lat_des          0<br>lon_des          0<br>date             1<br>driver_action    0<br>dtype: int64</pre><pre>def drop_missing_values(data, threshold=0.5):<br>    missing_percentage = data.isnull().mean()<br><br>    # If the overall missing percentage is less than the threshold, drop rows with missing values<br>    if missing_percentage.mean() &lt; threshold:<br>        data = data.dropna()<br>    else:<br>        # Drop columns where the percentage of missing values exceeds the threshold<br>        data = data.loc[:, missing_percentage &lt; threshold]<br>    <br>    return data<br>df_concatenated = eda.drop_missing_values(df_concatenated, threshold=0.05)</pre><pre>order_id         0<br>lat_org          0<br>lon_org          0<br>lat_des          0<br>lon_des          0<br>date             0<br>driver_action    0<br>dtype: int64</pre><ul><li>Dealing with outliers</li></ul><p>I calculated the z-score and then drop rows that has z_score greather than the threshold</p><pre>def drop_outliers_zscore(df, column_name, z_threshold=3):<br><br>    # Calculate Z-scores<br>    df[&#39;z_score&#39;] = zscore(df[column_name])<br><br>    # Identify outliers<br>    outliers = df[df[&#39;z_score&#39;].abs() &gt; z_threshold]<br>    print(&quot;Outliers identified:\n&quot;, outliers)<br><br>    # Drop outliers<br>    df_cleaned = df[df[&#39;z_score&#39;].abs() &lt;= z_threshold].copy()<br><br>    # Drop the z_score column<br>    df_cleaned.drop(columns=[&#39;z_score&#39;], inplace=True)<br><br>    return df_cleaned<br><br>columns_to_check = [&#39;lat_org&#39;,&#39;lon_org&#39;,&#39;lat_des&#39;, &#39;lon_des&#39;]<br>df_concatenated[columns_to_check] = df_concatenated[columns_to_check].astype(float)<br>for column_name in columns_to_check:<br>    df_concatenated = eda.drop_outliers_zscore(df_concatenated, column_name, z_threshold=3)<br>df_concatenated.head(5)</pre><p>result:</p><pre>Outliers identified:<br>[14827 rows x 8 columns]</pre><p><strong>Step 3: Adding Features</strong></p><p>in order to know the causes for unfulfilled requests we can add different features that may cause this unfulfilled. These are:</p><p>• Day type (Weekday/weekend)</p><p>• Weather condition</p><p>• Holidays</p><p>• The distance between the client and the driver</p><p>Merging the two data</p><p><strong>Visualization</strong></p><pre>cvs = ds.Canvas(plot_width=850, plot_height=500)<br>agg = cvs.points(df, &#39;lat_org&#39;, &#39;lon_org&#39;)<br>img = ds.tf.shade(agg, cmap=colorcet.fire, how=&#39;log&#39;)<br>img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Vva5dx-jp6J6oUU9K-WqWg.png" /></figure><h3>Techniques used to perform causal inference</h3><p>I used both casualNex and dowhy library to do the casual inferance. Let see step by step.</p><h3>Using CasualNex</h3><p>There are two main approaches we can take to understand the causal factors behind unfulfilled orders:</p><p><strong>Causal discovery</strong> — This involves analyzing the data to uncover potential causal relationships between variables, without relying on domain expertise.<br><strong>Leveraging domain knowledge</strong> — This approach uses subject matter expertise about the problem domain to hypothesize and test potential causal factors that may be driving unfulfilled orders.<br>In other words, we can either let the data guide us to uncover causal links, or we can use our prior knowledge about the problem context to inform our investigation into the causes of unfulfilled orders. Both approaches can provide valuable insights, and they can potentially be used in conjunction as well.</p><h4><strong>Casual Discovery</strong></h4><p>For the causal discovery approach, the plan is to use CasualNex to analyze the data and determine the causal relationships between the variables. After CasualNex generates the initial causal relationships, we will then apply a threshold to modify or refine the identified causal links.</p><p><strong>Learning the stracture</strong></p><p>The structure learning algorithm we are going to use here is the <a href="https://arxiv.org/abs/1803.01422">NOTEARS</a> algorithm. When learning structure, we can use the entire dataset. Since structure should be considered as a joint effort between machine learning and domain experts, it is not always necessary to use a train / test split.</p><p>But before we begin, we have to pre-process the data so that the NOTEARS algorithm can be used.</p><p>we want to make our data numeric, since this is what the NOTEARS expects. We can do this by label encoding non-numeric variables.</p><pre><br>import numpy as np<br>from sklearn.preprocessing import LabelEncoder<br><br>non_numeric_columns2 = list(discretised_data.select_dtypes(exclude=[np.number]).columns)<br><br>print(non_numeric_columns2)<br><br>label_encoders = {}<br><br># Store original data before encoding<br>original_data = discretised_data.copy()<br><br># Fit and transform each column with its respective LabelEncoder<br>for col in non_numeric_columns2:<br>    le = LabelEncoder()<br>    discretised_data[col] = le.fit_transform(discretised_data[col])<br>    label_encoders[col] = le<br><br>print(&quot;Encoded Data (first 5 rows):&quot;)<br>print(discretised_data.head())</pre><p>We can now apply the NOTEARS algorithm to learn the structure.</p><pre>from causalnex.structure.notears import from_pandas<br>sm_discovered = from_pandas(discretised_data)</pre><p>And plot the structure</p><pre><br>viz = plot_structure(<br>    sm_discovered,<br>    all_node_attributes=NODE_STYLE.WEAK,<br>    all_edge_attributes=EDGE_STYLE.WEAK,<br>)<br><br>viz.toggle_physics(False)<br>viz.show(&quot;/home/jabez/Documents/week_8/Logistic-optimization-Delivery-drivers-location-optimisation-with-Causal-Inference-/plots/discovered_fully_connected.html&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*nU8SRbZciY0ywCojcqQACg.png" /><figcaption>Fully connected discovered casual graph</figcaption></figure><p>The causal graph shows some causal dependencies that make sense, but it also includes other dependencies that don’t seem to make sense. For example, the graph indicates that weather data can influence the driver’s action to accept or reject an incoming order. This causal relationship seems plausible.</p><p>Similarly, factors like day type, holidays, and distance to the client could also reasonably influence the driver’s actions.</p><p>However, the causal graph also depicts cyclic dependencies, where the driver’s actions are shown to causally impact things like holidays or weather. These cyclic causal relationships don’t seem to make logical sense, since the driver’s actions could not realistically cause changes to things like holidays or the weather.</p><p>Therefore we can apply thresholding, so that we can discared week casual relatioships. Thresholding can be applied either by specifying the value for the parameter w_threshold in from_pandas, or we can remove the edges by calling the structure model function, remove_edges_below_threshold.</p><pre>sm_discovered.remove_edges_below_threshold(0.8)<br>viz = plot_structure(<br>    sm_discovered,<br>    all_node_attributes=NODE_STYLE.WEAK,<br>    all_edge_attributes=EDGE_STYLE.WEAK,<br>)<br>viz.show(&quot;/home/jabez/Documents/week_8/Logistic-optimization-Delivery-drivers-location-optimisation-with-Causal-Inference-/plots/discovered_thresholded.html&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*LL1SHqmpExmvGC3QahG73A.png" /><figcaption>Casual graph after applaying threshold</figcaption></figure><p>After applaying thresholding the result seems unrealistic. Even thoush the links seems right but the direction of the casuality dosen’t make sense.</p><h4><strong>Domain Knowlage</strong></h4><p>I tried a different approach to generate the causal graph. Instead of relying on a causal discovery , I opted to leverage the causal reasoning capabilities of a large language model like GPT-4.</p><p>To do this, I provided GPT-4 with the column information from the datasets as a prompt. Since large language models like GPT-4 are trained on vast amounts of data, they have developed an inherent understanding of causal relationships. By tapping into this causal reasoning ability, I was able to have the language model analyze the data structure and variables to produce an initial causal graph, without the need for a specialized causal discovery algorithm.</p><p>I found this to be an interesting and innovative approach, as it allowed me to harness the power of advanced language models to uncover potential causal insights directly from the data. The language model’s broad knowledge base can potentially surface causal connections that may not be immediately obvious through more traditional methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*T9wA_AZ_NrcK6x7JwfeC-A.png" /><figcaption>Suggested casual graph</figcaption></figure><p>I discretised the distance between the driver and the customer and lable it.</p><pre>number_of_buckets = 4<br>discretised_data[&#39;distance_to_client_km&#39;] = pd.qcut(discretised_data[&#39;distance_to_client_km&#39;], q=number_of_buckets, labels=False, duplicates=&#39;drop&#39;)<br><br># Map numerical labels to meaningful categories<br>category_labels = {0: &#39;Very Short&#39;, 1: &#39;Short&#39;, 2: &#39;Medium&#39;, 3: &#39;Long&#39;}<br>discretised_data[&#39;distance_to_client_km&#39;] = discretised_data[&#39;distance_to_client_km&#39;].map(category_labels)<br><br># Display the DataFrame<br>discretised_data</pre><p><strong>Fitting the Conditional Distribution of the Bayesian Network</strong><br>After deciding on how the final structure model should look, I can instantiate a BayesianNetwork.</p><pre>from causalnex.network import BayesianNetwork<br>bn_suggested = BayesianNetwork(suggested_sm)</pre><p><strong>Train / Test Split</strong><br>Like many other machine learning models, we will use a train and test split to help us validate our findings.</p><pre>from sklearn.model_selection import train_test_split<br><br>train, test = train_test_split(discretised_data, train_size=0.9, test_size=0.1, random_state=7)</pre><p><strong>Model Probability</strong><br>With the learnt structure model from earlier and the discretised data, we can now fit the probability distrbution of the Bayesian Network. The first step in this is specifying all of the states that each node can take. This can be done either from data, or providing a dictionary of node values.</p><pre>bn_suggested = bn_suggested.fit_node_states(discretised_data)</pre><p><strong>Fit Conditional Probability Distributions</strong><br>The fit_cpds method of BayesianNetwork accepts a dataset to learn the conditional probablilty distributions (CPDs) of each node, along with a method of how to do this fit.</p><pre>bn_suggested = bn_suggested.fit_cpds(train, method=&quot;BayesianEstimator&quot;, bayes_prior=&quot;K2&quot;)<br>bn_suggested.cpds[&quot;driver_action&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTzPaKGgxZMd7XCamvjl9g.png" /></figure><p>The result may seem odd diffrent arguments can be made. For example if the day is weekday and there is a holiday of Al-Hijra, and if it is a clear day the probablity of a drver accepting an order is 50/50. However if it is raing the probablity of accepting an order becomes 99.9%. This seems illogical since drivers tend to refuse driving in rain that cause them to reject order, however in this senario it seems that driver will probably accept an order if it is raing by setting the above parameters constant.</p><p>To check the prediction we can run the following code:</p><pre>discretised_data.loc[9, discretised_data.columns != &#39;driver_action&#39;]</pre><p>Result:</p><pre>icon                           rain<br>holiday_name             No holiday<br>day_type                    Weekday<br>distance_to_client_km          Long<br>Name: 9, dtype: object</pre><p>Prediction</p><pre><br>predictions = bn_suggested.predict(discretised_data, &quot;driver_action&quot;)<br>print(f&quot;The prediction is &#39;{predictions.loc[9, &#39;driver_action_prediction&#39;]}&#39;&quot;)</pre><p>Result:</p><pre>The prediction is &#39;rejected&#39;</pre><p>Ground Truth</p><pre>print(f&quot;The ground truth is &#39;{discretised_data.loc[9, &#39;driver_action&#39;]}&#39;&quot;)</pre><p>Result:</p><pre>The ground truth is &#39;rejected&#39;</pre><p><strong>Baseline Marginals</strong></p><p>To query the model for baseline marginals that reflect the population as a whole, a query method can be used. First let’s update our model using the complete dataset, since the one we currently have was only built from training data.</p><pre>bn_suggested = bn_suggested.fit_cpds(discretised_data, method=&quot;BayesianEstimator&quot;, bayes_prior=&quot;K2&quot;)<br>from causalnex.inference import InferenceEngine<br><br>ie = InferenceEngine(bn_suggested)<br>marginals = ie.query()<br>marginals[&quot;driver_action&quot;]</pre><pre>{&#39;accepted&#39;: 0.2766152310926944, &#39;rejected&#39;: 0.7233847689073054}</pre><p><strong>Do Calculus</strong><br>CausalNex also supports simple Do-Calculus, allowing us to specify interventions. In this section we will take a look at the supported methods, and what they mean.</p><p><strong>Updating a Node Distribution</strong><br>We can apply an intervention to any node in our data, updating its distribution using a do operator. This can be thought of as asking our model “What if” something were different. For example, if the driver distance is ‘very short’ to the client what will be the response of the driver</p><pre><br>print(&quot;Marginal driver_action&quot;, ie.query()[&quot;driver_action&quot;])<br>ie.do_intervention(&quot;distance_to_client_km&quot;,<br>                   {&#39;Short&#39;: 0.0,<br>                    &#39;Long&#39;: 0.0,<br>                    &#39;Medium&#39;:0.0,<br>                    &#39;Very Short&#39;:1<br>                    <br>                    })<br>print(&quot;updating Marginal driver_action&quot;, ie.query()[&quot;driver_action&quot;])</pre><pre>Marginal driver_action {&#39;accepted&#39;: 0.21283113165219425, &#39;rejected&#39;: 0.7871688683478063}<br>updating Marginal driver_action {&#39;accepted&#39;: 0.2190325832144563, &#39;rejected&#39;: 0.7809674167855447}</pre><p>If all the custemers distance to the driver is very short the acceptance rate of a drver increse form 21% to 22% increae by 1%</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3549fc0b643b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>