<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Machine Learning Use Cases in the Retail Industry</title>
	<atom:link href="https://www.relataly.com/category/retail/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.relataly.com/category/retail/</link>
	<description>The Business AI Blog</description>
	<lastBuildDate>Mon, 07 Aug 2023 19:02:19 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://www.relataly.com/wp-content/uploads/2023/04/cropped-AI-cat-Icon-White.png</url>
	<title>Machine Learning Use Cases in the Retail Industry</title>
	<link>https://www.relataly.com/category/retail/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">175977316</site>	<item>
		<title>Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT</title>
		<link>https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/</link>
					<comments>https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Wed, 05 Jul 2023 12:45:27 +0000</pubDate>
				<category><![CDATA[ChatBots]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Generative AI]]></category>
		<category><![CDATA[Healthcare]]></category>
		<category><![CDATA[Insurance]]></category>
		<category><![CDATA[Language Generation]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Responsible AI]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Telecommunications]]></category>
		<category><![CDATA[Vector Databases]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[AI in Finance]]></category>
		<category><![CDATA[Deep Learning]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=14056</guid>

					<description><![CDATA[<p>Welcome to the dawn of a new era in digital interaction! With the advent of Generative AI, we&#8217;re witnessing a remarkable revolution that&#8217;s changing the very nature of how we interact with software and digital services. This change is monumental. Leading the charge are the latest generation of AI-powered virtual assistants, aka &#8220;AI copilots&#8221;. Unlike ... <a title="Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT" class="read-more" href="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/" aria-label="Read more about Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT">Read more</a></p>
<p>The post <a href="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/">Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Welcome to the dawn of a new era in digital interaction! With the advent of <a href="https://www.relataly.com/openai-gpt-chatgpt-in-a-business-context-whats-the-value-proposition/12282/" target="_blank" rel="noreferrer noopener">Generative AI</a>, we&#8217;re witnessing a remarkable revolution that&#8217;s changing the very nature of how we interact with software and digital services. This change is monumental. Leading the charge are the latest generation of AI-powered virtual assistants, aka &#8220;AI copilots&#8221;. Unlike traditional narrow AI models, these are capable of understanding user needs, intents, and questions expressed in plain, natural language. </p>



<p>We are talking about nothing less but the next evolution in software design and user experience that is driven by recent advances in generative AI and Large Language Models (LLMs) like <a href="https://openai.com/" target="_blank" rel="noreferrer noopener">OpenAI&#8217;s ChatGPT</a>, <a href="https://bard.google.com/?hl=en" target="_blank" rel="noreferrer noopener">Google Bard</a>, or <a href="https://www.anthropic.com/index/introducing-claude" target="_blank" rel="noreferrer noopener">Anthrophic&#8217;s Claude</a>. </p>



<p>Thanks to LLMs user interactions are no longer bound by the constraints of a traditional user interface with forms and buttons. Whether it&#8217;s creating a proposal in Word, editing an image, or opening a claim in an insurance app, users can express their needs in natural language &#8211; a profound change in our interactions with software and services. </p>



<p>Despite the hype about these new virtual ai assistants, our understanding of how to build an LLM-powered virtual assistant remains scant. So, if you wonder how to take advantage of LLMs and build a virtual assistant for your app, this article is for you. This post will probe into the overarching components needed to create a virtual AI assistant. We will look at the architecture and its components including LLMs, Knowledge store, Cache, Conversational Logic, and APIs.</p>



<p><strong>Also: </strong></p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/" target="_blank" rel="noreferrer noopener">9 Business Use Cases of OpenAI’s ChatGPT</a></li>



<li><a href="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/" target="_blank" rel="noreferrer noopener">Using LLMs (OpenAI’s ChatGPT) to Streamline Digital Experiences</a></li>



<li><a href="https://www.relataly.com/mastering-prompt-engineering-for-chatgpt-a-practical-guide-for-businesses/13134/" target="_blank" rel="noreferrer noopener">ChatGPT Prompt Engineering Guide: Practical Advice for Business Use Cases</a></li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="1016" height="924" data-attachment-id="13898" data-permalink="https://www.relataly.com/?attachment_id=13898#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png" data-orig-size="1016,924" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png" src="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png" alt="Image of human pilots standing in front of an airplane, symbolizing the role of AI Copilots in shaping our interaction with software and its design." class="wp-image-13898" srcset="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png 1016w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_several_pilots_standing_in_front_of_an_airplane_colorful_b9c1a19e-5c8b-497a-b3d5-c3eddc25f4e2-min.png 768w" sizes="(max-width: 1016px) 100vw, 1016px" /><figcaption class="wp-element-caption">The new generation of virtual ai assistants inspires a profound change in the way we interact with software and digital services.</figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Virtual AI Assistants at the Example of Microsoft M365 Copilot</h2>



<p>Advances in virtual AI assistants are closely linked to ChatGPT and other LLMs from US-based startup OpenAI. Microsoft has forged a partnership with OpenAI to bring the latest advances in AI to their products and services. Microsoft has announced these &#8220;Copilots&#8221; across major applications, including M365 and the Power Platform. </p>



<p>Here are some capabilities of these Copilots within M365:</p>



<ul class="wp-block-list">
<li>In <strong>PowerPoint</strong>, Copilot allows users to create presentations based on a given context, such as a Word document, for example by stating &#8220;<em>Create a 10-slide product presentation based on the following product documentation.</em>&#8220;</li>



<li>In <strong>Word</strong>, Copilot can adjust the tone of writing a text or transform a few keywords into a complete paragraph. Simply type something like &#8220;<em>Create a proposal for a 3-month contract for customer XYZ based on doc ADF</em>.&#8221;</li>



<li>In <strong>Excel</strong>, Copilot helps users with analyzing datasets, as well as with creating or modifying them. For example, it can summarize a dataset in natural langue and describe trends. </li>



<li>Let&#8217;s not forget <strong>Outlook</strong>! Your new AI Copilot helps you organize your emails and calendar. It assists you in crafting email responses, scheduling meetings, and even provides summaries of key points from the ones you missed.</li>
</ul>



<p>If you want to learn more about Copilot in M365, this youtube video provides an excellent overview. However, these are merely a handful of examples: <a href="https://www.youtube.com/watch?v=VlM9a469LE0" target="_blank" rel="noreferrer noopener">Microsoft 365 Copilot Explained: How Microsoft Just Changed the Future of Work</a>. The potential of AI copilots extends far beyond the scope of Office applications and can elevate any software or service to a new level. No wonder, large software companies like <a href="https://www.reuters.com/technology/sap-ceo-huge-growth-potential-generative-ai-2023-06-28/" target="_blank" rel="noreferrer noopener">SAP</a>, and Adobe, have announced plans to upgrade their products with copilot features.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="982" height="848" data-attachment-id="13892" data-permalink="https://www.relataly.com/?attachment_id=13892#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/06/image-7.png" data-orig-size="982,848" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-7" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/06/image-7.png" src="https://www.relataly.com/wp-content/uploads/2023/06/image-7.png" alt="Microsoft has announced a whole series of copilots for its products, ranging from digital assistants in M365 office apps to its Azure cloud platform." class="wp-image-13892" srcset="https://www.relataly.com/wp-content/uploads/2023/06/image-7.png 982w, https://www.relataly.com/wp-content/uploads/2023/06/image-7.png 300w, https://www.relataly.com/wp-content/uploads/2023/06/image-7.png 512w, https://www.relataly.com/wp-content/uploads/2023/06/image-7.png 768w" sizes="(max-width: 982px) 100vw, 982px" /><figcaption class="wp-element-caption">Microsoft has <a href="https://blogs.microsoft.com/blog/2023/03/16/introducing-microsoft-365-copilot-your-copilot-for-work/" target="_blank" rel="noreferrer noopener">announced a whole fleet of virtual AI assistants</a> for its products. These range from copilots in M365 office apps to services of its Azure cloud platform.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading" id="h-how-llms-enable-a-new-generation-of-virtual-ai-assistants">How LLMs Enable a New Generation of Virtual AI Assistants</h2>



<p>Virtual AI assistants are nothing but new. Indeed, their roots can be traced back to innovative ventures such as the paperclip assistant, <a href="https://en.wikipedia.org/wiki/Office_Assistant" target="_blank" rel="noreferrer noopener">Clippy, from Microsoft Word</a> &#8211; a pioneering attempt at enhancing user experience. Later on, this was followed by the introduction of conventional chatbots.</p>



<p>Nonetheless, these early iterations had their shortcomings. Their limited capacity to comprehend and assist users with tasks outside of their defined parameters hampered their success on a larger scale. The inability to adapt to a wider range of user queries and requests kept these virtual ai assistants confined within their initial scope, restricting their growth and wider acceptance. So if we talk about this next generation of virtual ai assistants, what has truly revolutionized the scene? In essence, the true innovation lies in the emergence of LLMs such as OpenAI&#8217;s GPT4.</p>



<h3 class="wp-block-heading">LLMs &#8211; A Game Changer for Conversational User Interface Design</h3>



<p>Over time, advancements in machine learning, natural language processing, and vast data analytics transformed the capabilities of AI assistants. Modern AI models, like GPT-4, can understand context, engage in more human-like conversations, and offer solutions to a broad spectrum of queries. Furthermore, the integration of AI assistants into various devices and platforms, along with the increase in cloud computing, expanded their reach and functionality. These technological shifts have reshaped the scene, making AI assistants more adaptable, versatile, and user-friendly than ever before.</p>



<p>Take, for example, an AI model like GPT. A user might instruct, &#8220;Could you draft an email to John about the meeting tomorrow?&#8221; Not only would the AI grasp the essence of this instruction, but it could also produce a draft email seamlessly.</p>



<p>Yet, it&#8217;s not solely their adeptness at discerning user intent that sets LLMs apart. They also exhibit unparalleled proficiency in generating programmatic code to interface with various software functions. Imagine directing your software with, &#8220;Generate a pie chart that visualizes this year&#8217;s sales data by region,&#8221; and witnessing the software promptly fulfilling your command.</p>



<h3 class="wp-block-heading">A Revolution in Software Design and User Experience</h3>



<p>The advanced language understanding offered by LLMs unburdens developers from the painstaking task of constructing every possible dialog or function an assistant might perform. Rather, developers can harness the generative capabilities of LLMs and integrate them with their application&#8217;s API. This integration facilitates a myriad of user options without the necessity of explicitly designing them.</p>



<p>The outcome of this is far-reaching, extending beyond the immediate relief for developers. It sets the stage for a massive transformation in the software industry and the broader job market, affecting how developers are trained and what skills are prioritized. Furthermore, it alters our everyday interaction with technology, making it more intuitive and efficient. </p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Components of a Modern Virtual AI Assistant áka AI Copilot</h2>



<p>By now you should have some idea of what modern virtual AI assistants are. Next, let&#8217;s look at the technical components that need to come together. </p>



<p>The illustration below displays the main components of an LLM-powered virtual AI assistant:</p>



<ul class="wp-block-list">
<li>A &#8211; Conversational UI for providing the user with a chat experience</li>



<li>B &#8211; LLMs such as GPT-3.5 or GPT-4 </li>



<li>C &#8211; Knowledge store for grounding your bot in enterprise data and dynamically providing few-shot examples. </li>



<li>D &#8211; Conversation logic for intent recognition and tracking conversations. </li>



<li>E &#8211; Application API as an interface to trigger and perform application functionality. </li>



<li>F &#8211; Cache for maintaining an instant mapping between often encountered user intents and structured LLM responses. </li>
</ul>



<p>Let&#8217;s look at these components in more detail.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="3531" height="2753" data-attachment-id="14173" data-permalink="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/virtual-assistant-architecture-components-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png" data-orig-size="3531,2753" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="virtual-assistant-architecture-components-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png" src="https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png" alt="" class="wp-image-14173" srcset="https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 3531w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 300w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 512w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 768w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 1536w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 2048w, https://www.relataly.com/wp-content/uploads/2023/08/virtual-assistant-architecture-components-1.png 2475w" sizes="(max-width: 1237px) 100vw, 1237px" /></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h3 class="wp-block-heading">A) Conversational Application Frontend</h3>



<p>Incorporating virtual AI assistants into a software application or digital service often involves the use of a conversational user interface, typically embodied in a chat window that showcases previous interactions. The seamless integration of this interface as an intrinsic part of the application is vital.</p>



<p>A lot of applications employ a standard chatbot methodology, where the virtual AI assistant provides feedback to users in natural language or other forms of content within the chat window. Yet, a more dynamic and efficacious approach is to merge natural language feedback with alterations in the traditional user interface (UI). This dual approach not only enhances user engagement but also improves the overall user experience.</p>



<p>Microsoft&#8217;s M365 Copilot is a prime example of this approach. Instead of simply feeding responses back to the user in the chat window, the virtual assistant also manipulates elements in the traditional UI based on user input. It may highlight options, auto-fill data, or direct the user&#8217;s attention to certain parts of the screen. This combination of dynamic UI manipulation and natural language processing creates a more interactive and intuitive user experience, guiding the user toward their goal in a more efficient and engaging way.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="926" height="292" data-attachment-id="13999" data-permalink="https://www.relataly.com/?attachment_id=13999#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/07/image-5.png" data-orig-size="926,292" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-5" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/07/image-5.png" src="https://www.relataly.com/wp-content/uploads/2023/07/image-5.png" alt="Sample Copilot chat window in M365 Office" class="wp-image-13999" srcset="https://www.relataly.com/wp-content/uploads/2023/07/image-5.png 926w, https://www.relataly.com/wp-content/uploads/2023/07/image-5.png 300w, https://www.relataly.com/wp-content/uploads/2023/07/image-5.png 512w, https://www.relataly.com/wp-content/uploads/2023/07/image-5.png 768w" sizes="(max-width: 926px) 100vw, 926px" /><figcaption class="wp-element-caption">M365 Copilot chat window in M365 Office </figcaption></figure>



<p>When designing the UI for a virtual AI assistant, there are several key considerations. Firstly, the interface should be intuitive, ensuring users can easily navigate and understand how to interact with the AI. Secondly, the AI should provide feedback in a timely manner, so the user isn&#8217;t left waiting for a response. Thirdly, the system should be designed to handle errors gracefully, providing helpful error messages and suggestions when things don&#8217;t go as planned. Finally, the AI should keep the human in the loop and assist him in using AI in a safe way. </p>



<p>Also: <a href="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/" target="_blank" rel="noreferrer noopener">Building “Chat with your Data” Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore</a></p>



<h3 class="wp-block-heading">B) Large Language Model</h3>



<p>At the interface between users and assistant sits the large language mode. It translates users&#8217; requests and questions into code, actions, and responses that are shown to the user. Here, we are talking about foundational models like GPT-3.5-Turbo or GPT-4. In addition, if you are working with extensive content, you may use an embedding LLM that converts text or images into mathematical vectors as part of your knowledge store. An example, of such an embedding model, is ada-text-embeddings-002.</p>



<p>It&#8217;s important to understand that the user is not directly interacting with the LLM. Instead, you may want to put some control logic between the user and the LLM that steers the conversation. This logic can enrich prompts with additional data from the knowledge store or an online search API such as Google or Bing. This process of injecting data into a prompt depending on the user input is known as <a href="https://arxiv.org/abs/2005.11401" target="_blank" rel="noreferrer noopener">Retrieval Augmented Generation</a>. </p>



<p>Typical tasks performed by the LLM: </p>



<ul class="wp-block-list">
<li>Generating natural language responses based on the user’s query and the retrieved data from the knowledge store.</li>



<li>Recognizing and classifying user intent.</li>



<li>Generating code snippets (or API requests) that can be executed by the application or the user to achieve a desired outcome in your application.</li>



<li>Converting content into embeddings to retrieve relevant information from a vector-based knowledge store.</li>



<li>Generating summaries, paraphrases, translations, or explanations of the retrieved data or the generated responses.</li>



<li>Generating suggestions, recommendations, or feedback for the user to improve their experience or achieve their goals.</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h3 class="wp-block-heading">C) Knowledge Store</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Let&#8217;s dive into the &#8220;Knowledge Store&#8221; and why it&#8217;s vital. You might think feeding a huge prompt explaining app logic to your LLM, like ChatGPT, would work, but that&#8217;s not the case. As of June 2023, LLMs have context limits. For instance, GPT-3 can handle up to 4k tokens, roughly three pages of text. This limitation isn&#8217;t just for input, but output too. Hence, cramming everything into one prompt isn&#8217;t efficient or quick.</p>



<p>Instead, pair your LLM with a knowledge store, like a vector database (more on this in our article on <a href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/" target="_blank" rel="noreferrer noopener">Vector Databases</a>). Essentially, this is your system&#8217;s information storage, which efficiently retrieves data. Whichever storage you use, a search algorithm is crucial to fetch items based on user input. For vector databases, the typical way of doing this is by using similarity search.</p>



<p><strong>Token Limitations</strong></p>



<p>Curious about GPT models&#8217; token limits? Here&#8217;s a quick breakdown:</p>



<ul class="wp-block-list">
<li><strong>GPT-3.5-Turbo Model (4,000 tokens):</strong> About 7-8 DIN A4 pages</li>



<li><strong>GPT-4 Standard Model (8,000 tokens):</strong> Around 14-16 DIN A4 pages</li>



<li><strong>GPT-3.5-Turbo-16K Model (16,000 tokens):</strong> Approximately 28-32 DIN A4 pages</li>



<li><strong>GPT-4-32K Model (32,000 tokens):</strong> Estimated at 56-64 DIN A4 pages</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<p></p>
</div>
</div>



<h3 class="wp-block-heading">D) Conversation Control Logic</h3>



<p>Finally, the conversation needs a conductor to ensure it stays in harmony and doesn&#8217;t veer off the rails. This is the role of the conversation logic. An integral part of your app&#8217;s core software, the conversation logic bridges all the elements to deliver a seamless user experience. It includes several subcomponents. Meta prompts, for instance, help guide the conversation in the desired direction and provide some boundaries to the activities of the assistant. For example, the meta prompt may include a list of basic categories for intents that help the LLM with understanding what the user wants to do. </p>



<p>Another subcomponent is the connection to the knowledge store that allows the assistant to draw from a vast array of data to augment prompts handed over to the large language model. Moreover, the logic incorporates checks on the assistant&#8217;s activities and its generated content. These checks act like safety nets, mitigating risks and preventing unwanted outcomes. It&#8217;s akin to a quality control mechanism, keeping the assistant&#8217;s output in check and safeguarding against responses that might derail the user&#8217;s experience or even break the application.</p>



<h3 class="wp-block-heading">E) Application API</h3>



<p>Users expect their commands to initiate actions within your application. To fulfill these expectations, the application needs an API that can interact with various app functions. Consider the API as the nerve center of your app, facilitating access to its features and user journey. This API enables the AI assistant to guide users to specific pages, fill in forms, execute tasks, display information, and more. Tools like Microsoft Office even have their own language for this, while Python code, SQL statements, or generic REST requests usually suffice for most applications. </p>



<p>Applications based on a microservice architecture have an edge in this regard, as APIs are inherent to their design. If your application misses some APIs, remember, there&#8217;s no rush to provide access to all functions from the outset. You can start by supporting basic functionalities via chat and gradually expand over time. This allows you to learn from user interactions, continuously refine your offering, and ensure your AI assistant remains a useful and efficient tool for your users.</p>



<p>So, now that we&#8217;ve laid down the foundation, let&#8217;s buckle up and take a journey through the workflow of a modern virtual assistant. Trust me, it&#8217;s a fascinating trip ahead!</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h3 class="wp-block-heading">F) Cache</h3>



<p>Implementing a cache into your virtual AI assistant can significantly boost performance and decrease response times. Particularly useful for frequently recurring user intents, caching stores the outcomes of these intents for quicker access in future instances. However, a well-designed cache shouldn&#8217;t directly store specific inputs as there is too much variety in the human language. Instead, caching could be woven into the application&#8217;s logic in the mid-layers of your OpenAI prompt flow. </p>



<p>This strategy ensures frequently repeated intents are handled more swiftly, enhancing user experience. It&#8217;s critical to remember that cache integration is application-specific, and thoughtful design is vital to avoid unintentionally inducing inefficiencies.</p>



<p>While a well-implemented cache can speed up responses, it also introduces additional complexity. Effective cache management is crucial for avoiding resource drains, requiring strategies for data storage duration, updates, and purging.</p>



<p>The exact impact and efficiency of this caching strategy will depend on your application specifics, including the distribution and repetition of user intents. In the upcoming articles, we&#8217;ll explore this topic further, discussing efficient cache integration in AI assistant systems.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="467" height="156" data-attachment-id="14076" data-permalink="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/image-11-14/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/07/image-11.png" data-orig-size="467,156" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-11" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/07/image-11.png" src="https://www.relataly.com/wp-content/uploads/2023/07/image-11.png" alt="" class="wp-image-14076" srcset="https://www.relataly.com/wp-content/uploads/2023/07/image-11.png 467w, https://www.relataly.com/wp-content/uploads/2023/07/image-11.png 300w" sizes="(max-width: 467px) 100vw, 467px" /><figcaption class="wp-element-caption">An example of a caching technology would be <a href="https://redis.com/docs/caching-at-scale-with-redis/?utm_source=google&amp;utm_medium=cpc&amp;utm_term=cache&amp;utm_campaign=why_re-land_caching-cacheonly-emea-20125229738&amp;utm_content=why_re-eb-caching_at_scale_with_redis&amp;gclid=CjwKCAjwqZSlBhBwEiwAfoZUIIR30kfBaYLKfRO1ab0cxKcUB2og6UbR22oyogPcrj087B0CSp3TZRoC11gQAvD_BwE" target="_blank" rel="noreferrer noopener">Redis</a>.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Considerations on the Architecture of Virtual AI Assistants</h2>



<p>Designing an virtual AI assistant is an intricate process that blends cutting-edge technology with a keen understanding of user behavior. It&#8217;s about creating an efficient tool that not only simplifies tasks and optimizes workflows but also respects and preserves user autonomy. This section of our article will delve into the key considerations that guide the architecture of a virtual AI assistant. We&#8217;ll discuss the importance of user control, the strategic selection and use of GPT models, the benefits of starting simple, and the potential expansion as you gain confidence in your system&#8217;s stability and efficiency. As we journey through these considerations, remember the ultimate goal: creating a virtual AI assistant that augments user capabilities, enhances user experience, and breathes new life into software applications.</p>



<h3 class="wp-block-heading">Keep the User in Control</h3>



<p>At the heart of any virtual AI assistant should be the principle of user control. While automation can optimize tasks and streamline workflows, it is crucial to remember that your assistant is there to assist, not usurp. Balancing AI automation with user control is essential to crafting a successful user experience.</p>



<p>Take, for instance, the scenario of a user wanting to open a support ticket within your application. In this situation, your assistant could guide the user to the correct page, auto-fill known details like the user&#8217;s name and contact information, and even suggest possible problem categories based on the user&#8217;s descriptions. By doing so, the virtual AI assistant has significantly simplified the process for the user, making it quicker and less burdensome.</p>



<p>However, the user retains control throughout the process, making the final decisions. They can edit the pre-filled details, choose the problem category, and write the issue description in their own words. They&#8217;re in command, and the virtual AI assistant is there to assist, helping to avoid errors, speed up the process, and generally make the experience smoother and more efficient.</p>



<p>This balance between user control and AI assistance is not only about maintaining a sense of user agency; it is also about trust. Users need to trust that the AI is there to help them, not to take control away from them. If the AI seems too controlling or makes decisions that the user disagrees with, this can erode trust and hinder user acceptance.</p>



<h3 class="wp-block-heading">Mix and Match Models</h3>



<p>Another crucial consideration is the use of different GPT models. Each model comes with its own set of strengths, weaknesses, response times, costs, and token limits. It&#8217;s not just about capabilities. Sometimes, it&#8217;s unnecessary to deploy a complex GPT-4 model for simpler tasks in your workflow. Alternatives like ADA or GPT 3.5 Turbo might be more suitable and cost-effective for functions like intent recognition.</p>



<p>Reserve the heavy-duty models for tasks requiring an extended token limit or dealing with complex operations. One such task is the final-augmented prompt that creates the API call. If you&#8217;re working with a vector database, you&#8217;ll also need an embedding model. Be mindful that these models come with different vector sizes, and once you start building your database with a specific size, it can be challenging to switch without migrating your entire vector content.</p>



<h3 class="wp-block-heading">Think Big but Start Simple </h3>



<p>It&#8217;s always a good idea to start simple &#8211; maybe with a few intents to kick things off. As you gain experience and confidence in building virtual assistant apps, you can gradually integrate additional intents and API calls. And don&#8217;t forget to keep your users involved! Consider incorporating a feedback mechanism, allowing users to report any issues and suggest improvements. This will enable you to fine-tune your prompts and database content effectively.</p>



<p>As your application becomes more comprehensive, you might want to explore model fine-tuning for specific tasks. However, this step should be considered only when your virtual AI assistant functionality has achieved a certain level of stability. Fine-tuning a model can be quite costly, especially if you decide to change the intent categories after training.</p>



<h2 class="wp-block-heading">Digital LLM-based Assistants &#8211; A Major Business Opportunity</h2>



<p>From a business standpoint, upgrading software products and services with LLM-powered virtual AI assistants presents a significant opportunity to differentiate in the market and even innovate their business model. Many organizations are already contemplating the inclusion of virtual assistants as part of subscription packages or premium offerings. As the market evolves, software lacking a natural language interface may be perceived as outdated and struggle to compete.</p>



<p>AI-powered virtual assistants are likely to inspire a whole new generation of software applications and enable a new wave of digital innovations. By enhancing convenience and efficiency in user inputs, virtual assistants unlock untapped potential and boost productivity. Moreover, they empower users to fully leverage the diverse range of features offered by software applications, which often remain underutilized.</p>



<p>I strongly believe that LLM-driven virtual AI assistants are the next milestone in software design and will revolutionize software applications across industries. And remember, this is just the first generation of virtual assistants. The future possibilities are virtually endless and we can&#8217;t wait to see what&#8217;s next! Indeed, the emergence of natural language interfaces is expected to trigger a ripple effect of subsequent innovations, for example, in areas such as standardization, workflow automation, and user experience design.</p>



<h2 class="wp-block-heading">Summary</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>In this article, we delved into the fascinating world of virtual AI assistants, powered by LLMs. We started by exploring how the advanced language understanding of LLMs is revolutionizing software design, easing the workload of developers, and reshaping user experiences with technology.</p>



<p>Next, we provided an overview of the key architectural components of a modern virtual AI assistant: the <strong>Conversational Application Frontend</strong>, <strong>Large Language Model</strong>, <strong>Knowledge Store</strong>, and <strong>Conversation Control Logic</strong>. We also introduced the concept of an <strong>Application API </strong>and the novel idea of a <strong>Cache </strong>for storing and quickly retrieving common user intents. Each component was discussed in the context of their roles and how they work together to create a seamless, interactive, and efficient user experience.</p>



<p>We then discussed architecture considerations, emphasizing the necessity of maintaining user control while leveraging the power of AI automation. We talked about the judicious use of different GPT models based on task requirements, the advantages of starting with simple implementations and progressively scaling up, and the benefits of user feedback in continuously refining the system.</p>



<p>This journey of &#8216;AI in Software Applications&#8217;, from concept to reality, isn&#8217;t just about innovation. It&#8217;s about unlocking &#8216;Innovative Business Models with AI&#8217; and boosting user engagement and productivity. As we continue to ride the wave of &#8216;Natural Language Processing for Software Automation&#8217;, the opportunities for harnessing the power of virtual AI assistants are endless. Stay tuned as we explore the workflows further in the next article.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="289" data-attachment-id="14071" data-permalink="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png" data-orig-size="1426,806" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png" src="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1-512x289.png" alt="A mechanic working on an airplace engine" class="wp-image-14071" srcset="https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png 512w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png 300w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png 768w, https://www.relataly.com/wp-content/uploads/2023/07/Flo7up_a_mechanic_looking_at_the_engine_of_an_airplane_colorful_fd860957-d8af-48f4-a207-deb0ea13230d-min-1.png 1426w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">In this article, we have gone through the components of an LLM-powered virtual assistant aka &#8220;AI copilot&#8221;. In the next article, we will dive deeper into the processing logic and follow a prompt into the engine of an intelligent assistant. </figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<ul class="wp-block-list">
<li><a href="https://arxiv.org/pdf/2306.03460.pdf" target="_blank" rel="noreferrer noopener">Natural Language Commanding via Program Synthesis</a></li>



<li><a href="https://en.wikipedia.org/wiki/Office_assistant" target="_blank" rel="noreferrer noopener">Wikipedia.org/Office Assistant</a></li>



<li><a href="https://blogs.microsoft.com/blog/2023/03/16/introducing-microsoft-365-copilot-your-copilot-for-work/" target="_blank" rel="noreferrer noopener">Microsoft Blogs &#8211; Introducing Microsoft 365 Copilot</a></li>



<li><a href="https://www.reuters.com/technology/sap-ceo-huge-growth-potential-generative-ai-2023-06-28/" target="_blank" rel="noreferrer noopener">Reuters &#8211; Sap CEO Huge Growth Potential in Generative AI</a></li>



<li><a href="https://news.microsoft.com/source/features/ai/microsoft-outlines-framework-for-building-ai-apps-and-copilots-expands-ai-plugin-ecosystem/" target="_blank" rel="noreferrer noopener">Microsoft Outlines Framework for Building AI Apps and Copilots, Expands AI Plugin Ecosystem</a></li>



<li><a href="https://workspace.google.com/blog/product-announcements/generative-ai?hl=en" target="_blank" rel="noreferrer noopener">Google Announces Digital Assistants in their Worksuite</a></li>



<li><a href="https://www.youtube.com/watch?v=B2-8wrF9Okc" target="_blank" rel="noreferrer noopener">Youtube, Microsoft Mechanics &#8211; How Microsoft 365 Copilot works</a></li>



<li><a href="https://www.youtube.com/watch?v=VlM9a469LE0" target="_blank" rel="noreferrer noopener">Youtube, Lisa Crosby &#8211; Microsoft 365 Copilot Explained: How Microsoft Just Changed the Future of Work</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/">Building a Virtual AI Assistant (aka Copilot) for Your Software Application: Harnessing the Power of LLMs like ChatGPT</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/building-a-digital-ai-assistant-for-your-software-application/14056/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">14056</post-id>	</item>
		<item>
		<title>Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore</title>
		<link>https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/</link>
					<comments>https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sat, 27 May 2023 13:25:08 +0000</pubDate>
				<category><![CDATA[ChatBots]]></category>
		<category><![CDATA[Clustering]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Generative AI]]></category>
		<category><![CDATA[Healthcare]]></category>
		<category><![CDATA[Insurance]]></category>
		<category><![CDATA[Language Generation]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Marketing Automation]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Prompt Engineering]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Sentiment Analysis]]></category>
		<category><![CDATA[Use Cases]]></category>
		<category><![CDATA[Vector Databases]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=13687</guid>

					<description><![CDATA[<p>Artificial Intelligence (AI), in particular, the advent of OpenAI&#8217;s ChatGPT, has revolutionized how we interact with technology. Chatbots powered by this advanced language model can engage users in intricate, natural language conversations, marking a significant shift in AI capabilities. However, one thing that ChatGPT isn&#8217;t designed for is integrating personalized or proprietary knowledge – it&#8217;s ... <a title="Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore" class="read-more" href="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/" aria-label="Read more about Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore">Read more</a></p>
<p>The post <a href="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/">Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Artificial Intelligence (AI), in particular, the advent of OpenAI&#8217;s ChatGPT, has revolutionized how we interact with technology. Chatbots powered by this advanced language model can engage users in intricate, natural language conversations, marking a significant shift in AI capabilities. However, one thing that ChatGPT isn&#8217;t designed for is integrating personalized or proprietary knowledge – it&#8217;s built to draw upon general knowledge, not specifics about you or your organization. That&#8217;s where the concept of Retrieval Augmented Generation (RAG) comes into play. This article explores the exciting prospect of building your own ChatGPT that lets users ask questions on a custom knowledge base.</p>



<p>In this tutorial, we&#8217;ll unveil the mystery behind enterprise ChatGPT, guiding you through the process of creating your very own custom ChatGPT &#8211; an AI-powered chatbot based on OpenAI&#8217;s powerful Generative Pretrained Transformers (GPT) technology. We&#8217;ll use Python and delve into the world of <a href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/" target="_blank" rel="noreferrer noopener">vector databases</a>, specifically, <a href="https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/introduction" target="_blank" rel="noreferrer noopener">Mongo API for Azure Cosmos DB</a>, to show you how you can make a large knowledgebase available to ChatGPT that can go way beyond the <a href="https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them" target="_blank" rel="noreferrer noopener">typical token limitation of GPT models</a>.</p>



<p>For experts, AI fans, or tech newbies, this guide simplifies building your ChatGPT. With clear instructions, useful examples, and tips, we aim to make it informative and empowering.</p>



<p>We&#8217;ll explore AI, showing you how to customize your chatbot. We&#8217;ll simplify complex concepts and show you how to start your AI adventure from home or office. Ready to start this exciting journey? Keep reading!</p>



<p>Also: </p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/how-to-build-a-twitter-news-bot-with-openai-and-newsapi/13581/" target="_blank" rel="noreferrer noopener">How to Build a Twitter News Bot with OpenAI ChatGPT and NewsAPI in Python</a></li>



<li><a href="https://www.relataly.com/from-pirates-to-nobleman-simulating-conversations-between-openais-chatgpt-and-itself-using-python/13525/" target="_blank" rel="noreferrer noopener">From Pirates to Nobleman: Simulating Conversations between Various Characters using OpenAI’s ChatGPT and Python</a></li>
</ul>



<h2 class="wp-block-heading">Note on the use of Vector DBs and Costs.</h2>



<p>Please note that this tutorial describes a business use case that utilizes a Cosmos DB for Mongo DB vCore hosted on the Azure cloud. </p>



<p>Alternatively, you can set up an open-source vector database on your local machine, such as Milvus. Be aware that certain code adjustments will be necessary to proceed with the open-source alternative. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading" id="h-why-custom-chatgpt-is-so-powerful-and-versatile">Why Custom ChatGPT is so Powerful and Versatile</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>I believe we have all tested ChatGPT, and probably like me, you have been impressed by its remarkable capabilities. However, ChatGPT has a significant limitation: it can only answer questions and perform tasks based on the public knowledge base it was trained on. </p>



<p>Imagine having a chatbot based on ChatGPT that communicates effectively and truly understands the nuances of your business, sector, or even a particular topic of interest. That&#8217;s the power of a custom ChatGPT. A tailor-made chatbot allows for specialized conversations, providing the needed information and drawing from a unique database you&#8217;ve developed. </p>



<p>This becomes particularly beneficial in industries with specific terminologies or when you have a large database of knowledge that you want to make easily accessible and interactive. A custom ChatGPT, with its personalized and relevant responses, ensures a better user experience, effectively saving time and increasing productivity. </p>



<p>Let&#8217;s delve into how to build such a solution. Spoiler it does not work by putting all the content into the prompt. But there is a great alternative. </p>



<h2 class="wp-block-heading">Understanding the Building Blocks of Custom ChatGPT with Retrieval Augmented Generation</h2>



<p>The foundational technology behind ChatGPT is OpenAI&#8217;s Generative Pre-trained Transformer models (GPT). These models understand language by predicting the next word in a sentence and are trained on a diverse range of internet text. However, the GPT models, such as the GPT-3.5, have a limitation of processing 4096 tokens at a time. A token in this context is a chunk of text which can be as small as one character or as long as one word. For example, the phrase &#8220;ChatGPT is great&#8221; is four tokens long.</p>



<p>Another challenge with Foundation Models such as ChatGPT is that they are trained on large-scale datasets that were available at the time of their training. This means they are not aware of any data created after their training period. Also, because they&#8217;re trained on broad, general-domain datasets, they may be less effective for tasks requiring domain-specific knowledge.</p>



<h3 class="wp-block-heading">How Retrieval Augmented Generation (RAG) Helps </h3>



<p>Retrieval-Augmented Generation (RAG) is a method that combines the strength of transformer models with external knowledge to augment their understanding and applicability. Here&#8217;s a brief explanation:</p>



<p>To address this, RAG retrieves relevant information from an external data source and uses this information to augment the input to the foundation model. This can make the model&#8217;s responses more informed and relevant.</p>



<h3 class="wp-block-heading">Data Sources</h3>



<p>The external data can come from various sources like databases, document repositories, or APIs. To make this data compatible with the RAG approach, both the data and user queries are converted into numerical representations (embeddings) using language models.</p>



<h3 class="wp-block-heading">Data Preparation as Embeddings</h3>



<p>The embeddings, which are essentially vectors, need to be stored in a database that&#8217;s efficient at storing and searching through these high-dimensional data. This is where Azure&#8217;s Cosmos Mongo DB comes into play. It&#8217;s a vector search database specifically designed for this task.</p>



<p>To circumvent the token limitation and make your extensive data available to ChatGPT, we turn the data into embeddings. These are mathematical representations of your data, converting words, sentences, or documents into vectors. The advantage of using embeddings is that they capture the semantic meaning of the text, going beyond keywords to understand the context. In essence, similar information will have similar vectors, allowing us to cluster related information together and separate them from a semantically different text.</p>



<h3 class="wp-block-heading">Storing the Data in Vector Databases</h3>



<p>The embeddings, which are essentially vectors, need to be stored in a database that&#8217;s efficient at storing and searching through these high-dimensional data. This is where Azure&#8217;s Cosmos Mongo DB comes into play. It&#8217;s a vector search database specifically designed for this task.</p>



<h3 class="wp-block-heading">Matching Queries to Knowledge</h3>



<p>The RAG model compares the embeddings of user queries with those in the knowledge base to identify relevant information. The user&#8217;s original query is then augmented with context from similar documents in the knowledge base.</p>



<h3 class="wp-block-heading">Input to the Foundation Model</h3>



<p>This augmented input is sent to the foundation model, enhancing its understanding and response quality.</p>



<h3 class="wp-block-heading">Updates</h3>



<p>Importantly, the knowledge base and associated embeddings can be updated asynchronously, ensuring that the model remains up-to-date even as new information is added to the data sources.</p>



<p>In sum, RAG extends the utility of foundation models by incorporating external, up-to-date, domain-specific knowledge into their understanding and output.</p>



<p>By incorporating these components, you&#8217;ll be creating a robust custom ChatGPT that not only understands the user&#8217;s queries but also has access to your own information, giving it the ability to respond with precision and relevance. </p>



<p>Ready to dive into the technicalities? Stay tuned!</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="277" data-attachment-id="13775" data-permalink="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/flo7up_a_vector_database_colorful_popart_with_an_ai_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-copy-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png" data-orig-size="1432,776" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png" src="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min-512x277.png" alt="A tailor-made chatbot allows for specialized conversations, providing the exact information needed, drawing from a unique database that you've developed. " class="wp-image-13775" srcset="https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/05/Flo7up_a_vector_database_colorful_popart_with_an_AI_robot_worki_46d21322-5bd9-49f0-b1a7-b7b1a17536d5-Copy-min.png 1432w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">A tailor-made chatbot allows for specialized conversations, providing the exact information needed, drawing from a unique database that you&#8217;ve developed. </figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Building the Custom &#8220;Chat with Your Data&#8221; App in Python</h2>



<p>Now that we&#8217;ve discussed the theory behind building a custom ChatGPT and seen some exciting real-world applications, it&#8217;s time to put our knowledge into action! In this practical segment of our guide, we&#8217;re going to demonstrate how you can build a custom ChatGPT solution using Python.</p>



<p>Our project will involve storing a sample PDF document in Cosmos Mongo DB and developing a chatbot capable of answering questions based on the content of this document. This practical exercise will guide you through the entire process, including turning your PDF content into embeddings, storing these embeddings in the Cosmos Mongo DB, and finally integrating it all with ChatGPT to build an interactive chatbot.</p>



<p>If you&#8217;re new to Python, don&#8217;t worry, we&#8217;ll be breaking down the code and explaining each step in a straightforward manner. Let&#8217;s roll up our sleeves, fire up our Python environments, and get coding! Stay tuned as we embark on this exciting hands-on journey into the world of custom chatbots.</p>



<p>The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_c8e02b-b1"><a class="kb-button kt-button button kb-btn_022d60-c9 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/300%20Distributed%20Computing%20-%20Analyzing%20Zurich%20Weather%20Data%20using%20PySpark.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_8db802-ce kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">How to Set Up Vector Search in Cosmos DB</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>First, you must understand that you will need a database to store the embeddings. It does not necessarily have to be a vector database. Still, this type of database will make your solution more performant and robust, particularly when you want to store large amounts of data.</p>



<p><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/vcore/" target="_blank" rel="noreferrer noopener">Azure Cosmos DB for MongoDB vCore</a> is the first MongoDB-compatible offering to feature Vector Search. With this feature, you can store, index, and query high-dimensional vector data directly in Azure Cosmos DB for MongoDB vCore, eliminating the need for data transfer to alternative platforms for vector similarity search capabilities. Here are the steps to set it up:</p>



<ol class="wp-block-list">
<li><strong>Choose Your Azure Cosmos DB Architecture:</strong> Azure Cosmos DB for MongoDB provides two types of architectures, RU-based and vCore-based. Each has its strengths and is best suited for certain types of applications. Choose the one that best fits your needs. If you&#8217;re looking to lift and shift existing MongoDB apps and run them as-is on a fully supported managed service, the vCore-based option could be the perfect fit.</li>



<li><strong>Configure Your Vector Search:</strong> Once your database architecture is set up, you can integrate your AI-based applications, including those using OpenAI embeddings, with your data already stored in Cosmos DB.</li>



<li><strong>Build and Deploy Your AI Application:</strong> With the Vector Search set up, you can now build your AI application that takes advantage of this feature. You can create a Go app using Azure Cosmos DB for MongoDB or deploy Azure Cosmos DB for MongoDB vCore using a Bicep template as suggested next steps.</li>
</ol>



<p>Azure Cosmos DB for MongoDB vCore&#8217;s Vector Search feature is a game-changer for AI application development. It enables you to unlock new insights from your data, leading to more accurate and powerful applications.</p>



<h2 class="wp-block-heading">Cosmos DB for Mongo DB Usage Models</h2>



<p>Regarding <a href="https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/choose-model" target="_blank" rel="noreferrer noopener">Cosmos DB for Mongo DB</a>, there are two options to choose from: Request Unit (RU) Database Account and vCore Cluster. Each option follows a different pricing model to suit diverse needs.</p>



<p>The Request Unit (RU) Database Account operates on a pay-per-use basis. With this model, you are billed based on the number of requests and the level of provisioned throughput consumed by your workload.</p>



<p>As of 27th Mai 2023, <a href="https://devblogs.microsoft.com/cosmosdb/introducing-vector-search-in-azure-cosmos-db-for-mongodb-vcore/" target="_blank" rel="noreferrer noopener">the brand new vector search function is only available for the vCore Cluster option</a>, which is why we will use this setup for this tutorial. The vCore Cluster offers a reserved managed instance. Under this option, you are charged a fixed amount on a monthly basis, providing more predictable costs for your usage.</p>



<p>Once you have created your vCore instance, you must collect your connection string and make it available to your Python script. You can do this either by storing it in <a href="https://azure.microsoft.com/en-us/products/key-vault/">Azure Key Vault</a> (which I would recommend) or by storing it locally on your computer or in the code (which I would not recommend for obvious security reasons).</p>



<figure class="wp-block-image size-full"><img decoding="async" width="1536" height="588" data-attachment-id="13774" data-permalink="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/image-7-6/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/image-7.png" data-orig-size="1536,588" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-7" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/image-7.png" src="https://www.relataly.com/wp-content/uploads/2023/05/image-7.png" alt="" class="wp-image-13774" srcset="https://www.relataly.com/wp-content/uploads/2023/05/image-7.png 1536w, https://www.relataly.com/wp-content/uploads/2023/05/image-7.png 300w, https://www.relataly.com/wp-content/uploads/2023/05/image-7.png 512w, https://www.relataly.com/wp-content/uploads/2023/05/image-7.png 768w" sizes="(max-width: 1237px) 100vw, 1237px" /><figcaption class="wp-element-caption">When it comes to Cosmos DB for Mongo DB, there are two options to choose from: Request Unit (RU) Database Account and vCore Cluster. </figcaption></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="334" height="512" data-attachment-id="13772" data-permalink="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/image-5-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/05/image-5.png" data-orig-size="606,929" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-5" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/05/image-5.png" src="https://www.relataly.com/wp-content/uploads/2023/05/image-5-334x512.png" alt="Azure Cosmos DB for Mongo DB is a new offering that is specifically designed for vector use cases (incl. embeddings)" class="wp-image-13772" srcset="https://www.relataly.com/wp-content/uploads/2023/05/image-5.png 334w, https://www.relataly.com/wp-content/uploads/2023/05/image-5.png 196w, https://www.relataly.com/wp-content/uploads/2023/05/image-5.png 606w" sizes="(max-width: 334px) 100vw, 334px" /><figcaption class="wp-element-caption">Azure Cosmos DB for Mongo DB is a new offering that is designed explicitly for vector use cases (incl. embeddings)</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Using other Vector Databases</h2>



<p>While Cosmos DB is a popular choice for vector databases, I would like to note that other options are available in the market. You can still benefit from this tutorial if you decide to utilize a different vector database, such as Pinncecone or Chroma. However, it is necessary to make code adjustments tailored to the APIs and functionalities of the specific vector database you choose.</p>



<p>Specifically, you will need to modify the &#8220;insert embedding functions&#8221; and &#8220;similarity search functions&#8221; to align with the requirements and capabilities of your chosen vector database. These functions typically have variations that are specific to each vector database.</p>



<p>By customizing the code according to your selected vector database&#8217;s API, you can successfully adapt the tutorial to suit your specific database choice. This allows you to leverage the principles and concepts this tutorial covers, regardless of the vector database you opt for.</p>



<p>Also: <a href="https://www.relataly.com/vector-databases-the-rising-star-in-generative-ai-infrastructure/13599/" target="_blank" rel="noreferrer noopener">Vector Databases: The Rising Star in Generative AI Infrastructure</a></p>



<h3 class="wp-block-heading">Prerequisites</h3>



<p>Before diving into the code, it’s essential to ensure that you have the proper setup for your Python 3 environment and have installed all the necessary packages. If you do not have a Python environment, follow the instructions in&nbsp;<a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a>&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda Python environment</a>. This will provide you with a robust and versatile environment well-suited for machine learning and data science tasks.</p>



<p>In this tutorial, we will be working with several libraries:</p>



<ul class="wp-block-list">
<li>openai</li>



<li>pymongo</li>



<li>PyPDF2</li>



<li>dotenv</li>
</ul>



<p>Should you decide to use <a href="https://azure.microsoft.com/en-us/products/key-vault/" target="_blank" rel="noreferrer noopener">Azure Key Vault</a>, then you also need the following Python libraries:</p>



<ul class="wp-block-list">
<li>azure-identity</li>



<li>azure-key-vault</li>
</ul>



<p>You can install the OpenAI Python library using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install&nbsp;</em>openai</li>



<li><em>conda install&nbsp;</em>openai&nbsp;(if you are using the Anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading">Step #1 Authentification and DB Setup</h3>



<p>Let&#8217;s start with the authentification and setup of the API keys. After making necessary imports, the code gets things read to connect to essential services &#8211; OpenAI and Cosmos DB &#8211; and makes sure it can access these services properly.</p>



<ol class="wp-block-list">
<li><strong>Fetching Credentials:</strong> The script starts by setting up a connection to a service called Azure Key Vault to retrieve some crucial credentials securely. These are like &#8220;passwords&#8221; that the script needs to access various resources.</li>



<li><strong>Setting Up AI Services:</strong> Then, it prepares to connect to two different AI services. One is a version that&#8217;s hosted by Azure, and the other is the standard, public version.</li>



<li><strong>Establishing Database Connection:</strong> Lastly, the script sets up a connection to a database service, specifically to a certain collection within the Cosmos DB database. The script also checks if the connection to the database was successful by sending a &#8220;ping&#8221; &#8211; if it receives a response, it knows the connection is good.</li>
</ol>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">from azure.identity import AzureCliCredential
from azure.keyvault.secrets import SecretClient
import openai
import logging
import tiktoken
import pandas as pd
import pymongo
from dotenv import load_dotenv
load_dotenv()
# Set up the Azure Key Vault client and retrieve the Blob Storage account credentials
keyvault_name = ''
openaiservicename = ''
client = SecretClient(f&quot;https://{keyvault_name}.vault.azure.net/&quot;, AzureCliCredential())
print('keyvault service ready')
# AzureOpenAI Service
def setup_azureopenai():
    openai.api_key = client.get_secret('openai-api-key').value
    openai.api_type = &quot;azure&quot;
    openai.api_base = f'https://{openaiservicename}.openai.azure.com'
    openai.api_version = '2023-05-15'
    print('azure openai service ready')
# public openai service
def setup_public_openai():
    openai.api_key = client.get_secret('openai-api-key-public').value
    print('public openai service ready')
DB_NAME = &quot;hephaestus&quot;
COLLECTION_NAME = 'isocodes'
def setup_cosmos_connection():
    COSMOS_CLUSTER_CONNECTION_STRING = client.get_secret('cosmos-cluster-string').value
    cosmosclient = pymongo.MongoClient(COSMOS_CLUSTER_CONNECTION_STRING)
    db = cosmosclient[DB_NAME]
    collection = cosmosclient[DB_NAME][COLLECTION_NAME]
    # Send a ping to confirm a successful connection
    try:
        cosmosclient.admin.command('ping')
        print(&quot;Pinged your deployment. You successfully connected to MongoDB!&quot;)
    except Exception as e:
        print(e)
    return collection, db
setup_public_openai()
collection, db = setup_cosmos_connection()</pre></div>



<p>Now we have set things up to interact with our Cosmos DB Mong DB vCore instance.</p>



<h3 class="wp-block-heading">Step #2 Functions for Populating the Vector DB</h3>



<p>Next, we prepare and insert data into the database as embeddings. First, we prepare the content. The preparation process involves turning the text content into embeddings. Each embedding is a list of flats representing the meaning of a specific part of the text in a way the AI system can understand.</p>



<p>We create the embeddings by sending text (for example, a paragraph of a document) to an OpenAI embedding model that returns the embedding. There are two options for using OpenAI: You can use the Azure OpenAI engine and deploy your own Ada embedding model. Alternatively, you can use the public OpenAI Ada embedding model. </p>



<p>We&#8217;ll use the public OpenAI&#8217;s <a href="https://platform.openai.com/docs/guides/embeddings" target="_blank" rel="noreferrer noopener">text-embedding-ada-002</a>. Remember that the model is designed to return embeddings, not text. Model inference may incur costs based on the data processed. Refer to <a href="https://openai.com/pricing" target="_blank" rel="noreferrer noopener">OpenAI </a>or Azure OpenAI service for pricing details. </p>



<p>Finally, the code inserts the prepared requests (which now include both the original text and the corresponding embeddings) into the database. The function returns the unique IDs assigned to these newly inserted items in the database. In this way, the code processes and stores the necessary information in the database for later use.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># prepare content for insertion into cosmos db
def prepare_content(text_content):
  embeddings = create_embeddings_with_openai(text_content)
  request = [
    {
    &quot;textContent&quot;: text_content, 
    &quot;vectorContent&quot;: embeddings}
  ]
  return request
# create embeddings
def create_embeddings_with_openai(input):
    #print('Generating response from OpenAI...')
    ###### uncomment for AzureOpenAI model usage and comment code below
    # embeddings = openai.Embedding.create( 
    #     engine='&lt;name of the embedding deployment &gt;', 
    #     input=input)[&quot;data&quot;][0][&quot;embedding&quot;]
    ###### public openai model usage and comment code above
    embeddings = openai.Embedding.create(
        model='text-embedding-ada-002', 
        input=input)[&quot;data&quot;][0][&quot;embedding&quot;]
    
    # Number of embeddings    
    # print(len(embeddings))
    return embeddings
# insert the requests
def insert_requests(text_input):
    request = prepare_content(text_input)
    return collection.insert_many(request).inserted_ids
# Creates a searchable index for the vector content
def create_index():
  
  # delete and recreate the index. This might only be necessary once.
  collection.drop_indexes()
  embedding_len = 1536
  print(f'creating index with embedding length: {embedding_len}')
  db.command({
    'createIndexes': COLLECTION_NAME,
    'indexes': [
      {
        'name': 'vectorSearchIndex',
        'key': {
          &quot;vectorContent&quot;: &quot;cosmosSearch&quot;
        },
        'cosmosSearchOptions': {
          'kind': 'vector-ivf',
          'numLists': 100,
          'similarity': 'COS',
          'dimensions': embedding_len
        }
      }
    ]
  })
# Resets the DB and deletes all values from the collection to avoid dublicates
#collection.delete_many({})</pre></div>



<h3 class="wp-block-heading">Step #3 Document Cracing and Populating the DB</h3>



<p>The next step is to break down the PDF document into smaller chunks of text (in this case, &#8216;records&#8217;) and then process these records for future use. You can repeat this process for any document that you want to make available to OpenAI. </p>



<p>You can use any PDF that you like as long as you it contains readable text (use OCR). For demo purposes, I will use a <a href="https://www.zh.ch/content/dam/zhweb/bilder-dokumente/themen/steuern-finanzen/steuern/quellensteuer/infobl%C3%A4tter/div_q_informationsblatt_qs_2021_EN.pdf" target="_blank" rel="noreferrer noopener">tax document from Zurich</a>. Put the document in the folder data/vector_db_data/ in your root folder and provide the name to the Python script. </p>



<p>Want to read in many documents at once? If you want to insert many documents, read the pdf documents from the folder and use the names to populate a list. You can then surround the insert function with a for loop that iterates through the list of document names </p>



<h4 class="wp-block-heading">#3.1 Document Slicing Considerations </h4>



<p>To convert a PDF into embeddings, the first step is to divide it into smaller content slices. The slicing process plays a crucial role as it affects the information provided to the OpenAI GPT model when answering user questions. If the slices are too large, the model may encounter token limitations. Conversely, if they are too small, the model may not receive sufficient content to answer the question effectively. It is important to strike a balance between the number of slices and their length to optimize the results, considering that the search process may yield multiple outcomes.</p>



<p>There are several approaches to handle the slicing process. One option is to define the slices based on a specific number of sentences or paragraphs. Alternatively, you can iteratively slice the document, allowing for some overlap between the data in the vector database. This approach has the advantage of providing more precise information to answer questions, but it also increases the data volume in the vector database, which can impact speed and cost considerations.</p>



<h4 class="wp-block-heading">#3.2 Running the code below to crack a document and insert embeddings into the vector DB</h4>



<p>Running the code below will first define a function that breaks text into separate paragraphs based on line breaks. Another function slices the PDF into records. Each record contains a certain number of sentences (the maximum is defined by the &#8216;max_sentences&#8217; value). We use a Python library called PyPDF2 to extract text from each page of the PDF and Python&#8217;s built-in regular expressions to split the text into sentences and paragraphs. Note that if you want to achieve better results, you could also use a professional document content extraction tool such as Azure form recognizer.</p>



<p>The code then opens a specific PDF file (&#8216;zurich_tax_info_2023.pdf&#8217;) and slices it into records, each containing no more than a certain number of sentences (as defined by&#8217;max_sentences&#8217;). After that, the function inserts these records into the vector database. Finally, we print the count of documents in the database collection. This shows how many pieces of data are already stored in this specific part of the database.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># document cracking function to insert data from the excel sheet
def split_text_into_paragraphs(text):
    paragraphs = re.split(r'\n{2,}', text)
    return paragraphs
def slice_pdf_into_records(pdf_path, max_sentences):
    records = []
    
    with open(pdf_path, 'rb') as file:
        reader = PyPDF2.PdfReader(file)
        
        for page in reader.pages:
            text = page.extract_text()
            paragraphs = split_text_into_paragraphs(text)
            
            current_record = ''
            sentence_count = 0
            
            for paragraph in paragraphs:
                sentences = re.split(r'(?&lt;=[.!?])\s+', paragraph)
                
                for sentence in sentences:
                    current_record += sentence
                    
                    sentence_count += 1
                    
                    if sentence_count &gt;= max_sentences:
                        records.append(current_record)
                        current_record = ''
                        sentence_count = 0
                
                if sentence_count &lt; max_sentences:
                    current_record += ' '  # Add space between paragraphs
            
            # If there is remaining text after the loop, add it as a record
            if current_record:
                records.append(current_record)
    
    return records
# get file from root/data folder
pdf_path = '../data/vector_db_data/zurich_tax_info_2023.pdf'
max_sentences = 20  # Adjust the slice size as per your requirement
result = slice_pdf_into_records(pdf_path, max_sentences)
# print the length of result
print(f'{len(result)} vectors created with maximum {max_sentences} sentences each.')
# Print the sliced records
for i, record in enumerate(result):
    insert_requests(record)
    if i &lt; 5:
        print(record[0:100])
        print('-------------------')
create_index()
print(f'number of records in the vector DB: {collection.count_documents({})}')</pre></div>



<p>After slicing the document and inserting the embeddings into the vector database, we can proceed with functions for similarity search and prompting. </p>



<h3 class="wp-block-heading">Step #4 Functions for Similarity Search and Prompts to ChatGPT</h3>



<p>This section of code provides a set of functions to perform a vector search in the Cosmos DB, make a request to the ChatGPT 3.5 Turbo model for generating responses, and create prompts for the OpenAI model to use in generating those responses.</p>



<h4 class="wp-block-heading">#4.1 How the Search Part Works </h4>



<p><br>Allow me to provide a concise explanation of how the search process operates. We have now reached the stage where a user poses a question, and we utilize the OpenAI model to supply an answer, drawing from our vector database. Here, it&#8217;s vital to understand that the model transforms the question into embeddings and subsequently scours the knowledge base for similar embeddings that align with the information requested in the user&#8217;s prompt. </p>



<p>The vector database yields the most suitable results and inserts them into another prompt tailored for ChatGPT. This model, distinct from the embedding model, generates text. Thus, the final interaction with the ChatGPT model incorporates both the user&#8217;s question and the results from the vector database, which are the most fitting responses to the question. This combination should ideally aid the model in providing the appropriate answer. Now, let&#8217;s turn our attention to the corresponding code.</p>



<h4 class="wp-block-heading">#4.2 Setting up the Functions for Vector Search</h4>



<p>The vector_search function takes as input a query vector (representing a user&#8217;s question in vector form) and an optional parameter to limit the number of results. It then conducts a search in the Cosmos DB, looking for entries whose vector content is most similar to the query vector.</p>



<p>Next, the openai_request function makes a request to OpenAI&#8217;s ChatGPT 3.5 Turbo model to generate a response. This function takes a formatted conversation history (or &#8216;prompt&#8217;) and sends it to the model, which then generates a response. The content of the generated response is then returned.</p>



<p>The create_tweet_prompt function constructs the conversation history for the OpenAI model. This function takes the user&#8217;s question and a JSON object containing results from a database search and constructs a list of system and user messages. This list will then serve as the prompt for the ChatGPT model, instructing it to generate a response that answers the user&#8217;s question about tax, with the added guideline that the response should be in the same language as the question. The constructed prompt is then returned by the function.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Cosmos DB Vector Search API Command
def vector_search(vector_query, max_number_of_results=2):
  results = collection.aggregate([
    {
      '$search': {
        &quot;cosmosSearch&quot;: {
          &quot;vector&quot;: vector_query,
          &quot;path&quot;: &quot;vectorContent&quot;,
          &quot;k&quot;: max_number_of_results
        },
      &quot;returnStoredSource&quot;: True
      }
    }
  ])
  return results
# openAI request - ChatGPT 3.5 Turbo Model
def openai_request(prompt, model_engine='gpt-3.5-turbo'):
    completion = openai.ChatCompletion.create(model=model_engine, messages=prompt, temperature=0.2, max_tokens=500)
    return completion.choices[0].message.content
# define OpenAI Prompt for News Tweet
def create_prompt(user_question, result_json):
    instructions = f'You are an assistant that answers questions based on sources provided. \
    If the information is not in the provided source, you answer with &quot;I don\'t know&quot;. '
    task = f&quot;{user_question} Translate the response to english /n \
    source: {result_json}&quot;
    
    prompt = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: instructions }, 
              {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: task }]
    return prompt</pre></div>



<p>You can easily change the voice and tone in which the ChatGPT answers questions by including the respective instructions in the create_prompt function. </p>



<p>Also: <a href="https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/">ChatGPT Style Guide: Understanding Voice and Tone Prompt Options for Engaging Conversations</a></p>



<h3 class="wp-block-heading">Step #5 Testing the Custom ChatGPT Solution</h3>



<p>This part of the code works with the previous functions to facilitate a complete question-answering cycle with Cosmos DB and OpenAI&#8217;s ChatGPT 3.5 Turbo model.</p>



<p>Now comes the most exciting part. Testing the solution, you can define a question and then execute the code below to run the search process. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># define OpenAI Prompt 
users_question = &quot;When do I have to submit my tax return?&quot;
# generate embeddings for the question
user_question_embeddings = create_embeddings_with_openai(user_question)
# search for the question in the cosmos db
search_results = vector_search(user_question_embeddings, 1)
print(search_results)
# prepare the results for the openai prompt
result_json = []
# print each document in the result
# remove all empty values from the results json
search_results = [x for x in search_results if x]
for doc in search_results:
    display(doc.get('_id'), doc.get('textContent'), doc.get('vectorContent')[0:5])
    result_json.append(doc.get('textContent'))
# create the prompt
prompt = create_prompt(user_question, result_json)
display(prompt)
# generate the response
response = openai_request(prompt)
display(f'User question: {users_question}')
display(f'OpenAI response: {response}')</pre></div>



<p>&#8216;User question: When do I have to submit my tax return?&#8217;</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;disableCopy&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">'OpenAI response: When do I have to submit my tax return? \n\nAll natural persons who had their residence in the canton of Zurich on December 31, 2022, or who owned properties or business premises (or business operations) in the canton of Zurich, must submit a tax return for 2022 in the calendar year 2023. Taxpayers with a residence in another canton also have to submit a tax return for 2022 in the calendar year 2023 if they ended their tax liability in the canton of Zurich by giving up a property or business premises during the calendar year 2022. If you turned 18 in the tax period 2022 (persons born in 2004), you must submit your own tax return (for the tax period 2022) for the first time in the calendar year 2023.'</pre></div>



<p>As of Mai 2023, the knowledge base of ChatGPT 3.5 is limited to the timeframe before September 2021. So it&#8217;s evident that the response of our custom ChatGPT solution is based on the individual information provided in the vector database. Remember that we did not fine-tune the GPT model, so the model itself does not inherently know anything about your private data and instead uses the data that was dynamically provided to it as part of the prompt. </p>



<h2 class="wp-block-heading">Real-world Applications of Chat with your data</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Custom ChatGPT boosts efficiency, personalizes services, and improves experiences across industries. Here are some examples:</p>



<ul class="wp-block-list">
<li><strong>Customer Support:</strong> Companies can use ChatGPT for 24/7 customer service. With data from manuals, FAQs, and support docs, it delivers fast, accurate answers, enhancing customer satisfaction and lessening staff workload.</li>



<li><strong>Healthcare</strong>: ChatGPT can respond to patient questions using medical texts and care guidelines. It offers data on symptoms, treatments, side effects, and preventive care, helping both healthcare providers and patients.</li>



<li><strong>Legal Sector</strong>: Law firms can use ChatGPT with legal texts, court decisions, and case studies for answering legal questions, offering case references, or explaining legal terms.</li>



<li><strong>Financial Services:</strong> Banks can use ChatGPT to extend their customer service and give customers advice based on their individual financial situation.</li>



<li><strong>E-Learning:</strong> Schools and e-learning platforms can use ChatGPT to tutor students. Using textbooks, notes, and research papers, it helps students understand complex topics, solve problems, or guide them through a course.</li>
</ul>



<p>In short, any sector needing a large information database for queries or services can use custom ChatGPT. It enhances engagement and efficiency by offering personalized experiences.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">Summary</h2>



<p>In this comprehensive guide, we&#8217;ve journeyed through the fascinating process of creating a customized ChatGPT that lets users chat with your business data. We started with understanding the immense value a tailored ChatGPT brings to the table and dove into its ability to produce specialized responses sourced from a custom knowledge base. This tailored approach enhances user experiences, saves time, and bolsters productivity.</p>



<p>We went behind the scenes to reveal the vital elements of crafting a custom ChatGPT: OpenAI&#8217;s GPT models, data embeddings, and vector databases like Cosmos DB for Mongo DB vCore. We clarified how these components synergize to transcend the token limitations inherent to GPT models. By integrating the components in Python, we broadened ChatGPT&#8217;s ability to answer queries based on your private knowledgebase, thereby offering contextually appropriate responses.</p>



<p>I hope this tutorial was able to illustrate the business value of ChatGPT and its versatile utility across a variety of sectors, including customer service, healthcare, legal services, finance, e-learning, and CRM data analytics. Each instance emphasized the transformative potential of a personalized ChatGPT in delivering efficient, targeted solutions.</p>



<p>I hope you found this helpful article. If you have any questions or remarks, please drop them in the comment section.</p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<ul class="wp-block-list">
<li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/introduction" target="_blank" rel="noreferrer noopener">Azure Cosmos DB</a></li>



<li><a href="https://openai.com/pricing" target="_blank" rel="noreferrer noopener">OpenAI pricing</a></li>



<li><a href="https://learn.microsoft.com/en-us/azure/cognitive-services/openai/">Azure OpenAI</a></li>



<li><a href="https://azure.microsoft.com/en-au/products/cognitive-services/openai-service" target="_blank" rel="noreferrer noopener">Semantic search</a></li>



<li><a href="https://platform.openai.com/docs/guides/embeddings" target="_blank" rel="noreferrer noopener">What are embeddings?</a></li>



<li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/vcore/vector-search" target="_blank" rel="noreferrer noopener">Using vector search on embeddings in Azure Cosmos DB for MongoDB vCore</a></li>



<li>OpenAI ChatGPT helped to revise this article</li>



<li>Images created with <a href="https://www.midjourney.com/home/?callbackUrl=%2Fapp%2F" target="_blank" rel="noreferrer noopener">Midjourney</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/">Building &#8220;Chat with your Data&#8221; Apps using Embeddings, ChatGPT, and Cosmos DB for Mongo DB vCore</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/step-by-step-guide-to-building-your-own-chatgpt-on-a-custom-knowledge-base-in-python-leveraging-mongo-db-and-embeddings/13687/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">13687</post-id>	</item>
		<item>
		<title>Using LLMs (OpenAI&#8217;s ChatGPT) to Streamline Digital Experiences</title>
		<link>https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/</link>
					<comments>https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Mon, 27 Mar 2023 08:35:21 +0000</pubDate>
				<category><![CDATA[Finance]]></category>
		<category><![CDATA[Healthcare]]></category>
		<category><![CDATA[Insurance]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Marketing Automation]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Use Cases]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[AI in Finance]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=13171</guid>

					<description><![CDATA[<p>In the age of information overload, finding what you need quickly and efficiently is more important than ever. OpenAI&#8217;s GPT technology has the potential to reduce friction between products and services, making it easier for individuals and businesses to find what they need. In this article, we&#8217;ll explore some specific examples of how OpenAI is ... <a title="Using LLMs (OpenAI&#8217;s ChatGPT) to Streamline Digital Experiences" class="read-more" href="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/" aria-label="Read more about Using LLMs (OpenAI&#8217;s ChatGPT) to Streamline Digital Experiences">Read more</a></p>
<p>The post <a href="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/">Using LLMs (OpenAI&#8217;s ChatGPT) to Streamline Digital Experiences</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>In the age of information overload, finding what you need quickly and efficiently is more important than ever. OpenAI&#8217;s GPT technology has the potential to reduce friction between products and services, making it easier for individuals and businesses to find what they need. In this article, we&#8217;ll explore some specific examples of how OpenAI is already making a difference and what we can expect in the future.</p>



<p>Also: </p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/openai-gpt-chatgpt-in-a-business-context-whats-the-value-proposition/12282/" target="_blank" rel="noreferrer noopener">What is the value proposition of OpenAI&#8217;s GPT models?</a></li>



<li><a href="https://www.relataly.com/exploring-the-journey-of-the-swiss-economy-in-adopting-openai-chatgpt-and-co/13486/" target="_blank" rel="noreferrer noopener">Exploring the Journey of the Swiss Economy in Adopting OpenAI&#8217;s ChatGPT and Co</a></li>
</ul>



<h2 class="wp-block-heading">What is Meant With Digital Friction?</h2>



<p>Digital friction refers to any obstacles or inefficiencies that users may encounter when interacting with digital products or services. This can include things like slow-loading websites, confusing user interfaces, or difficult-to-navigate online forms. </p>



<p>Essentially, any aspect of a digital product or service that makes it more difficult or frustrating for users to achieve their desired outcome can be considered a form of digital friction. Reducing digital friction is a key goal of many businesses and organizations, as it can help to improve user satisfaction, drive conversions, and increase overall engagement with digital products and services.</p>



<p>But what about the friction that still exists when we have to Google something? Is that already a form of friction? I would argue yes. The bias of search engines towards paid results can also create friction for users seeking unbiased information. As a result, it has become common for users to search on Google and other websites separately to gain a comprehensive overview of products or services since search engines may not provide a complete picture. Having to enter a search query into a search engine manually is a form of friction that GPT can help eliminate.</p>



<p>Also: <a href="https://www.relataly.com/mastering-prompt-engineering-for-chatgpt-a-practical-guide-for-businesses/13134/" target="_blank" rel="noreferrer noopener">Mastering Prompt Engineering for ChatGPT</a> </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Examples of How OpenAI GPT Reduces Digital Friction</h2>



<p>With OpenAI GPT models, we can expect to see a future where we no longer have to search for information, but rather, it will be readily available to us through natural language conversations with our devices.</p>



<p>By leveraging the power of artificial intelligence, large generative language models are capable of reducing any friction between products and services, enabling users to access information quickly and effortlessly. The key is their ability to understand and reason over natural language. </p>



<ul class="wp-block-list">
<li>Users can communicate with GPT models using natural language and express their intent. </li>



<li>GPT can go through large amounts of data and return an aggregated result</li>
</ul>



<p>As we continue to see advancements in artificial intelligence, I believe we are on the cusp of a new era of technology that will redefine how we interact with the world around us. With OpenAI GPT, we can expect to see a future where accessing information is no longer a chore, but rather a seamless and intuitive experience. In the following, we will discuss four examples.</p>



<p>Also: <a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/">9 Powerful Applications of OpenAI’s ChatGPT and Davinci for Your Business</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="365" data-attachment-id="13217" data-permalink="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-copy-min-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-Copy-min-min.png" data-orig-size="1121,800" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-Copy-min-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-Copy-min-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-Copy-min-min-512x365.png" alt="People iceskating how openai reduces friction" class="wp-image-13217" srcset="https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-Copy-min-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-Copy-min-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-Copy-min-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_people_ice_skating_in_the_mounts_with_data_and_digital_e_f54e3e95-59f7-4fa0-8078-9aa14f5a27c0-Copy-min-min.png 1121w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">With the rise of OpenAI GPT, we can expect to see even more seamless interactions between products and services.</figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h3 class="wp-block-heading">Customer Service ChatBots</h3>



<p>Before OpenAI, chatbots were often limited in their ability to understand and respond to customer inquiries. They relied on keyword matching and pre-programmed responses, which could lead to frustration for customers who weren&#8217;t getting the help they needed. With OpenAI, chatbots can now use natural language processing to understand the context of a customer&#8217;s inquiry and provide more accurate and helpful responses. This reduces friction by speeding up the process of resolving customer issues and increasing customer satisfaction.</p>



<p>Businesses can benefit from OpenAI-powered chatbots by reducing the workload of customer service agents. With chatbots able to handle routine inquiries, agents can focus on more complex tasks that require human expertise. This results in a more efficient use of resources, allowing businesses to provide better service to their customers while maximizing their operational efficiency.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h3 class="wp-block-heading">E-commerce Product Recommendations</h3>



<p>In the past, product recommendations were often based on simple algorithms that looked at a customer&#8217;s browsing history or purchase history. However, these recommendations were often too simplistic and didn&#8217;t take into account a customer&#8217;s preferences or interests. With OpenAI, product recommendations can now be based on more complex algorithms that take into account a wider range of data, such as customer reviews and social media activity. </p>



<p>Furthermore, the recent <a href="https://openai.com/blog/chatgpt-plugins" target="_blank" rel="noreferrer noopener">release of ChatGPT plugins</a> has enabled it to browse the web. This means that it can now take into account information from websites and aggregate the result. This allows ChatGPT to provide even more accurate and relevant recommendations to customers. In the future, there is a possibility that generative language models like ChatGPT can present a comprehensive view rather than a biased fragment.</p>



<h3 class="wp-block-heading">Language Translation Services</h3>



<p>In the past, language translation services often relied on machine translation, which had several limitations. Machine translation typically used rule-based algorithms that had difficulty with idiomatic expressions, cultural nuances, and colloquialisms. This often led to translations that were inaccurate or awkward, causing confusion or misunderstandings. In addition, machine translation was often unable to recognize and correct errors in the original text, leading to further inaccuracies in the translation.</p>



<p>However, with the advent of OpenAI and its advanced neural networks, language translation services can now produce more accurate and natural translations. OpenAI&#8217;s neural networks are trained on large amounts of data, allowing them to recognize and adapt to a wider range of linguistic features, such as idioms, slang, and regional variations. This makes the translations produced by OpenAI much more accurate and natural-sounding than those produced by traditional machine translation.</p>



<p>Improved translation capabilities can help to make content more widely accessible to people who speak different languages. This can be particularly beneficial for businesses and organizations that operate in multiple countries or regions, as it allows them to reach a wider audience and communicate more effectively with customers or stakeholders who may speak different languages. </p>



<h3 class="wp-block-heading">Virtual Assistants</h3>



<p>In the past, virtual assistants were often limited in their ability to understand and respond to users&#8217; requests due to their reliance on pre-programmed responses. With OpenAI, virtual assistants can now use natural language processing to better understand and respond to users&#8217; requests, reducing the friction of having to repeat requests or navigate through a confusing user interface. This can improve the user experience and increase engagement with the product or service.</p>



<p>With the increasing capabilities of large language models like OpenAI&#8217;s GPT, we are likely to see the development of digital assistants that can help us with a wide range of day-to-day tasks. These assistants could use natural language processing to understand our requests and preferences, and then use machine learning algorithms to generate personalized recommendations and solutions.</p>



<p>For example, a digital assistant based on GPT could help us to organize our schedules, book appointments, make travel arrangements, and even order groceries or meals. By reducing the friction associated with these tasks, these digital assistants could help us to save time and increase our overall productivity and efficiency.</p>



<p>Also: <a href="https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/" target="_blank" rel="noreferrer noopener">ChatGPT Style Guide: Understanding Voice and Tone Prompt Options for Engaging Conversations</a></p>



<h3 class="wp-block-heading">Customized Content Creation</h3>



<p>Creating high-quality content can be time-consuming and challenging, especially for businesses or individuals without extensive writing experience. With OpenAI, content creation can be made easier by providing users with AI-generated content suggestions or even full articles based on their desired topic or target audience. This is another example of how OpenAI can help reduce friction and streamline tasks, ultimately making it easier for individuals and businesses to succeed in today&#8217;s digital landscape.</p>



<p>With OpenAI, businesses and individuals can use AI-generated content to create highly customized products and services that stand out from the competition. For example, a t-shirt company could use AI-generated designs to create truly unique and personalized shirts for their customers. This not only reduces the time and effort required for design work, but also allows for a higher level of customization and uniqueness in the final product. This can help businesses differentiate themselves in crowded markets and appeal to customers looking for something truly one-of-a-kind.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="506" height="512" data-attachment-id="13224" data-permalink="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1.png" data-orig-size="1024,1036" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1.png" src="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1-506x512.png" alt="With OpenAI, product recommendations can now be based on more complex algorithms that take into account a wider range of data, such as customer reviews and social media activity. " class="wp-image-13224" srcset="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1.png 506w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1.png 297w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-1.png 1024w" sizes="(max-width: 506px) 100vw, 506px" /><figcaption class="wp-element-caption">With OpenAI, product recommendations can now be based on more complex algorithms that take into account a wider range of data, such as customer reviews and social media activity. </figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>The advancements in OpenAI technology will significantly impact the digital landscape by reducing friction between users and products/services. From customer service chatbots and e-commerce product recommendations to language translation services and content creation, OpenAI has provided new and innovative solutions to improve user experience and efficiency. And these are just a few examples. We are just beginning to understand the possibilities of OpenAI GPT to reduce friction in the digital world, and much more innovations can be expected in the coming years.</p>



<p>Things are already moving very fast. With the recent release of OpenAI&#8217;s ChatGPT plugins, users can now enjoy the benefits of AI-generated content and web browsing, further expanding the capabilities of digital assistants. As OpenAI continues to develop and refine its technology, we can expect to see even more exciting applications and use cases emerge, ultimately shaping the future of digital interactions.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="508" data-attachment-id="13227" data-permalink="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/a_robot_with_ice_skates_colourful_popart/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/A_robot_with_ice_skates_colourful_popart.png" data-orig-size="998,990" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="A_robot_with_ice_skates_colourful_popart" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/A_robot_with_ice_skates_colourful_popart.png" src="https://www.relataly.com/wp-content/uploads/2023/03/A_robot_with_ice_skates_colourful_popart-512x508.png" alt="" class="wp-image-13227" srcset="https://www.relataly.com/wp-content/uploads/2023/03/A_robot_with_ice_skates_colourful_popart.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/A_robot_with_ice_skates_colourful_popart.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/A_robot_with_ice_skates_colourful_popart.png 140w, https://www.relataly.com/wp-content/uploads/2023/03/A_robot_with_ice_skates_colourful_popart.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/A_robot_with_ice_skates_colourful_popart.png 998w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">Get ready to put on your skates! We are just beginning to understand how OpenAI GPT can reduce friction in the digital world.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<p><a href="https://techcrunch.com/2023/03/23/openai-connects-chatgpt-to-the-internet/?guccounter=1&amp;guce_referrer=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&amp;guce_referrer_sig=AQAAAH7tUcVBhStwBX4ICPpSEx63ufioYVR517HUJIx37411lJlkyacPSyWESvOTGyV461wR4XTjULRl3olqnjZvYcWZ0dgLH28cIkk7jwboUfQn3bWz3SkurPvm9b8i7U0pOnKBUaOfgS4KgXPbAXgf2tcoVFCAjpOUdA60n-J9fEYz" target="_blank" rel="noreferrer noopener">TechCrunch &#8211; OpenAI connects ChatGPT to the internet.</a><br>Images created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a>.<br>ChatGPT helped to revise this article.<br></p>
<p>The post <a href="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/">Using LLMs (OpenAI&#8217;s ChatGPT) to Streamline Digital Experiences</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">13171</post-id>	</item>
		<item>
		<title>9 Business Use Cases of OpenAI&#8217;s ChatGPT</title>
		<link>https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/</link>
					<comments>https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sat, 25 Feb 2023 16:30:48 +0000</pubDate>
				<category><![CDATA[Finance]]></category>
		<category><![CDATA[Healthcare]]></category>
		<category><![CDATA[Insurance]]></category>
		<category><![CDATA[Language Generation]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Manufacturing]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Telecommunications]]></category>
		<category><![CDATA[Use Cases]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[AI in Finance]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=12200</guid>

					<description><![CDATA[<p>You haven&#8217;t had enough of the recent hype about OpenAI? Fantastic! Let&#8217;s explore the business use cases for ChatGPT and other Large Language Models (LLMs). ChatGPT is often considered the beginning of a new era of AI adoption. A growing number of ChatGPT users are now using AI in their personal workflows. However, adoption in ... <a title="9 Business Use Cases of OpenAI&#8217;s ChatGPT" class="read-more" href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/" aria-label="Read more about 9 Business Use Cases of OpenAI&#8217;s ChatGPT">Read more</a></p>
<p>The post <a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/">9 Business Use Cases of OpenAI&#8217;s ChatGPT</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>You haven&#8217;t had enough of the recent hype about OpenAI? Fantastic! Let&#8217;s explore the business use cases for ChatGPT and other Large Language Models (LLMs). ChatGPT is often considered the beginning of a new era of AI adoption. A growing number of <a href="https://www.reuters.com/technology/chatgpt-sets-record-fastest-growing-user-base-analyst-note-2023-02-01/" target="_blank" rel="noreferrer noopener">ChatGPT users</a> are now using AI in their personal workflows. However, adoption in a business context is lagging behind. Although decision-makers around the globe are highly interested in using OpenAI&#8217;s LLMs, their knowledge of use cases and implementation strategies is often vague. This article aims to offer some guidance on the topic and inspire by sharing insights from recent conversations with decision-makers and industry experts. We present nine Applications for GPT for which we can expect to see increasing adoption in the coming month:</p>





<p>Let&#8217;s discuss these cases in more detail. </p>



<p>Also: <a href="https://www.relataly.com/mastering-prompt-engineering-for-chatgpt-a-practical-guide-for-businesses/13134/" target="_blank" rel="noreferrer noopener">Mastering Prompt Engineering for ChatGPT for Business Use</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<div class="wp-block-kadence-infobox kt-info-box_d5a753-ee"><span class="kt-blocks-info-box-link-wrap info-box-link kt-blocks-info-box-media-align-top kt-info-halign-center"><div class="kt-blocks-info-box-media-container"><div class="kt-blocks-info-box-media kt-info-media-animate-none"><div class="kadence-info-box-image-inner-intrisic-container"><div class="kadence-info-box-image-intrisic kt-info-animate-none"><div class="kadence-info-box-image-inner-intrisic"><img decoding="async" data-attachment-id="12485" data-permalink="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/chatgpt-logo-02afa704b5-seeklogo-com/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/chatgpt-logo-02AFA704B5-seeklogo.com_.png" data-orig-size="296,300" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="chatgpt-logo-02AFA704B5-seeklogo.com" data-image-description="&lt;p&gt;chatGPT logo&lt;/p&gt;
" data-image-caption="&lt;p&gt;chatGPT logo&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/chatgpt-logo-02AFA704B5-seeklogo.com_.png" src="https://www.relataly.com/wp-content/uploads/2023/02/chatgpt-logo-02AFA704B5-seeklogo.com_.png" alt="chatGPT logo" width="296" height="300" class="kt-info-box-image wp-image-12485"/></div></div></div></div></div><div class="kt-infobox-textcontent"><h5 class="kt-blocks-info-box-title">What is it with OpenAI and ChatGPT?</h5><p class="kt-blocks-info-box-text">If you&#8217;ve been frozen in Carbonite for the past six months, you may have missed the whole hype on OpenAI and ChatGPT. Let&#8217;s bring you up to speed!<br/><br/>ChatGPT is a member of the family of GPT language models, which were developed by OpenAI. GPT stands for &#8220;Generative Pretrained Transformers.&#8221; These models are known for their ability to understand and generate human-like text. One of the key strengths of ChatGPT is its ability to understand the context of a conversation and generate appropriate responses. Although it&#8217;s not perfect and can sometimes make mistakes, it is a very powerful tool for generating and interpreting natural language text. </p></div></span></div>
</div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Top Business Applications for Generative Language Models</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The coming month will be exciting as we can expect to see the first wave of OpenAI use cases being implemented. So what can we expect? In the current economic situation, cost reduction is top of mind for many decision-makers. Business efforts will, therefore, likely focus on improving and optimizing the existing business processes rather than exploring new applications.</p>



<p>One of the critical reasons for this approach is that organizations need to gain experience with generative models to lay the foundation for working on more innovative solutions in the future. While traditional machine learning techniques are valuable for many applications, they have limitations when it comes to implementing OpenAI&#8217;s generative language models. </p>



<p>OpenAI&#8217;s GPT models are a form of general-purpose AI that uses a different approach to machine learning. Implementing these models requires new skills and knowledge. For example, prompt design and rethinking existing processes are crucial for effectively using OpenAI&#8217;s capabilities. This means that organizations need to invest in training and develop new expertise to leverage the new technology fully. </p>



<p>Before delving into use cases, it&#8217;s important to note that the categories were deliberately chosen to be generic and relevant across various industries. Additionally, to make the use cases as practical as possible, we&#8217;ve included examples for prompts and responses. For simplicity, this article doesn&#8217;t differentiate between various GPT-3 models but rather focuses on the use cases for ChatGPT and Davinci, which have similar capabilities. The primary distinction between the two models is that ChatGPT keeps track of conversation history, while Davinci treats each request separately.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large is-style-default"><img decoding="async" width="1024" height="730" data-attachment-id="12257" data-permalink="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/openai-business-use-cases-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/OpenAi-business-use-cases-min.png" data-orig-size="1111,792" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="OpenAi business use cases-min" data-image-description="&lt;p&gt;OpenAI ChatGPT Business Use Cases&lt;/p&gt;
" data-image-caption="&lt;p&gt;OpenAI ChatGPT Business Use Cases&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/OpenAi-business-use-cases-min.png" src="https://www.relataly.com/wp-content/uploads/2023/02/OpenAi-business-use-cases-min-1024x730.png" alt="OpenAI ChatGPT Business Use Cases" class="wp-image-12257" srcset="https://www.relataly.com/wp-content/uploads/2023/02/OpenAi-business-use-cases-min.png 1024w, https://www.relataly.com/wp-content/uploads/2023/02/OpenAi-business-use-cases-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/02/OpenAi-business-use-cases-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/02/OpenAi-business-use-cases-min.png 1111w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">OpenAI ChatGPT has various business use cases; not all are new. Image Source: Created with <a href="https://www.midjourney.com/app/" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-1-text-summarization">1. Text Summarization</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Today&#8217;s fast-paced business environment confronts organizations with an overwhelming amount of text and documents to process. From customer requests to contracts and product information, employees often spend countless hours sifting through information to understand and extract relevant insights. The inability to efficiently process text-based data can cause delays in critical business processes, leading to reduced productivity and increased costs. </p>



<p>OpenAI&#8217;s text summarization capabilities are a game-changer for businesses that need to process large amounts of text. By summarizing dense documents into a few key points or even a single title, businesses can increase process efficiency and improve decision-making. </p>



<p>Text summarization is helpful in various areas. For example, customer service, where customer inquiries via email can be numerous and time-consuming to address. In many cases, only a part of a conversation is relevant to the business, and employees spend a lot of time sifting through customer emails and chat messages. By using OpenAI, customer service representatives can quickly summarize the content of customer emails and identify the key issues that need to be addressed. This form of summarization can lay the foundation for delegating tasks to teams and individuals effectively. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h4 class="wp-block-heading">Example of GPT-3 Based Summarization</h4>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background"><strong><strong>Prompt</strong></strong><br>Summarize the following text into three sentences, each with a maximum of 20 words: <a href="https://en.wikipedia.org/wiki/Reinforcement_learning" target="_blank" rel="noreferrer noopener">https://en.wikipedia.org/wiki/Reinforcement_learning</a></p>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background"><strong>Response</strong><br>Reinforcement learning is an area of machine learning concerned with how software agents ought to take actions in an environment so as to maximize some notion of cumulative reward. Reinforcement learning is different from supervised learning as there is no labelled input/output pair. It can be applied to various real-world scenarios such as game playing, robotics, recommendation systems, and even in autonomous driving</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-2-message-triage-and-other-types-of-text-classification">2. Message Triage and Other Types of Text Classification</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The modern work environment is characterized by work sharing and specialization. However, this often leads to tasks landing on someone&#8217;s desk who may not be the best person to handle them, leading to delays in completing the task. This is where GPT models can be particularly useful. These models can classify text into categories, allowing organizations to automate the routing of incoming messages to the appropriate person or department. Prediction accuracy will benefit when the models are fine-tuned for a particular domain or industry. </p>



<p>Implementing GPT models for classification can yield significant benefits for organizations, enabling them to save time and resources while ensuring that messages and tasks are directed to the right person or department. For instance, organizations can use generative AI for email triage and prioritization by categorizing incoming messages and assigning them to specialized service teams, such as contract inquiries, relocations, claim-related issues, and general complaints. </p>



<p>In addition, sentiment analysis can be employed to gauge customer satisfaction or dissatisfaction in social media statements. Organizations can start with a semi-automated process, where they use OpenAI to assign labels to text, and a human then makes the final decision on who should handle the task. This can lead to increased efficiency and accuracy, as well as reduced response times and improved customer satisfaction.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="761" height="506" data-attachment-id="12500" data-permalink="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/tiny_construction_workers_working_on_piles_of_huge_documents-2-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/tiny_construction_workers_working_on_piles_of_huge_documents-2-min.png" data-orig-size="761,506" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="tiny_construction_workers_working_on_piles_of_huge_documents (2)-min" data-image-description="&lt;p&gt;tiny_construction_workers_working_on_piles_of_huge_documents relataly midjourney&lt;/p&gt;
" data-image-caption="&lt;p&gt;tiny_construction_workers_working_on_piles_of_huge_documents relataly midjourney&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/tiny_construction_workers_working_on_piles_of_huge_documents-2-min.png" src="https://www.relataly.com/wp-content/uploads/2023/02/tiny_construction_workers_working_on_piles_of_huge_documents-2-min.png" alt="tiny_construction_workers_working_on_piles_of_huge_documents relataly midjourney chatGPT OpenAI GPT-3" class="wp-image-12500" srcset="https://www.relataly.com/wp-content/uploads/2023/02/tiny_construction_workers_working_on_piles_of_huge_documents-2-min.png 761w, https://www.relataly.com/wp-content/uploads/2023/02/tiny_construction_workers_working_on_piles_of_huge_documents-2-min.png 300w" sizes="(max-width: 761px) 100vw, 761px" /><figcaption class="wp-element-caption">Processing large amounts of documents and text is a major pain point in many organizations. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div>
</div>



<h4 class="wp-block-heading">Example of GPT-3 Based Message Triage</h4>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background has-medium-font-size"><strong><strong>Prompt</strong></strong><br>Classify the following news article into 1 of the following categories: categories: [Business, Tech, Politics, Sport, Entertainment] news article: Donna Steffensen Is Cooking Up a New Kind of Perfection. The Internet’s most beloved cooking guru has a buzzy new book and a fresh new perspective: Classified category:</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background"><strong>Response</strong><br>Entertainment</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">3. Completeness of Information Checks</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Another challenge that many businesses face when processing natural language is incomplete information. For example, companies receive customer inquiries and orders via email or telephone. Customers may submit requests via email, social media, or telephone, and while it is convenient for them to state their issue in natural language, the messages may lack the necessary information to process their request further. This may include missing product or service information when the customer states his order, address changes where the new address is missing, or inquiries with missing order or ticket numbers. In these cases, a person must first reach out to the customer to collect the missing information and then again check if the information has been completed. </p>



<p>OpenAI can help to identify missing information and streamline information processing. For example, when a customer submits an order request via email, social media, or telephone, OpenAI can analyze the message and identify any missing product or service information, address changes, or order and ticket numbers. This can help customer service teams quickly address the issue and fulfill the request, ultimately improving customer satisfaction and loyalty. </p>



<p>If the AI identifies missing information, it can directly reach out to the customer to request it, enhancing the process efficiency even further. Additionally, combining OpenAI&#8217;s capabilities with text classification can streamline the process by automatically categorizing and prioritizing requests.</p>



<h4 class="wp-block-heading">Example of GPT-3 Based Completeness of Information Checks</h4>



<div class="wp-block-kadence-column kadence-column_3ae8f6-68"><div class="kt-inside-inner-col">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background"><strong>Prompt</strong><br>Determine if the numeric 5-digit claim number is present in the text below. Limit your answer to one of the following categories: [Yes, No] Text: &#8220;Awful airline! I have emailed you over 5 times over the past few months regarding my lost bag claim. I’ve included claim number, and details and I simply never get an answer. What a joke.&#8221; Classified category:</p>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background"><strong>Response</strong><br>No.</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-4-personalized-communication">4. Personalized Communication</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Personalized communication is key for businesses to achieve customer experience and satisfaction because it demonstrates that the company values each customer as an individual with unique needs and preferences. By customizing communication, businesses can provide targeted messages and recommendations that are relevant to each customer, making them feel seen and understood. This can lead to increased engagement, loyalty, and improved customer satisfaction. However, creating personalized communication usually takes a lot of time and resources. This is where GPT models can step in. </p>



<p>ChatGPT offers businesses the opportunity to enhance customer satisfaction, engagement, and sales through personalized communication. The model can generate individualized email campaigns, social media posts, and website/app experiences, creating a tailored and unique interaction for each customer. </p>



<p>As businesses begin to implement personalized communication, it may be beneficial to conduct a test phase during which humans review generated messages to ensure accuracy and relevance. Additionally, businesses can provide ChatGPT with additional information on customers, such as past purchases or preferences, to personalize messages further and increase the effectiveness of the communication strategy.</p>



<h4 class="wp-block-heading">Example of a GPT Prompt for Personalized Communication</h4>



<div class="wp-block-kadence-column kadence-column_b0b3a0-4b"><div class="kt-inside-inner-col">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background"><strong>Prompt</strong><br>Write a gentle answer to this customer request: Mr. Jong: I can’t believe I thought this was a quality company &#8211; I’m still waiting for my order despite being told over and over again that it would be delivered within 24 hours, only for me to have to chase again. So disappointed, don’t trust this company to fulfil orders as they say they will, and customer service haven’t helped at all.</p>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background has-medium-font-size"><strong>Response</strong> <br>Dear Mr. Jong,<br><br>I am sorry to hear that you have had a negative experience with our company. I can understand your frustration with the delay in receiving your order despite being promised a 24-hour delivery.<br><br>Please know that this is not the level of service that we strive to provide our customers. We take pride in ensuring that all our orders are fulfilled promptly and efficiently.<br><br>I would like to assure you that we are investigating this matter, and we will take the necessary steps to ensure that this doesn&#8217;t happen again in the future.<br><br>We value your business and appreciate your feedback. Our customer service team is always available to help and address any concerns you may have. Please don&#8217;t hesitate to reach out to us if you need any assistance.<br><br>Thank you for bringing this to our attention, and I hope we can earn back your trust and continue to serve you in the future.<br><br>Best regards,<br><br>[Your Name]<br></p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="504" height="503" data-attachment-id="12949" data-permalink="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/a_happy_grandpa_receiving_a_personalized_letter_white-relataly-gpt3-openai-personalzed-communicationi/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/a_happy_grandpa_receiving_a_personalized_letter_white-relataly-gpt3-openai-personalzed-communicationi.png" data-orig-size="504,503" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="a_happy_grandpa_receiving_a_personalized_letter_white-relataly-gpt3-openai-personalzed-communicationi" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/a_happy_grandpa_receiving_a_personalized_letter_white-relataly-gpt3-openai-personalzed-communicationi.png" src="https://www.relataly.com/wp-content/uploads/2023/03/a_happy_grandpa_receiving_a_personalized_letter_white-relataly-gpt3-openai-personalzed-communicationi.png" alt="" class="wp-image-12949" srcset="https://www.relataly.com/wp-content/uploads/2023/03/a_happy_grandpa_receiving_a_personalized_letter_white-relataly-gpt3-openai-personalzed-communicationi.png 504w, https://www.relataly.com/wp-content/uploads/2023/03/a_happy_grandpa_receiving_a_personalized_letter_white-relataly-gpt3-openai-personalzed-communicationi.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/a_happy_grandpa_receiving_a_personalized_letter_white-relataly-gpt3-openai-personalzed-communicationi.png 140w" sizes="(max-width: 504px) 100vw, 504px" /><figcaption class="wp-element-caption">Organizations can use GPT-3 to personalize customer interactions, which is crucial in delivering remarkable experiences. Image generated with Midjourney. </figcaption></figure>
</div>
</div>



<div style="height:12px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-5-document-comparison">5. Document Comparison</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>ChatGPT can help businesses to identify differences and similarities between two documents. This feature can be particularly useful in situations where businesses need to ensure the authenticity of important documents or when multiple collaborators work on the same document. For instance, a law firm can use ChatGPT to compare two versions of a contract and highlight any discrepancies or unusual changes. Additionally, ChatGPT can group similar documents together and identify instances of plagiarism, redundant information, or conflicting statements, which can save time and improve accuracy. </p>



<p>Areas, where document comparison with GPT models is particularly useful, include underwriting, purchasing, and contract management, especially in legal and contractual matters such as comparing versions of contracts, identifying unauthorized changes or unusual deviations from the norm, and ensuring compliance with regulations. </p>



<p>For example, in the insurance industry, underwriters can use ChatGPT to compare policy documents and ensure that there are no inconsistencies or errors in coverage. Purchasers can use ChatGPT to compare supplier contracts and ensure that prices, terms, and conditions are consistent across multiple agreements. In contract management, ChatGPT can help businesses track changes made to a contract over time and ensure that all parties are adhering to the agreed-upon terms. By utilizing ChatGPT for document comparison, businesses can maintain document integrity and improve their overall efficiency.</p>



<h4 class="wp-block-heading">Example of a Prompt for Document Comparison</h4>



<div class="wp-block-kadence-column kadence-column_80cf9d-5f"><div class="kt-inside-inner-col">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background"><strong><strong>Prompt</strong></strong><br>Compare the following two privacy statements and explain the difference:<br>Text 1: This website uses cookies, as do many other websites. Cookies are used to store information about visitors, including their preferences and which pages they have accessed or visited on the website. This information is used to optimize the user experience by customizing the content of our web pages based on the visitor&#8217;s browser type and other information.<br>Text 2: Like any other website, this website uses ‘cookies.’ These cookies are used to store information, including visitors’ preferences and the pages on the website that the visitor accessed or visited. The information is used to optimize the users’ experience by customizing our web page content based on visitors&#8217; browser type and/or other information.<br>We will definitely sell your information.</p>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background"><strong><strong>Response</strong></strong><br>There is a clear difference between the two privacy statements. Text 1 does not mention anything about selling the visitor&#8217;s information, while Text 2 includes the sentence &#8220;We will definitely sell your information.&#8221; This indicates that the website may not have ethical or lawful practices when it comes to handling visitor information, and it could potentially violate privacy laws. Additionally, Text 1 appears to be more professional and straightforward, while Text 2 includes a grammatical error in the first sentence. However, both texts mention the use of cookies to store visitor information and optimize the user experience.<br></p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="510" data-attachment-id="13186" data-permalink="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/openai-robot-comparing-documents-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-comparing-documents-min.png" data-orig-size="1024,1020" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="openai-robot-comparing-documents-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-comparing-documents-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-comparing-documents-min-512x510.png" alt="Generative AI can compare documents and spot differences or deviations from the norm. ChatGPT robot colorful pop art" class="wp-image-13186" srcset="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-comparing-documents-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-comparing-documents-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-comparing-documents-min.png 140w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-comparing-documents-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-comparing-documents-min.png 1024w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">Generative AI can compare documents and spot differences or deviations from the norm.</figcaption></figure>
</div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-6-reasoning-and-question-answering-over-a-knowledge-base">6. Reasoning and Question Answering over a Knowledge Base</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>OpenAI&#8217;s advanced machine learning models, such as the GPT series, have proven to be powerful tools for analyzing complex information. These can be either structured or unstructured data in individual documents or a comprehensive knowledge base. </p>



<p>Take financial data, for example. Balance statements can be a nightmare to interpret manually, but with OpenAI&#8217;s natural language processing, companies can automatically pinpoint trends and crucial information, making it easier to digest and act on financial data. And that&#8217;s just the beginning. By enhancing their solutions with techniques for summarization or advanced prompt engineering, organizations can generate complete reports with tables, further simplifying the digestion of complex information.</p>



<p>But OpenAI&#8217;s power extends beyond finance. In IoT (Internet of Things), analyzing sensor data can be a mind-bending challenge. OpenAI can help companies make sense of this data in real-time, identifying patterns and anomalies that might have otherwise gone unnoticed. This can be especially valuable in manufacturing, where even minor sensor data variations can significantly impact product quality and efficiency.</p>



<p>Also: <a href="https://www.relataly.com/predictive-maintenance-predicting-machine-failure-with-python/10618/" target="_blank" rel="noreferrer noopener">Predictive Maintenance: Predicting Machine Failure using Sensor Data with XGBoost and Python</a> </p>



<p>In short, OpenAI&#8217;s ability to analyze and reason over complex information is nothing short of revolutionary. With this technology, companies can make faster, more informed decisions based on large volumes of data. As technology continues to improve and evolve, the possibilities for AI are limitless. We can expect to see organizations using AI to interpret and analyze even more complex information in the years ahead, paving the way for a brighter, smarter future.</p>



<h4 class="wp-block-heading">Sample Prompt for Reasoning over Structured and Unstructured Data</h4>



<div class="wp-block-kadence-column kadence-column_8145a6-c2"><div class="kt-inside-inner-col">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background"><strong>Prompt</strong><br>Assess the financial situation of an enterprise with the following income statement: Income Statement All numbers in thousands Date 9/29/2022 9/29/2021 Total Revenue 387,537,000 394,328,000 Cost of Revenue 220,666,000 223,546,000 Gross Profit 166,871,000 170,782,000 Operating Expense 52,906,000 51,345,000 Operating Income 113,965,000 119,437,000 Total Operating Income as Reported 113,965,000 119,437,000 Total Expenses 273,572,000 274,891,000 Interest Income 3,043,000 2,825,000 Interest Expense 3,240,000 2,931,000 EBIT 116,725,000 122,034,000</p>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background"><strong>Response</strong><br>To assess the financial situation of the enterprise, we need to analyze the income statement and calculate the key financial ratios.<br>First, let&#8217;s look at the income statement. We can see that the company&#8217;s revenue has decreased slightly from 2021 to 2022. However, the cost of revenue has also decreased, resulting in a stable gross profit. Operating expenses have increased slightly, but the operating income remains relatively stable. Interest income has increased slightly, but interest expenses have also increased.<br><br>Now let&#8217;s calculate some financial ratios:<br><br>Gross Profit Margin = (Gross Profit / Total Revenue) x 100<br>= (166,871,000 / 387,537,000) x 100<br>= 43.0%<br>The gross profit margin measures how much profit the company makes after accounting for the cost of goods sold. A gross profit margin of 43.0% indicates that the company is able to generate a decent profit from its sales.<br><br>Operating Profit Margin = (Operating Income / Total Revenue) x 100<br>= (113,965,000 / 387,537,000) x 100<br>= 29.4%<br>The operating profit margin measures how much profit the company makes after accounting for all operating expenses. A margin of 29.4% indicates that the company is able to generate a good amount of profit from its operations.<br><br>&#8230;</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="508" height="504" data-attachment-id="12931" data-permalink="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/gpt-3-5-can-reason-over-complex-data-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/GPT-3.5-can-reason-over-complex-data-min.png" data-orig-size="508,504" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="GPT-3.5-can-reason-over-complex-data-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/GPT-3.5-can-reason-over-complex-data-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/GPT-3.5-can-reason-over-complex-data-min.png" alt="GPT-3.5 can reason over complex data." class="wp-image-12931" srcset="https://www.relataly.com/wp-content/uploads/2023/03/GPT-3.5-can-reason-over-complex-data-min.png 508w, https://www.relataly.com/wp-content/uploads/2023/03/GPT-3.5-can-reason-over-complex-data-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/GPT-3.5-can-reason-over-complex-data-min.png 140w" sizes="(max-width: 508px) 100vw, 508px" /><figcaption class="wp-element-caption">GPT-3.5 can reason over complex data like no other AI before.</figcaption></figure>
</div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-7-query-generation">7. Query Generation </h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>OpenAI ChatGPT can also assist businesses with SQL query generation. This is especially useful for non-technical users, who may not be familiar with SQL syntax or the structure of the database. With ChatGPT, users can simply ask natural language questions about the data they are interested in, and the model can generate the appropriate SQL queries to extract the relevant information.</p>



<p>This has the potential to greatly expand the user base that can directly interact with a database. Additionally, more advanced solutions can provide question-answering functionality based on the data residing in data warehouses (DWH). This can help businesses quickly extract insights and make data-driven decisions without the need for extensive technical knowledge. More advanced solutions will be able to provide question-answering functionality based on the data residing in a DWH, that are often perceived as black boxes by non-tech guys. This will expand the user base that can directly interact with a database and leverage the existing information. </p>



<h4 class="wp-block-heading">Sample Prompt for SQL Query Generation</h4>



<div class="wp-block-kadence-column kadence-column_d778a6-ee"><div class="kt-inside-inner-col">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background"><strong>Prompt</strong><br>Tables in the database: Customers, Purchases, Addresses. Tables are linked through a customer_id, which is present in all tables. Given an input question, respond with syntactically correct PostgreSQL. Input: Get the names and addresses of customers who made a purchase in the past week.</p>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background"><strong>Response</strong><br>Here&#8217;s the PostgreSQL query to get the names and addresses of customers who made a purchase in the past week: SELECT c.name, a.address FROM Customers c JOIN Purchases p ON c.customer_id = p.customer_id JOIN Addresses a ON c.customer_id = a.customer_id WHERE p.purchase_date &gt; now() &#8211; interval &#8216;1 week&#8217;; This query uses a JOIN operation to link the Customers, Purchases, and Addresses tables together using the customer_id field. It selects the name and address columns from the Customers and Addresses tables, respectively, and filters the results to include only purchases made in the past week using the WHERE clause with a date comparison.</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="506" height="512" data-attachment-id="13189" data-permalink="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min.png" data-orig-size="1024,1036" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min-506x512.png" alt="openai robot working with a sql database colorful pop art midjourney relataly. If ChatGPT can generate SQL queries, why not use these queries to return a result to the user directly?  " class="wp-image-13189" srcset="https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min.png 506w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min.png 297w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/openai-robot-working-with-a-sql-database-colorful-pop-art-midjourney-relataly-min.png 1024w" sizes="(max-width: 506px) 100vw, 506px" /><figcaption class="wp-element-caption">If ChatGPT can generate SQL queries, why not use these queries to return a result to the user directly?  </figcaption></figure>
</div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-8-language-translation">8. Language Translation</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Another powerful feature is ChatGPT&#8217;s language translation capacity. It can translate text in near real-time, allowing businesses to communicate with customers in their preferred language. While language translation is nothing but new, what sets ChatGPT apart is its ability to seamlessly integrate with any process by simply adding a &#8220;translate to&#8221; command to a prompt. As a result, ChatGPT has the potential to significantly lower language barriers and facilitate communication across international teams and channels.</p>



<p>By using ChatGPT for language translation, businesses can enhance their reach and improve customer satisfaction. ChatGPT&#8217;s language translation capabilities can be used to translate various types of content, such as customer service interactions, website content, and other communication channels. What&#8217;s even more impressive is that ChatGPT supports regional dialects like Swiss-German, making it a versatile tool for organizations operating in multilingual regions. </p>



<h4 class="wp-block-heading">Example of GPT-3 Based Language Translation</h4>



<div class="wp-block-kadence-column kadence-column_e5dfb5-a0 kb-section-dir-vertical"><div class="kt-inside-inner-col">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background"><strong><strong>Prompt</strong></strong><br>Translate to Swiss-German: ChatGPT can translate text in real-time, making it possible to communicate with customers in their preferred language. This can help businesses expand their reach and improve customer satisfaction. ChatGPT&#8217;s language translation capabilities are highly accurate and can be used to translate customer service interactions, website content, and other types of communication. By using ChatGPT for language translation, businesses can improve their ability to communicate with a global audience.</p>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background"><strong>Response</strong><br>ChatGPT cha verwendet werde, um Text in Echtzeit z&#8217;übersetze und ermöglicht so d&#8217;Kommunikation mit Kunden in ihre bevorzugte Sprach. Das cha Unternehme helfe, ihre Reichwiti z&#8217;vergrössere und d&#8217;Kundenzufriedeheit z&#8217;verbessere. ChatGPT&#8217;s Sprachübersetzigsfähigkeit isch hochpräzis und cha verwendt werde, um Kundeservice-Interaktione, Website-Inhalte und ander Arten vo Kommunikation z&#8217;übersetze. Durch d&#8217;Verwendig vo ChatGPT für d&#8217;Sprachübersetzig cha d&#8217;Kommunikationsfähigkeit vo Unternehme mit ere globale Zielgruppe verbessert werde.</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-9-content-generation">9. Content Generation</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Content generation is a critical aspect of modern business. It is vital in attracting and engaging customers, building brand awareness, and establishing thought leadership in a particular industry. As such, businesses invest significant resources in creating high-quality content that can capture the attention of their target audience. Such content ranges from blog posts and social media updates to product descriptions and website copy.</p>



<p>However, creating compelling and engaging content is not always easy. Businesses need to produce a large volume of content while ensuring that it is high-quality and relevant to their target audience. This is where OpenAI ChatGPT can assist.</p>



<p>ChatGPT can assist businesses with content generation in a variety of ways. For instance, it can generate unique and engaging content based on specific topics or keywords provided by the user, saving businesses time and resources. Moreover, ChatGPT can be trained to understand a business&#8217;s unique tone and voice. In this way, businesses can ensure that the generated content aligns with their brand and values.</p>



<p>Another way that ChatGPT can assist with content generation is by automating the content curation process. By analyzing and organizing vast amounts of data from various sources, including social media, blogs, news articles, and research papers, ChatGPT can generate curated content that is highly relevant and valuable to a business&#8217;s target audience. Some examples are product recommendations, email campaigns, or chatbot interactions that are tailored to each customer&#8217;s preferences and needs.</p>



<h4 class="wp-block-heading">Example of GPT-3 Based Content Generation</h4>



<div class="wp-block-kadence-column kadence-column_2cfc14-b4"><div class="kt-inside-inner-col">
<p class="has-contrast-3-color has-base-3-background-color has-text-color has-background"><strong>Prompt</strong><br>Generate three creative advertisement slogans for Cereals for the Japanese market. Be as creative as possible. Put in some Pokemon references.</p>



<p class="has-global-color-8-color has-base-3-background-color has-text-color has-background"><strong>Response</strong> <br>&#8220;Gotta catch &#8217;em all, starting with your breakfast bowl! Our cereals are the perfect fuel for your daily adventures!&#8221;<br>&#8220;Our cereals are so delicious, even Pikachu would choose them over berries!&#8221;<br>&#8220;Power up your mornings with our cereals, just like how trainers power up their Pokemon with berries!&#8221;</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="506" height="512" data-attachment-id="12830" data-permalink="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/orca-swimming-in-candy-content-generation-gpt-3-openai-relataly-midjourney-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/orca-swimming-in-candy-content-generation-gpt-3-openai-relataly-Midjourney-min.png" data-orig-size="508,514" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="orca-swimming-in-candy-content-generation-gpt-3-openai-relataly-Midjourney-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/orca-swimming-in-candy-content-generation-gpt-3-openai-relataly-Midjourney-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/orca-swimming-in-candy-content-generation-gpt-3-openai-relataly-Midjourney-min-506x512.png" alt="" class="wp-image-12830" srcset="https://www.relataly.com/wp-content/uploads/2023/03/orca-swimming-in-candy-content-generation-gpt-3-openai-relataly-Midjourney-min.png 506w, https://www.relataly.com/wp-content/uploads/2023/03/orca-swimming-in-candy-content-generation-gpt-3-openai-relataly-Midjourney-min.png 296w, https://www.relataly.com/wp-content/uploads/2023/03/orca-swimming-in-candy-content-generation-gpt-3-openai-relataly-Midjourney-min.png 508w" sizes="(max-width: 506px) 100vw, 506px" /><figcaption class="wp-element-caption">GPT-3 is great at content creation and can also come up with really creative content. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div>
</div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Conclusion</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>This article has outlined nine business applications that are likely to be the focus of the first wave of OpenAI adoption. While some of these applications, such as sentiment analysis, are not entirely new and can be accomplished with traditional NLP models, others like content generation are groundbreaking and were not previously possible.</p>



<p>The hype surrounding GPT models stems from their combination of versatility and performance. Unlike traditional models, generative AI can handle a variety of tasks simultaneously without requiring extensive training data. As a result, businesses can leverage generative AI to develop new use cases, as well as upgrade their existing processes and become more agile by outsourcing some of their decision logic to generative AI.</p>



<p>It will be fascinating to witness the development of generative AI and how it will transform how we work and communicate in the future. The emergence of generative AI is often compared to the introduction of the iPhone, and just as the iPhone has evolved over time, so too will generative AI. If we think of GPT-3 as the third generation of the iPhone, we can only imagine what the future holds.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<ul class="has-contrast-color has-text-color wp-block-list">
<li><a href="https://www.reuters.com/technology/chatgpt-sets-record-fastest-growing-user-base-analyst-note-2023-02-01/" target="_blank" rel="noreferrer noopener">Reuter.com/chatgpt-sets-record-fastest-growing-user-base-analyst/</a></li>



<li><a href="https://platform.openai.com/docs/guides/completion/prompt-design" target="_blank" rel="noreferrer noopener">OpenAI.com/prompt-design</a></li>



<li>ChatGPT helped to revise some sections of this article.</li>



<li>Images are generated with Midjourney, an AI that generates images from<a href="https://www.midjourney.com/app/"> text.</a></li>



<li><a href="https://www.relataly.com/category/use-case/sentiment-analysis-use-case/" target="_blank" rel="noreferrer noopener">Performing traditional sentiment analysis using Python</a></li>
</ul>



<div class="wp-block-query is-layout-flow wp-block-query-is-layout-flow"></div>



<p>Articles on the practical implementation of OpenAI GPT-3 models via the public API</p>



<ul class="has-contrast-color has-text-color wp-block-list">
<li><a href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/" target="_blank" rel="noreferrer noopener">Relataly.com &#8211; Using OpenAI GPT-3 with Python</a></li>



<li><a href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/" target="_blank" rel="noreferrer noopener">Relataly.com &#8211; Integrating Dall-E with GPT-3 for Prompt Generation using Python</a></li>
</ul>



<div class="wp-block-query is-layout-flow wp-block-query-is-layout-flow"></div>
<p>The post <a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/">9 Business Use Cases of OpenAI&#8217;s ChatGPT</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">12200</post-id>	</item>
		<item>
		<title>Create a Personalized Movie Recommendation Engine using Content-based Filtering in Python</title>
		<link>https://www.relataly.com/content-based-movie-recommender-using-python/4294/</link>
					<comments>https://www.relataly.com/content-based-movie-recommender-using-python/4294/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Mon, 25 Jul 2022 11:29:00 +0000</pubDate>
				<category><![CDATA[Content-based Filtering]]></category>
		<category><![CDATA[Correlation]]></category>
		<category><![CDATA[Cosine Similarity]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[nltk]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Recommender Systems]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Scikit-Learn]]></category>
		<category><![CDATA[Seaborn]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<category><![CDATA[Supervised Learning]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=4294</guid>

					<description><![CDATA[<p>Content-based recommender systems are a popular type of machine learning algorithm that recommends relevant articles based on what a user has previously consumed or liked. This approach aims to identify items with certain keywords, understand what the customer likes, and then identify other items that are similar to items the user has previously consumed or ... <a title="Create a Personalized Movie Recommendation Engine using Content-based Filtering in Python" class="read-more" href="https://www.relataly.com/content-based-movie-recommender-using-python/4294/" aria-label="Read more about Create a Personalized Movie Recommendation Engine using Content-based Filtering in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/content-based-movie-recommender-using-python/4294/">Create a Personalized Movie Recommendation Engine using Content-based Filtering in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Content-based recommender systems are a popular type of machine learning algorithm that recommends relevant articles based on what a user has previously consumed or liked. This approach aims to identify items with certain keywords, understand what the customer likes, and then identify other items that are similar to items the user has previously consumed or rated. The recommendations are based on the similarity of the items, represented by similarity scores in a vector matrix. The attributes used to describe an item are called &#8220;content.&#8221; For example, in the case of movie recommendations, content could be the genre, actors, director, year of release, etc. A well-designed content-based recommendation service will suggest movies of the same genre, actors, or keywords. This tutorial will implement a content-based recommendation service for movies using Python and Scikit-learn. </p>



<p>The rest of this tutorial proceeds as follows: After a brief introduction to content-based recommenders, we will work with a database that contains several thousands of <a href="https://www.imdb.com/" target="_blank" rel="noreferrer noopener">IMDB </a>movie titles and create a feature model that uses actors, release year, and a short description for each movie. In this tutorial, you will also learn how to deal with some challenges of building a content-based recommender. For example, we will look at how we can engineer features for content-based model words and reduce the dimensionality of our model. Finally, we use our model to generate some sample predictions.</p>



<p>Note: Another popular type of recommender system that I have covered in a previous article is <a href="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/" target="_blank" rel="noreferrer noopener">collaborative filtering</a>.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="508" height="508" data-attachment-id="12673" data-permalink="https://www.relataly.com/signpost-decisions-recommender-system-machine-learning-python-tutorial-midjourney-2-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/signpost-decisions-recommender-system-machine-learning-python-tutorial-midjourney-2-min.png" data-orig-size="508,508" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="signpost decisions recommender system machine learning python tutorial midjourney (2)-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/signpost-decisions-recommender-system-machine-learning-python-tutorial-midjourney-2-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/signpost-decisions-recommender-system-machine-learning-python-tutorial-midjourney-2-min.png" alt="Recommendation systems can ease decision-making. Image created with Midjourney." class="wp-image-12673" srcset="https://www.relataly.com/wp-content/uploads/2023/03/signpost-decisions-recommender-system-machine-learning-python-tutorial-midjourney-2-min.png 508w, https://www.relataly.com/wp-content/uploads/2023/03/signpost-decisions-recommender-system-machine-learning-python-tutorial-midjourney-2-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/signpost-decisions-recommender-system-machine-learning-python-tutorial-midjourney-2-min.png 140w" sizes="(max-width: 508px) 100vw, 508px" /><figcaption class="wp-element-caption">Recommendation systems can ease decision-making. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a>.</figcaption></figure>
</div>
</div>
</div>
</div>



<h2 class="wp-block-heading" id="h-what-is-content-based-filtering">What is Content-Based Filtering?</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The idea behind content-based recommenders is to generate recommendations based on user&#8217;s preferences and tastes. These preferences revolve around past user choices, for example, the number of times a user has watched a movie, purchased an item, or clicked on a link. </p>



<p>Content-based filtering uses domain-specific item features to measure the similarity between items. Given the user preferences, the algorithm will recommend items similar to what the user has consumed or liked before. For movie recommendations, this content can be the genre, actors, release year, director, film length, or keywords used to describe the movies. This approach works particularly well for domains with a lot of textual metadata, such as movies and videos, books, or products.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-kadence-image kb-image_efc597-b6 size-large"><img decoding="async" width="512" height="500" data-attachment-id="12668" data-permalink="https://www.relataly.com/polaroid-film-movie-recommender-machine-learning-python-tutorial-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/polaroid-film-movie-recommender-machine-learning-python-tutorial-min.png" data-orig-size="518,506" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="polaroid film movie recommender machine learning python tutorial-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/polaroid-film-movie-recommender-machine-learning-python-tutorial-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/polaroid-film-movie-recommender-machine-learning-python-tutorial-min-512x500.png" alt="" class="kb-img wp-image-12668" srcset="https://www.relataly.com/wp-content/uploads/2023/03/polaroid-film-movie-recommender-machine-learning-python-tutorial-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/polaroid-film-movie-recommender-machine-learning-python-tutorial-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/polaroid-film-movie-recommender-machine-learning-python-tutorial-min.png 518w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption>Content-based movie recommendations will suggest more of the same, for example, actors, genres, stories, and directors.<br></figcaption></figure>
</div>
</div>



<p></p>



<h3 class="wp-block-heading">Basic Steps to Building a Content-based Recommender System</h3>



<p>The approach to building a content-based recommender involves four essential steps:</p>



<ol class="wp-block-list">
<li>The first step is to create a so-called &#8216;bag of words&#8217; model from the input data, which is a list of words used to characterize the items. This step involves selecting useful content for describing and differentiating the items. The more precise the information, the better the recommendations will be. </li>



<li>The next step is to turn the bag (of words) into a feature vector. Different algorithms can be used for this step, for example, the Tfdif vectorizer or the count vectorizer. The result is a vector matrix with items as records and features as columns. This step often also includes applying techniques for dimensionality reduction. </li>



<li>The idea of content-based recommendations is based on measuring item similarity. Similarity scores are assigned through pairwise comparison. Here again, we can choose between different measures, e.g., the dot product or cosine similarity. </li>



<li>Once you have the similarity scores, you can return the most similar items by sorting the data by similarity scores. Given user preferences (single or multiple items a user consumed or liked), the algorithm will then recommend the most similar items. </li>
</ol>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="8937" data-permalink="https://www.relataly.com/content-based-movie-recommender-using-python/4294/image-11-5/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/07/image-11.png" data-orig-size="1911,1227" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-11" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/07/image-11.png" src="https://www.relataly.com/wp-content/uploads/2022/07/image-11-1024x657.png" alt="" class="wp-image-8937" width="1169" height="751" srcset="https://www.relataly.com/wp-content/uploads/2022/07/image-11.png 1024w, https://www.relataly.com/wp-content/uploads/2022/07/image-11.png 300w, https://www.relataly.com/wp-content/uploads/2022/07/image-11.png 768w, https://www.relataly.com/wp-content/uploads/2022/07/image-11.png 1536w, https://www.relataly.com/wp-content/uploads/2022/07/image-11.png 1911w" sizes="(max-width: 1169px) 100vw, 1169px" /><figcaption class="wp-element-caption">Approach to Building a Content-based Recommender System</figcaption></figure>



<h3 class="wp-block-heading">Similarity Scoring</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The quality of the content-based recommendations is significantly influenced by how well the algorithm succeeds in measuring the similarity of the items. There are different techniques to calculate similarity, including Cosine Similarity, Pearson Similarity, Dot Product, and Euclidian Distance. They have in common that they use numerical characteristics of the text to calculate the distance between text vectors in an n-dimensional vector space.</p>



<p>It is worth denoting that these techniques can only measure word-level similarity. This means the algorithms compare the word of the item for word without considering the semantic meaning of the sentences. In some instances, this can lead to errors. For example, how similar are <em>&#8220;now that they were sitting on a bank, he noticed she stole his heart, and he was in love&#8221;</em> and <em>&#8220;They are gangsters who love to steal from a large bank&#8221;</em>? By just looking at the words, one may appear similar because the words have a good overlap.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<p></p>



<h3 class="wp-block-heading">Pros and Cons of Content-based Filtering</h3>



<p>Like most machine learning algorithms, content-based recommenders have their strength and weaknesses.</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p><strong>Advantages</strong></p>



<ul class="wp-block-list">
<li>Content-based filtering is good at capturing a user&#8217;s specific interests and will recommend more of the same (for example, genre, actors, directors, etc.). It will also recommend niche items if they match the user preferences, even if these items draw little attention.</li>



<li>Another advantage is that the model can generate recommendations for a specific user without the knowledge of other users. This is particularly helpful if you want to generate predictions for many users.</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p><strong>Disadvantages</strong></p>



<ul class="wp-block-list">
<li>On the other hand, there are also a couple of downsides. The feature representation of the items has to be done manually to a certain extent, and the prediction quality strongly depends on whether items are described in detail. Therefore, content-based filtering requires a lot of expertise.</li>



<li>Since recommendations are based on the user&#8217;s previous interests. However, the recommendations are unlikely to go beyond that and expand to areas (e.g., genres) that are still unknown to the user.  Content-based models thus tend to develop some tunnel vision, so that the model recommends more and more of the same.</li>
</ul>
</div>
</div>



<div style="height:54px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading" id="h-implementing-a-content-based-movie-recommender-in-python">Implementing a Content-based Movie Recommender in Python</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>In the following, we will implement a content-based movie recommender using Python and Scikit-learn. We will carry out all steps necessary to create a content-based recommender. The data comes from an IMDB dataset containing more than 40k films between 1996 and 2018. Based on the data, we define the features we want to use for recommending the movies. These features include the genre, director, main actors, plot keywords, or other metadata associated with the movies. Then we preprocess the data to extract these features and create a feature matrix. The feature matrix becomes the foundation for a similarity matrix that measures the similarity between the items based on their feature vectors. Finally, we use the similarity matrix to generate recommendations for a given item. </p>



<p>By the end of this Python tutorial, you will have learned how to implement a content-based recommendation system for movies using Python and Scikit-learn. This knowledge can be applied to other types of recommendations, such as articles, products, or songs.</p>



<p>The code is available on the GitHub repository. </p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_c5cd86-dc"><a class="kb-button kt-button button kb-btn_a1ac8b-37 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/05%20Recommender%20Systems/032%20Movie%20Recommender%20using%20Content-based%20Filtering.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_f7ca5b-85 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" src="https://www.relataly.com/wp-content/uploads/2023/01/DALL·E-2023-01-12-19.26.12-A-plush-robot-watching-a-movie-on-tv-min.png" alt="This Robot doesn't know what to watch on tv. Let's build a recommender system for him! Image generated using DALL-E 2 by OpenAI." class="wp-image-11993"/><figcaption class="wp-element-caption">This Robot doesn&#8217;t know what to watch on tv. Let&#8217;s build a recommender system for him! Image generated using <a href="https://openai.com/dall-e-2/" target="_blank" rel="noreferrer noopener">DALL-E 2 by OpenAI</a>.</figcaption></figure>
</div>
</div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p>Before you start with the coding part, ensure you have set up your Python 3 environment and required packages. If you don&#8217;t have an environment, consider the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda Python environment</a>. Follow <a href="https://www.relataly.com/category/data-science/setup-anaconda-environment/" target="_blank" rel="noreferrer noopener">this tutorial</a> to set it up.</p>



<p>Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>



<li><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>
</ul>



<p>In addition, we will be using <a href="https://seaborn.pydata.org/" target="_blank" rel="noreferrer noopener">Seaborn </a>for visualization and the natural language processing library <a href="https://www.nltk.org/" target="_blank" rel="noreferrer noopener">nltk</a>. </p>



<p>You can install these packages by using one of the following commands: </p>



<ul class="wp-block-list">
<li><em>pip install &lt;package name&gt;</em></li>



<li><em>conda install &lt;package name&gt;</em>&nbsp;(if you are using the anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading" id="h-about-the-imdb-movies-dataset">About the IMDB Movies Dataset</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>We will train our movie recommender on a popular Movies Dataset (you can download it from <a href="https://grouplens.org/datasets/movielens/latest/" target="_blank" rel="noreferrer noopener">grouplens.org</a>). The MovieLens recommendation service collected the Dataset from 610 users between 1996 and 2018. Unpack the data into the working folder of your project.</p>



<p>The full Dataset contains metadata on over 45,000 movies and 26 million ratings from over 270,000 users. The Dataset contains the following files (Source of the data description: <a href="https://www.kaggle.com/rounakbanik/the-movies-dataset" target="_blank" rel="noreferrer noopener">Kaggle.com</a>):</p>



<ul class="wp-block-list">
<li><strong>movies_metadata.csv:</strong>&nbsp;The main Movies Metadata file contains information on 45,000 movies featured in the Full MovieLens Dataset. Features include posters, backdrops, budget, revenue, release dates, languages, production countries, and companies.
<ul class="wp-block-list">
<li></li>
</ul>
</li>



<li><strong>ratings_small.csv:</strong>&nbsp;The subset of 100,000 ratings from 700 users on 9,000 movies. Each line corresponds to a 5-star movie rating with half-star increments (0.5 &#8211; 5.0 stars).</li>



<li><strong>keywords.csv:</strong>&nbsp;Contains the movie plot keywords for our MovieLens movies. Available in the form of a stringified JSON Object.</li>



<li><strong>credits.csv:</strong>&nbsp;Consists of Cast and Crew Information for all our films. Available in the form of a stringified JSON Object.</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full is-resized"><img decoding="async" data-attachment-id="7128" data-permalink="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/mdb-movie-database/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png" data-orig-size="1024,537" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="recomender systems collaborative filtering imdb movies" data-image-description="&lt;p&gt;recomender systems collaborative filtering imdb movies&lt;/p&gt;
" data-image-caption="&lt;p&gt;recomender systems collaborative filtering imdb movies&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png" src="https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png" alt="MDB Movie Database Recommender Systems Collaborative Filtering " class="wp-image-7128" width="366" height="192" srcset="https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png 1024w, https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png 300w, https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png 768w" sizes="(max-width: 366px) 100vw, 366px" /><figcaption class="wp-element-caption">IMDB Movie Database </figcaption></figure>
</div>
</div>



<p>Several other files are included that we won&#8217;t use, incl. ratings_small, links_small, and links.</p>



<p>You can download it <a href="https://grouplens.org/datasets/movielens/latest/" target="_blank" rel="noreferrer noopener">here</a> or from <a href="https://www.kaggle.com/rounakbanik/the-movies-dataset" target="_blank" rel="noreferrer noopener">Kaggle</a>.</p>



<h3 class="wp-block-heading" id="h-step-1-load-the-data">Step #1: Load the Data</h3>



<p>Our goal is to create a content-based recommender system for movie recommendations. In this case, the content will be meta information on movies, such as genre, actors, the description.</p>



<p>We begin by making imports and loading the data from three files:</p>



<ul class="wp-block-list">
<li>movies_metadata.csv</li>



<li>credits.csv</li>



<li>keywords.csv</li>
</ul>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style('white', { 'axes.spines.right': False, 'axes.spines.top': False})
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.decomposition import TruncatedSVD
from nltk.corpus import stopwords

# the IMDB movies data is available on Kaggle.com
# https://www.kaggle.com/datasets/rounakbanik/the-movies-dataset

# in case you have placed the files outside of your working directory, you need to specify the path
path = 'data/movie_recommendations/' 

# load the movie metadata
df_meta=pd.read_csv(path + 'movies_metadata.csv', low_memory=False, encoding='UTF-8') 

# some records have invalid ids, which is why we remove them
df_meta = df_meta.drop([19730, 29503, 35587])

# convert the id to type int and set id as index
df_meta = df_meta.set_index(df_meta['id'].str.strip().replace(',','').astype(int))
pd.set_option('display.max_colwidth', 20)
df_meta.head(2)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">		adult	belongs_to_collection			budget		genres				homepage			id		imdb_id		original_language	original_title	overview			...	release_date	revenue		runtime	spoken_languages	status		tagline	title	video	vote_average	vote_count
id																					
862		False	{'id': 10194, 'n...				30000000	[{'id': 16, 'nam...	http://toystory....	862		tt0114709	en					Toy Story		Led by Woody, An...	...	1995-10-30		373554033.0	81.0	[{'iso_639_1': '...	Released	NaN	Toy Story	False	7.7	5415.0
8844	False	NaN								65000000	[{'id': 12, 'nam...	NaN					8844	tt0113497	en				Jumanji				When siblings Ju...	...	1995-12-15		262797249.0	104.0	[{'iso_639_1': '...	Released	Roll the dice an...	Jumanji	False	6.9	2413.0</pre></div>



<p>After we have loaded credits and keywords, we will combine the data into a single dataframe. Now we have various input fields available. However, we will only use keywords, cast, year of release, genres, and overview. If you like, you can enhance the data with additional inputs, for example, budget, running time, or film language. </p>



<p>Once we have gathered our data in a single dataframe, we print out the first rows to gain an overview of the data. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># load the movie credits
df_credits = pd.read_csv(path + 'credits.csv', encoding='UTF-8')
df_credits = df_credits.set_index('id')

# load the movie keywords
df_keywords=pd.read_csv(path + 'keywords.csv', low_memory=False, encoding='UTF-8') 
df_keywords = df_keywords.set_index('id')

# merge everything into a single dataframe 
df_k_c = df_keywords.merge(df_credits, left_index=True, right_on='id')
df = df_k_c.merge(df_meta[['release_date','genres','overview','title']], left_index=True, right_on='id')
df.head(3)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">		keywords			cast				crew				release_date	genres				overview			title
id							
862		[{'id': 931, 'na...	[{'cast_id': 14,...	[{'credit_id': '...	1995-10-30		[{'id': 16, 'nam...	Led by Woody, An...	Toy Story
8844	[{'id': 10090, '...	[{'cast_id': 1, ...	[{'credit_id': '...	1995-12-15		[{'id': 12, 'nam...	When siblings Ju...	Jumanji
15602	[{'id': 1495, 'n...	[{'cast_id': 2, ...	[{'credit_id': '...	1995-12-22		[{'id': 10749, '...	A family wedding...	Grumpier Old Men</pre></div>



<div style="height:15px" aria-hidden="true" class="wp-block-spacer"></div>



<p>We can see cast, crew, and genres have a dictionary-like structure. To create a cosine similarity matrix, we need to extract the keywords from these columns and gather them in a single column. This is what we will do in the next step. </p>



<h3 class="wp-block-heading" id="h-step-2-feature-engineering-and-data-cleaning">Step #2: Feature Engineering and Data Cleaning</h3>



<p>A problem with modeling text is that machine learning algorithms have difficulty processing text directly. An essential step in creating content-based recommenders is bringing the text into a machine-readable form. This is what we call feature engineering. </p>



<h4 class="wp-block-heading">2.1 Creating a Bag-of-Words Model</h4>



<p>We begin with feature engineering and creating the bag of words. As mentioned, a bag of words is a list of words relevant to describe items in a dataset, such as films, and differentiate them. Creating a bag of words removes stopwords but preserves multiplicity so that words can occur multiple times in the concatenated text. Later, each word can be used as a feature in calculating cosine similarities. </p>



<p>The input for a bag of words does not necessarily come from a single input column. We will use keywords, genres, cast, and overview and merge them into a new single column that we call tags. Make sure to capture the text field&#8217;s nature. We will keep names and surnames together and not split them, as we will do with the words from the overview column. The result of this process is our bag.</p>



<p>In addition, we add the movie title and a new index (id), which will later ease working with the similarity matrix. Finally, we print the first rows of our feature dataframe. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># create an empty DataFrame
df_movies = pd.DataFrame()

# extract the keywords
df_movies['keywords'] = df['keywords'].apply(lambda x: [i['name'] for i in eval(x)])
df_movies['keywords'] = df_movies['keywords'].apply(lambda x: ' '.join([i.replace(&quot; &quot;, &quot;&quot;) for i in x]))

# extract the overview
df_movies['overview'] = df['overview'].fillna('')

# extract the release year 
df_movies['release_date'] = pd.to_datetime(df['release_date'], errors='coerce').apply(lambda x: str(x).split('-')[0] if x != np.nan else np.nan)

# extract the actors
df_movies['cast'] = df['cast'].apply(lambda x: [i['name'] for i in eval(x)])
df_movies['cast'] = df_movies['cast'].apply(lambda x: ' '.join([i.replace(&quot; &quot;, &quot;&quot;) for i in x]))

# extract genres
df_movies['genres'] = df['genres'].apply(lambda x: [i['name'] for i in eval(x)])
df_movies['genres'] = df_movies['genres'].apply(lambda x: ' '.join([i.replace(&quot; &quot;, &quot;&quot;) for i in x]))

# add the title
df_movies['title'] = df['title']

# merge fields into a tag field
df_movies['tags'] = df_movies['keywords'] + df_movies['cast']+' '+df_movies['genres']+' '+df_movies['release_date']

# drop records with empty tags and dublicates
df_movies.drop(df_movies[df_movies['tags']==''].index, inplace=True)
df_movies.drop_duplicates(inplace=True)

# add a fresh index to the dataframe, which we will later use when refering to items in a vector matrix
df_movies['new_id'] = range(0, len(df_movies))

# Reduce the data to relevant columns
df_movies = df_movies[['new_id', 'title', 'tags']]

# display the data
pd.set_option('display.max_colwidth', 500)
pd.set_option('display.expand_frame_repr', False)
print(df_movies.shape)
df_movies.head(5)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">		new_id	title							tags
id			
862		0		Toy Story						jealousy toy boy friendship friends rivalry boynextdoor newtoy toycomestolifeTomHanks TimAllen DonRickles JimVarney WallaceShawn JohnRatzenberger AnniePotts JohnMorris ErikvonDetten LaurieMetcalf R.LeeErmey SarahFreeman PennJillette Animation Comedy Family 1995
8844	1		Jumanji							boardgame disappearance basedonchildren'sbook newhome recluse giantinsectRobinWilliams JonathanHyde KirstenDunst BradleyPierce BonnieHunt BebeNeuwirth DavidAlanGrier PatriciaClarkson AdamHann-Byrd LauraBellBundy JamesHandy GillianBarber BrandonObray CyrusThiedeke GaryJosephThorup LeonardZola LloydBerry MalcolmStewart AnnabelKershaw DarrylHenriques RobynDriscoll PeterBryant SarahGilson FloricaVlad JuneLion BrendaLockmuller Adventure Fantasy Family 1995
15602	2		Grumpier Old Men				fishing bestfriend duringcreditsstinger oldmenWalterMatthau JackLemmon Ann-Margret SophiaLoren DarylHannah BurgessMeredith KevinPollak Romance Comedy 1995
31357	3		Waiting to Exhale				basedonnovel interracialrelationship singlemother divorce chickflickWhitneyHouston AngelaBassett LorettaDevine LelaRochon GregoryHines DennisHaysbert MichaelBeach MykeltiWilliamson LamontJohnson WesleySnipes Comedy Drama Romance 1995
11862	4		Father of the Bride Part II		baby midlifecrisis confidence aging daughter motherdaughterrelationship pregnancy contraception gynecologistSteveMartin DianeKeaton MartinShort KimberlyWilliams-Paisley GeorgeNewbern KieranCulkin BDWong PeterMichaelGoetz KateMcGregor-Stewart JaneAdams EugeneLevy LoriAlan Comedy 1995</pre></div>



<h4 class="wp-block-heading" id="h-2-2-visualizing-text-length">2.2 Visualizing Text Length</h4>



<p>We can use a bar chart to illustrate each movie&#8217;s word bag length. This gives us an idea of how detailed the movie descriptions are. Items with short descriptions have, in principle, a lower probability of being recommended later. Recommenders produce better results if the length of the descriptions is somewhat balanced.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># add the tag length to the movies df
df_movies['tag_len'] = df_movies['tags'].apply(lambda x: len(x))

# illustrate the tag text length
sns.displot(data=df_movies.dropna(), bins=list(range(0, 2000, 25)), height=5, x='tag_len', aspect=3, kde=True)
plt.title('Distribution of tag text length')
plt.xlim([0, 2500])</pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="346" data-attachment-id="8866" data-permalink="https://www.relataly.com/content-based-movie-recommender-using-python/4294/tags-text-length-visualization-python-content-based-recommender-system-2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/07/tags-text-length-visualization-python-content-based-recommender-system-2.png" data-orig-size="1083,366" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="tags-text-length-visualization-python-content-based-recommender-system-2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/07/tags-text-length-visualization-python-content-based-recommender-system-2.png" src="https://www.relataly.com/wp-content/uploads/2022/07/tags-text-length-visualization-python-content-based-recommender-system-2-1024x346.png" alt="content-based recommender system - illustration of the distribution of word length in our bag-of-word model" class="wp-image-8866" srcset="https://www.relataly.com/wp-content/uploads/2022/07/tags-text-length-visualization-python-content-based-recommender-system-2.png 1024w, https://www.relataly.com/wp-content/uploads/2022/07/tags-text-length-visualization-python-content-based-recommender-system-2.png 300w, https://www.relataly.com/wp-content/uploads/2022/07/tags-text-length-visualization-python-content-based-recommender-system-2.png 768w, https://www.relataly.com/wp-content/uploads/2022/07/tags-text-length-visualization-python-content-based-recommender-system-2.png 1083w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h3 class="wp-block-heading" id="h-step-3-vectorization-using-tfidfvectorizer">Step #3: Vectorization using TfidfVectorizer</h3>



<p>The next step is to create a vector matrix from the Bag of Words model. Each column from the matrix represents a word feature. This step is the basis for determining the similarity of the movies afterward. Before the vectorization, we will remove stop words from the text (e.g., and, it, that, or, why, where, etc.). In addition, I limited the number of features in the matrix to 5000 to reduce training time.</p>



<p>A simple vectorization approach is to determine the word frequency for each movie using a count vectorizer. However, a frequently mentioned disadvantage of this approach is that it does not consider how often a word occurs. For example, some words may appear in almost all items. On the other hand, some words may be prevalent in a few items but are rare in general.  So we can argue that observing rare words in an item is more informative than observing common words. Instead of a count vectorizer, we will use a more practical approach called TfidfVectorizer from the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" target="_blank" rel="noreferrer noopener">scikit-learn package</a>. </p>



<p>Tfidf stands for term frequency-inverse document frequency. Compared to a count vectorizer, the tf-idf vectorizer considers the overall word frequencies and weights the general importance of the words when spanning the vectors. This way, tf-idf can determine which words are more important than others, reducing the model&#8217;s complexity and improving performance. This <a href="https://medium.com/@cmukesh8688/tf-idf-vectorizer-scikit-learn-dbc0244a911a" target="_blank" rel="noreferrer noopener">medium article</a> explains the math behind tf-idf vectorization in more detail.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># set a custom stop list from nltk
stop = list(stopwords.words('english'))

# create the tfid vectorizer, alternatively you can also use countVectorizer
tfidf =  TfidfVectorizer(max_features=5000, analyzer = 'word', stop_words=set(stop))
vectorized_data = tfidf.fit_transform(df_movies['tags'])
count_matrix = pd.DataFrame(vectorized_data.toarray(), index=df_movies['tags'].index.tolist())
print(count_matrix)

</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">			0     1     2     3     4     5     6     7     8     9     ...  4990  4991  4992  4993  4994  4995  4996  4997  4998  4999
862      	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
8844     	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
15602    	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
31357    	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
11862    	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
...      	...   ...   ...   ...   ...   ...   ...   ...   ...   ...  ...   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...
439050   	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
111109   	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
67758    	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
227506   	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
461257   	0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  ...   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0

[45432 rows x 5000 columns]</pre></div>



<p>The vectorization process results in a feature matrix in which each feature is a word from the text bag of words. </p>



<p>We can display features with the get_feature_names_out function from the tfidf vectorizer.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># print feature names
print(tfidf.get_feature_names_out()[940:990])</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">['climbing' 'clinteastwood' 'clinthoward' 'clive' 'cliveowen'
 'cliverevill' 'cliverussell' 'clone' 'clorisleachman' 'cloviscornillac'
 'clown' 'clugulager' 'clydekusatsu' 'co' 'coach' 'cobb' 'cocaine' 'code'
 'coffin' 'cohen' 'coldwar' 'cole' 'colehauser' 'coleman' 'colinfarrell'
 'colinfirth' 'colinhanks' 'colinkenny' 'colinsalmon' 'colleencamp'
 'college' 'colmfeore' 'colmmeaney' 'coma' 'combat' 'comedian' 'comedy'
 'comicbook' 'comingofage' 'comingout' 'common' 'communism' 'communist'
 'company' 'competition' 'composer' 'computer' 'con' 'concentrationcamp'
 'concert']</pre></div>



<p>As you can see, features are specific words,</p>



<h3 class="wp-block-heading" id="h-step-4-dimensionality-reduction-and-calculate-consine-similarities">Step #4 Dimensionality Reduction and Calculate Consine Similarities</h3>



<p>In the previous section, we created a vector matrix that contains movies and features. This matrix is the foundation for calculating similarity scores for all movies. Before we assign feature scores, we will apply dimensionality reduction.</p>



<h4 class="wp-block-heading">4.1 Dimensionality Reduction using SVD</h4>



<p>The matrix spans a high-dimensional vector space with more than 5000 feature columns. Do we need all of these features? The answer is most likely not. There are likely a lot of words in the matrix that only occur once or twice. On the other hand, words may occur in almost all movies. How can we deal with this issue?</p>



<p>The reason for this is that we have a very dimensional vector space. By reducing this space to fewer, more essential features, we can save some time training our recommender model. We will use TruncatedSVD from the scikit-learn package, a popular algorithm for dimensionality reduction. The algorithm smoothens the matrix and approximates it to a lower dimensional space, thereby reducing noise and model complexity.</p>



<p>This way, we will reduce the vector space from 5000 to 3000 features. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># reduce dimensionality for improved performance
svd = TruncatedSVD(n_components=3000)
reduced_data = svd.fit_transform(count_matrix)</pre></div>



<h4 class="wp-block-heading">4.2 Calculate Text Similarity Scores for all Movies</h4>



<p>Now that we have reduced the complexity of our vector matrix, we can calculate the similarity scores for all movies. In this process, we assign a similarity score to all item pairs that measure content closeness according to the position of the items in the vector space. </p>



<p>We use the cosine function to calculate the similarity value of the movies. The cosine similarity is a mathematical calculation to determine the mathematical similarity of two vectors. In our case, the vectors are the movie descriptions. The cosine similarity function uses these feature vectors to compare each movie to every other and assigns them a similarity value. </p>



<ul class="wp-block-list">
<li>A similarity value of -1 means that two feature vectors are correlated, and the movies are entirely different. </li>



<li>A value of 1 means that the two movies are identical. </li>



<li>A value of 0 is between and means f an average match of the feature vectors.</li>
</ul>



<p>The cosine similarity function will calculate pairwise similarities for all movies in our vector matrix. We can determine the number of pairwise comparisons with the formula k²/2, whereby k is the number of items in the vector matrix. In our case, we have a k of 45000 movies. This means the cosine similarity function must calculate about 1 billion similarity scores. So don&#8217;t worry if the process takes some time to complete. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># compute the cosine similarity matrix
similarity = cosine_similarity(reduced_data)
similarity</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">array([[ 1.00000000e+00,  9.75542082e-02,  6.00755620e-02, ...,
        -3.03965235e-04,  0.00000000e+00,  5.81243547e-05],
       [ 9.75542082e-02,  1.00000000e+00,  5.92929339e-02, ...,
        -2.97565163e-03,  0.00000000e+00,  4.57945869e-05],
       [ 6.00755620e-02,  5.92929339e-02,  1.00000000e+00, ...,
         9.40459504e-03,  0.00000000e+00, -2.22415551e-04],
       ...,
       [-3.03965235e-04, -2.97565163e-03,  9.40459504e-03, ...,
         1.00000000e+00,  0.00000000e+00, -2.60823346e-04],
       [ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       [ 5.81243547e-05,  4.57945869e-05, -2.22415551e-04, ...,
        -2.60823346e-04,  0.00000000e+00,  1.00000000e+00]])</pre></div>



<div style="height:38px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-step-5-generate-content-based-movie-recommendations">Step #5: Generate Content-based Movie Recommendations </h3>



<p>Once you have created the similarity matrix, it&#8217;s time to generate some recommendations. We begin by generating recommendations based on a single movie. In the cosine similarity matrix, the most similar movies have the highest similarity scores. Once we have the film with the highest scores, we can visualize the results in a bar chart that shows the cosine similarity scores. </p>



<p>The example below displays the results of the movie &#8220;The Matrix.&#8221; Oh, how I love this movie 🙂</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># create a function that takes in movie title as input and returns a list of the most similar movies
def get_recommendations(title, n, cosine_sim=similarity):
    
    # get the index of the movie that matches the title
    movie_index = df_movies[df_movies.title==title].new_id.values[0]
    print(movie_index, title)
    
    # get the pairwsie similarity scores of all movies with that movie and sort the movies based on the similarity scores
    sim_scores_all = sorted(list(enumerate(cosine_sim[movie_index])), key=lambda x: x[1], reverse=True)
    
    # checks if recommendations are limited
    if n &gt; 0:
        sim_scores_all = sim_scores_all[1:n+1]
        
    # get the movie indices of the top similar movies
    movie_indices = [i[0] for i in sim_scores_all]
    scores = [i[1] for i in sim_scores_all]
    
    # return the top n most similar movies from the movies df
    top_titles_df = pd.DataFrame(df_movies.iloc[movie_indices]['title'])
    top_titles_df['sim_scores'] = scores
    top_titles_df['ranking'] = range(1, len(top_titles_df) + 1)
    
    return top_titles_df, sim_scores_all

# generate a list of recommendations for a specific movie title
movie_name = 'The Matrix'
number_of_recommendations = 15
top_titles_df, _ = get_recommendations(movie_name, number_of_recommendations)
 
# visualize the results
def show_results(movie_name, top_titles_df):
    fix, ax = plt.subplots(figsize=(11, 5))
    sns.barplot(data=top_titles_df, y='title', x= 'sim_scores', color='blue')
    plt.xlim((0,1))
    plt.title(f'Top 15 recommendations for {movie_name}')
    pct_values = ['{:.2}'.format(elm) for elm in list(top_titles_df['sim_scores'])]
    ax.bar_label(container=ax.containers[0], labels=pct_values, size=12)

show_results(movie_name, top_titles_df)</pre></div>



<p>Example for the movies &#8220;Spectre&#8221; and &#8220;The Lion King&#8221;</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-image size-full"><img decoding="async" width="830" height="329" data-attachment-id="9748" data-permalink="https://www.relataly.com/content-based-movie-recommender-using-python/4294/image-2-13/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/10/image-2.png" data-orig-size="830,329" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/10/image-2.png" src="https://www.relataly.com/wp-content/uploads/2022/10/image-2.png" alt="" class="wp-image-9748" srcset="https://www.relataly.com/wp-content/uploads/2022/10/image-2.png 830w, https://www.relataly.com/wp-content/uploads/2022/10/image-2.png 300w, https://www.relataly.com/wp-content/uploads/2022/10/image-2.png 768w" sizes="(max-width: 830px) 100vw, 830px" /></figure>
</div>
</div>



<h3 class="wp-block-heading">Step #6: Generate Content-based Movie Recommendations</h3>



<p>But what if you want to generate recommendations for specific users that have seen several movies? For this, we can aggregate the similarity scores for all films the user has seen. This way, we create a new dataframe that sums up similarity scores. To return the top-recommended movies, we can sort this dataframe by similarity scores and replace the top elements. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># list of movies a user has seen
movie_list = ['The Lion King', 'Seven', 'RoboCop 3', 'Blade Runner', 'Quantum of Solace', 'Casino Royale', 'Skyfall']

# create a copy of the movie dataframe and add a column in which we aggregated the scores
user_scores = pd.DataFrame(df_movies['title'])
user_scores['sim_scores'] = 0.0

# top number of scores to be considered for each movie
number_of_recommendations = 10000
for movie_name in movie_list:
    top_titles_df, _ = get_recommendations(movie_name, number_of_recommendations)
    # aggregate the scores
    user_scores = pd.concat([user_scores, top_titles_df[['title', 'sim_scores']]]).groupby(['title'], as_index=False).sum({'sim_scores'})
# sort and print the aggregated scores
user_scores.sort_values(by='sim_scores', ascending=False)[1:20]</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="8888" data-permalink="https://www.relataly.com/content-based-movie-recommender-using-python/4294/image-8-12/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/07/image-8.png" data-orig-size="1375,583" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-8" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/07/image-8.png" src="https://www.relataly.com/wp-content/uploads/2022/07/image-8-1024x434.png" alt="Content-based movie recommdations for a user that has previously watched The Lion King, Seven, RoboCop 3, Blade Runner, Quantum of Solace, Casino Royale, Skyfall" class="wp-image-8888" width="805" height="341" srcset="https://www.relataly.com/wp-content/uploads/2022/07/image-8.png 1024w, https://www.relataly.com/wp-content/uploads/2022/07/image-8.png 300w, https://www.relataly.com/wp-content/uploads/2022/07/image-8.png 768w, https://www.relataly.com/wp-content/uploads/2022/07/image-8.png 1375w" sizes="(max-width: 805px) 100vw, 805px" /></figure>



<div style="height:65px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>In this tutorial, you have learned to implement a simple content-based recommender system for movie recommendations in Python.  We have used several movie-specific details to calculate a similarity matrix for all movies in our dataset. Finally, we have used this model to generate recommendations for two cases:</p>



<ul class="wp-block-list">
<li>Films that are similar to a specific movie</li>



<li>Films that are recommended based on the watchlist of a particular user.</li>
</ul>



<p>A downside of content-based recommenders is that you cannot test their performance unless you know how users perceived the recommendations. This is because content-based recommenders can only determine which items in a dataset are similar. To understand how well the suggestions work, you must include additional data about actual user preferences. </p>



<p>More advanced recommenders will combine content-based recommendations with user-item interactions (<a href="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/" target="_blank" rel="noreferrer noopener">e.g., collaborative filtering</a>). Such models are called hybrid recommenders, but this is something for another article.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="472" data-attachment-id="12683" data-permalink="https://www.relataly.com/dog-with-popcorn-machine-learning-movie-recommender-python-tutorial-relataly-midjourney-ai-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/dog-with-popcorn-machine-learning-movie-recommender-python-tutorial-relataly-midjourney-ai-min.png" data-orig-size="532,490" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="dog with popcorn machine learning movie recommender python tutorial relataly midjourney ai-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/dog-with-popcorn-machine-learning-movie-recommender-python-tutorial-relataly-midjourney-ai-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/dog-with-popcorn-machine-learning-movie-recommender-python-tutorial-relataly-midjourney-ai-min-512x472.png" alt="" class="wp-image-12683" srcset="https://www.relataly.com/wp-content/uploads/2023/03/dog-with-popcorn-machine-learning-movie-recommender-python-tutorial-relataly-midjourney-ai-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/dog-with-popcorn-machine-learning-movie-recommender-python-tutorial-relataly-midjourney-ai-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/dog-with-popcorn-machine-learning-movie-recommender-python-tutorial-relataly-midjourney-ai-min.png 532w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div>
</div>



<p></p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<p>Below are some resources for further reading on recommender systems and content-based models.</p>



<p><strong>Books</strong></p>



<ol class="wp-block-list"><li><a href="https://amzn.to/3T3Sl2V" target="_blank" rel="noreferrer noopener">Charu C. Aggarwal (2016) Recommender Systems: The Textbook</a></li><li><a href="https://amzn.to/3D0P8eX" target="_blank" rel="noreferrer noopener">Kin Falk (2019) Practical Recommender Systems</a></li><li><a href="https://amzn.to/3MAy8j5" target="_blank" rel="noreferrer noopener">Andriy Burkov (2020) Machine Learning Engineering</a></li><li><a href="https://amzn.to/3D0gB0e" target="_blank" rel="noreferrer noopener">Oliver Theobald (2020) Machine Learning For Absolute Beginners: A Plain English Introduction</a></li><li><a href="https://amzn.to/3S9Nfkl" target="_blank" rel="noreferrer noopener">Aurélien Géron (2019) Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems </a></li><li><a href="https://amzn.to/3EKidwE" target="_blank" rel="noreferrer noopener">David Forsyth (2019) Applied Machine Learning Springer</a></li></ol>



<p class="has-contrast-2-color has-base-3-background-color has-text-color has-background"><em>The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.</em></p>



<p><strong>Articles</strong></p>



<ol class="wp-block-list"><li><a href="https://surprise.readthedocs.io/en/stable/getting_started.html" target="_blank" rel="noreferrer noopener">Getting started with Suprise</a></li><li><a href="https://onespire.hu/sap-news-en/history-of-recommender-systems/" target="_blank" rel="noreferrer noopener">About the history of Recommender Systems</a></li><li><a href="https://www.freecodecamp.org/news/singular-value-decomposition-vs-matrix-factorization-in-recommender-systems-b1e99bc73599/" target="_blank" rel="noreferrer noopener"></a><a href="https://www.freecodecamp.org/news/singular-value-decomposition-vs-matrix-factorization-in-recommender-systems-b1e99bc73599/" target="_blank" rel="noreferrer noopener">Singular value decomposition vs. matrix factorization</a></li><li><a href="https://proceedings.neurips.cc/paper/2007/file/d7322ed717dedf1eb4e6e52a37ea7bcd-Paper.pdf" target="_blank" rel="noreferrer noopener">Probabilistic Matrix Factorization</a></li></ol>
<p>The post <a href="https://www.relataly.com/content-based-movie-recommender-using-python/4294/">Create a Personalized Movie Recommendation Engine using Content-based Filtering in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/content-based-movie-recommender-using-python/4294/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4294</post-id>	</item>
		<item>
		<title>Build a High-Performing Movie Recommender System using Collaborative Filtering in Python</title>
		<link>https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/</link>
					<comments>https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Mon, 31 May 2021 10:29:35 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Collaborative Filtering]]></category>
		<category><![CDATA[Recommender Systems]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Surprise Lib]]></category>
		<category><![CDATA[Use Cases]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[Collaborative Filtering Recommender System]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<category><![CDATA[SVD]]></category>
		<category><![CDATA[Unsupervised Learning]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=4376</guid>

					<description><![CDATA[<p>The digital age presents us with an unmanageable number of decisions and even more options. Which series to watch today? What song to listen to next? Nowadays, the internet and its vast content offer too many choices. But there is hope &#8211; recommender systems are here to solve this problem and support our decision-making. They ... <a title="Build a High-Performing Movie Recommender System using Collaborative Filtering in Python" class="read-more" href="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/" aria-label="Read more about Build a High-Performing Movie Recommender System using Collaborative Filtering in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/">Build a High-Performing Movie Recommender System using Collaborative Filtering in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The digital age presents us with an unmanageable number of decisions and even more options. Which series to watch today? What song to listen to next? Nowadays, the internet and its vast content offer too many choices. But there is hope &#8211; recommender systems are here to solve this problem and support our decision-making. They rank among the fascinating use cases for machine learning and intelligently filter information to present us with a smaller set of options that most likely fit our tastes and needs. This tutorial will explore recommender systems and implement a movie recommender in Python that uses &#8220;Collaborative Filtering.&#8221;</p>



<p>This article is structured as follows: We begin by briefly going through the basics of different types of recommender systems. Then we will look at the most common recommender algorithms and go into more detail on Collaborative Filtering. Once equipped with this conceptual understanding, we will develop our recommender system using the popular 100k Movies Dataset. We will train and test a recommender model to predict movie ratings. The library used is the Scikit-Surprise Python library. The recommendation approach combines Collaborative Filtering and Singular Value Decomposition (SVD).</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>
</div>
</div>



<h2 class="wp-block-heading" id="h-an-overview-of-recommender-techniques">An Overview of Recommender Techniques</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The first attempts with recommendation systems reach back to the 1970s. The approach was relatively simple and categorized users into groups to suggest the same content to all users in the same group. However, it was a breakthrough because, for the first time, a program could make personalized recommendations. As the importance of recommendation engines increased, so did the interest in improving their predictions.</p>



<p>With the rise of the internet and the rapidly growing amount of data available on the web, filtering relevant content has become increasingly important. Large tech companies such as Netflix (TV shows and movies), Amazon (products), or Facebook (user content and profiles) understood early on that they could use recommendation systems to personalize the selection of user content shown to their customers. They all face the same challenge of having massive content and only limited space to display it to their users. Therefore, it has become crucial for them to select and display only the content that matches the individual interests of their users.</p>



<p>Internet companies are predestined for using recommender systems, as they have massive amounts of user data available. The user data is the foundation for generating personalized recommendations on a large scale by analyzing behavior patterns among larger groups of users to tailor suggestions to the taste of individuals.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"><div class="wp-block-image">
<figure class="alignright size-full"><img decoding="async" width="512" height="512" data-attachment-id="11938" data-permalink="https://www.relataly.com/reinforcement-learning-agents-learn-from-their-activities-if-our-reward-function-tells-them-how-they-perform/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/Reinforcement-Learning-Agents-learn-from-their-activities-if-our-reward-function-tells-them-how-they-perform.png" data-orig-size="512,512" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Reinforcement Learning &amp;#8211; Agents learn from their activities if our reward function tells them how they perform" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/Reinforcement-Learning-Agents-learn-from-their-activities-if-our-reward-function-tells-them-how-they-perform.png" src="https://www.relataly.com/wp-content/uploads/2023/01/Reinforcement-Learning-Agents-learn-from-their-activities-if-our-reward-function-tells-them-how-they-perform.png" alt="" class="wp-image-11938" srcset="https://www.relataly.com/wp-content/uploads/2023/01/Reinforcement-Learning-Agents-learn-from-their-activities-if-our-reward-function-tells-them-how-they-perform.png 512w, https://www.relataly.com/wp-content/uploads/2023/01/Reinforcement-Learning-Agents-learn-from-their-activities-if-our-reward-function-tells-them-how-they-perform.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/Reinforcement-Learning-Agents-learn-from-their-activities-if-our-reward-function-tells-them-how-they-perform.png 140w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">The more choices we have, the more difficult it gets to decide </figcaption></figure>
</div></div>
</div>



<p></p>



<h3 class="wp-block-heading" id="h-three-common-approaches-to-recommender-systems">Three Common Approaches to Recommender Systems</h3>



<p>Nowadays, many different approaches can generate recommendations. However, most recommender systems use one of the following three techniques:</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="4348" data-permalink="https://www.relataly.com/content-based-movie-recommender-using-python/4294/image-29-6/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-29.png" data-orig-size="1834,751" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-29" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-29.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-29-1024x419.png" alt="machine learning for recommender systems -  comparison of three different techniques used to build recommender systems - content based filtering, collaborative filtering, hybrid approach" class="wp-image-4348" width="1056" height="430" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-29.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/image-29.png 768w" sizes="(max-width: 1056px) 100vw, 1056px" /><figcaption class="wp-element-caption">Popular techniques used to build recommender systems</figcaption></figure>



<h4 class="wp-block-heading" id="h-content-based-filtering">Content-based Filtering&nbsp;</h4>



<p id="h-content-based-filtering-is-a-technique-that-recommends-similar-items-based-on-item-content-naturally-this-approach-is-based-on-metadata-to-find-out-which-items-are-similar-for-example-in-the-case-of-movie-recommendations-the-algorithm-would-look-at-the-genre-cast-or-director-of-a-movie-models-may-also-consider-metadata-on-users-such-as-age-gender-and-so-on-to-suggest-similar-content-to-similar-users-the-similarity-can-be-calculated-using-different-methods-for-example-cosine-similarity-or-minkowski-distance">Content-based filtering&nbsp;is a technique that recommends similar items based on item content. Naturally, this approach is based on metadata to determine which items are similar. For example, in the case of movie recommendations, the algorithm would look at the genre, cast, or director of a movie. Models may also consider metadata on users, such as age, gender, etc., to suggest similar content to similar users. There are different methods to calculate the similarity, for example, Cosine Similarity or Minkowski Distance.</p>



<p>A significant challenge in content-based Filtering is the transferability of user preference insights from one item type to another. Often, content-based recommenders struggle to transfer user actions on one item (e.g., book) to other content types (e.g., clothing). In addition, content-based systems tend to develop tunnel vision, leading the engine to recommend more and more of the same.</p>



<p>A separate article covers content-based filtering in more detail and shows <a href="https://www.relataly.com/content-based-movie-recommender-using-python/4294/" target="_blank" rel="noreferrer noopener">how to implement this approach for movie recommendations. </a></p>



<h4 class="wp-block-heading" id="h-collaborative-filtering">Collaborative Filtering</h4>



<p>Collaborative Filtering&nbsp;is a well-established approach used to build recommendation systems. The recommendations generated through Collaborative Filtering are based on past interactions between a user and a set of items (movies, products, etc.) that are matched against past item-user interactions within a larger group of people. The main idea is to use the interactions between a group of users and a group of items to guess how users rate items they have not yet rated before.</p>



<p>A challenge of collaborative filters is known as the cold start problem, which refers to the entry of new users into the system without any ratings. As a result, the engine does not know its interests and cannot make meaningful recommendations. The same applies to new items entering the system (e.g., products) that have not yet received any ratings. As a result, recommendations can become self-reinforcing. Popular content that many users have rated is recommended to almost all other users, making this content even more popular. On the other hand, the engine hardly suggests content with few or no ratings, so no one will rate this content.</p>



<h4 class="wp-block-heading" id="h-hybrid-approach">Hybrid Approach</h4>



<p>Combining the previous two techniques in a hybrid approach is also possible. We can implement hybrid approaches by generating content-based and collaborative-based predictions separately and then combining them. The result is a model that considers the interactions between users and items and context information. Hybrid recommender systems often achieve better results than recommendation approaches that use a single of the underlying techniques.</p>



<p>Netflix is known to use a hybrid recommendation system. Its engine recommends content to its users based on similar users&#8217; viewing and search habits (Collaborative Filtering). At the same time, it also recommends series and movies whose characteristics match the content users rated highly (content-based Filtering).</p>



<h3 class="wp-block-heading" id="h-how-model-based-collaborative-filtering-works">How Model-based Collaborative Filtering Works</h3>



<p>We can further differentiate between memory-based and model-based Collaborative Filtering. This tutorial focuses on model-based Collaborative Filtering, which is more commonly used. </p>



<h3 class="wp-block-heading" id="h-behavioral-patterns-dependencies-among-users-and-items">Behavioral Patterns: Dependencies among Users and Items</h3>



<p></p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p>Collaborative filtering searches for behavioral patterns in interactions between a group of users and a group of items to infer the interests of individuals. The input data for collaborative Filtering is typically in the form of a user/item matrix filled with ratings (as shown below).</p>



<p>Patterns can exist in the user/item matrix in dependencies between users and items. Some dependencies are easy to grasp. Similar dependencies exist between items in that some movies receive high ratings from the same users. For example, assume two users, Ron and Joe, have rated movies. Ron enjoyed Batman, Indiana Jones, Star Wars, and Godzilla. Joe enjoyed the same movies as Ron, except Godzilla, which he has not yet rated. Based on the similarity between Joe and Ron, we assume that Joe would also enjoy Godzilla. </p>



<p>Things get more complex as latent dependencies are present in the data. Imagine Bob gave a three-star rating to five different movies. Another user, Jenny, rated the same movies as Bob but always gave four stars, which is an example of latent dependency. There is some form of dependence between the two users, and although it is not as significant as in the first example, considering latent dependencies will improve predictions.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="4441" data-permalink="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/image-3-14/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/06/image-3.png" data-orig-size="402,303" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-3" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/06/image-3.png" src="https://www.relataly.com/wp-content/uploads/2021/06/image-3.png" alt="Dependencies among users and items for movie recommendations" class="wp-image-4441" width="327" height="247" srcset="https://www.relataly.com/wp-content/uploads/2021/06/image-3.png 402w, https://www.relataly.com/wp-content/uploads/2021/06/image-3.png 300w" sizes="(max-width: 327px) 100vw, 327px" /><figcaption class="wp-element-caption">user/movies matrix</figcaption></figure>
</div>
</div>



<p></p>



<h3 class="wp-block-heading" id="h-machine-learning-and-dimensionality-reduction">Machine Learning and Dimensionality Reduction</h3>



<p>Model-based collaborative filtering techniques estimate the parameters of statistical models to predict how individual users would rate an unrated item. A widely used approach formulates this problem as a classification task that considers items over users as features and ratings as prediction labels (as shown in the matrix). We can use various algorithms to solve such an optimization problem, including gradient-based techniques or alternating least squares.</p>



<p>However, user/item matrices can become very large, making searching for patterns computationally expensive. Also, users will typically rate only a tiny fraction of the items in the matrix, so algorithms must deal with an abundant number of missing values (sparse matrix). Therefore, combining machine learning or deep learning with techniques for dimensionality reduction has become state-of-the-art.</p>



<p>One of the most widely used techniques for dimensionality reduction is matrix factorization. This approach compresses the initial sparse user/item matrix and presents it as separate matrices that present items and users as unknown feature vectors (as shown below). Such a matrix is densely populated and thus easier to handle, but it also enables the model to uncover latent dependencies among items and users, which increases model accuracy. </p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="276" data-attachment-id="4462" data-permalink="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/image-7-14/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/06/image-7.png" data-orig-size="1299,350" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-7" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/06/image-7.png" src="https://www.relataly.com/wp-content/uploads/2021/06/image-7-1024x276.png" alt="Matrix Factorization applied to the sparse Items / User Matrix" class="wp-image-4462" srcset="https://www.relataly.com/wp-content/uploads/2021/06/image-7.png 1024w, https://www.relataly.com/wp-content/uploads/2021/06/image-7.png 300w, https://www.relataly.com/wp-content/uploads/2021/06/image-7.png 768w, https://www.relataly.com/wp-content/uploads/2021/06/image-7.png 1299w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Matrix Factorization is applied to the sparse Items / User Matrix.</figcaption></figure>



<h3 class="wp-block-heading" id="h-python-libraries-for-collaborative-filtering">Python Libraries for Collaborative Filtering</h3>



<p>So far, only a few Python libraries support model-based collaborative Filtering out of the box. The most well-known libraries for recommender systems are probably <a href="https://github.com/NicolasHug/Surprise" target="_blank" rel="noreferrer noopener">Scikit-Suprise</a> and <a href="https://www.fast.ai/" target="_blank" rel="noreferrer noopener">Fast.ai for Pytorch</a>. </p>



<p>Below you find an overview of the different algorithms that these libraries support. </p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="4303" data-permalink="https://www.relataly.com/content-based-movie-recommender-using-python/4294/image-18-8/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-18.png" data-orig-size="989,218" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-18" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-18.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-18.png" alt="different algorithms used to train recommender systems based on collaborative filtering " class="wp-image-4303" width="592" height="130" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-18.png 989w, https://www.relataly.com/wp-content/uploads/2021/05/image-18.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/image-18.png 768w" sizes="(max-width: 592px) 100vw, 592px" /></figure>



<h2 class="wp-block-heading" id="h-implementing-a-movie-recommender-in-python-using-collaborative-filtering">Implementing a Movie Recommender in Python using Collaborative Filtering</h2>



<p>Now it&#8217;s time to get our hands dirty and begin with implementing our movie recommender. As always, you find the code in the relataly git-hub repository. </p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_6a7ed1-b5"><a class="kb-button kt-button button kb-btn_7902e3-f8 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/05%20Recommender%20Systems/031Movie%20Recommender%20using%20Collaborative%20Filtering.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_26bd47-d7 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p>Before beginning the coding part, make sure that you have set up your Python 3 environment and required packages. If you don&#8217;t have an environment, consider the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda Python environment</a>. Follow <a href="https://www.relataly.com/category/data-science/setup-anaconda-environment/" target="_blank" rel="noreferrer noopener">this tutorial</a> to set it up.</p>



<p>Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>



<li><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>
</ul>



<p>In addition, we will be using <a href="https://seaborn.pydata.org/" target="_blank" rel="noreferrer noopener">Seaborn </a>for visualization and the recommender systems library <a href="https://www.fast.ai/" target="_blank" rel="noreferrer noopener"></a><em><a href="https://github.com/NicolasHug/Surprise" target="_blank" rel="noreferrer noopener">Scikit-Suprise</a></em>. You can install the surprise package by forging it with the following command: </p>



<ul class="wp-block-list">
<li><em>conda install -c conda-forge scikit-surprise</em></li>
</ul>



<p>You can install the other packages using standard console commands:</p>



<ul class="wp-block-list">
<li><em>pip install &lt;package name&gt;</em></li>



<li><em>conda install &lt;package name&gt;</em>&nbsp;(if you are using the anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading" id="h-about-the-imdb-movies-dataset">About the IMDB Movies Dataset</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>We will train our movie recommendation model on a popular Movies Dataset (you can download it from <a href="https://grouplens.org/datasets/movielens/latest/" target="_blank" rel="noreferrer noopener">grouplens.org</a>). The MovieLens recommendation service collected the Dataset from 610 users between 1996 and 2018. Unpack the data into the working folder of your project.</p>



<p>The full Dataset contains metadata on over 45,000 movies and 26 million ratings from over 270,000 users. However, we will be working with a subset of the data &#8220;ratings_small.csv,&#8221; which contains 100,836 ratings from 700 users on 9742 movies.</p>



<p>The Dataset contains the following files, from which we will only use the first two (Source of the data description: <a href="https://www.kaggle.com/rounakbanik/the-movies-dataset" target="_blank" rel="noreferrer noopener">Kaggle.com</a>):</p>



<ul class="wp-block-list">
<li><strong>movies_metadata.csv:</strong>&nbsp;The main Movies Metadata file contains information on 45,000 movies featured in the Full MovieLens Dataset. Features include posters, backdrops, budget, revenue, release dates, languages, production countries, and companies.</li>



<li><strong>ratings_small.csv:</strong>&nbsp;The subset of 100,000 ratings from 700 users on 9,000 movies. Each line corresponds to a single 5-star movie rating with half-star increments (0.5 &#8211; 5.0 stars).</li>
</ul>



<p>There are several other files included that we won&#8217;t use. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full is-resized"><img decoding="async" data-attachment-id="7128" data-permalink="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/mdb-movie-database/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png" data-orig-size="1024,537" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="recomender systems collaborative filtering imdb movies" data-image-description="&lt;p&gt;recomender systems collaborative filtering imdb movies&lt;/p&gt;
" data-image-caption="&lt;p&gt;recomender systems collaborative filtering imdb movies&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png" src="https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png" alt="MDB Movie Database Recommender Systems Collaborative Filtering " class="wp-image-7128" width="366" height="192" srcset="https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png 1024w, https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png 300w, https://www.relataly.com/wp-content/uploads/2022/04/MDB-Movie-Database.png 768w" sizes="(max-width: 366px) 100vw, 366px" /><figcaption class="wp-element-caption">IMDB Movie Database </figcaption></figure>
</div>
</div>



<h3 class="wp-block-heading" id="h-step-1-load-the-data">Step #1: Load the Data</h3>



<p>Ensure you have downloaded and unpacked the data and the required packages.</p>



<p>You can then load the movie data into our Python project using the code snippet below. We do not need all of the files in the movie dataset and only work with the following two.</p>



<ul class="wp-block-list">
<li>movies_metadata.csv</li>



<li>ratings_small.csv</li>
</ul>



<h4 class="wp-block-heading" id="h-1-1-load-the-movies-data">1.1 Load the Movies Data</h4>



<p>First, we will load the movies_metadata, which contains a list of all movies and meta information such as the release year, a short description, etc. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
from surprise import SVD, Dataset, Reader
from surprise.model_selection import train_test_split, cross_validate
from ast import literal_eval

# in case you have placed the files outside of your working directory, you need to specify a path
path = '' # for example: 'data/movie_recommendations/'  

# load the movie metadata
df_moviesmetadata=pd.read_csv(path + 'movies_metadata.csv', low_memory=False) 
print(df_moviesmetadata.shape)
print(df_moviesmetadata.columns)
df_moviesmetadata.head(1)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">(45466, 24)
Index(['adult', 'belongs_to_collection', 'budget', 'genres', 'homepage', 'id',
       'imdb_id', 'original_language', 'original_title', 'overview',
       'popularity', 'poster_path', 'production_companies',
       'production_countries', 'release_date', 'revenue', 'runtime',
       'spoken_languages', 'status', 'tagline', 'title', 'video',
       'vote_average', 'vote_count'],
      dtype='object')
	adult	belongs_to_collection								budget		genres												homepage								id	imdb_id		original_language	original_title	overview	...	release_date	revenue	runtime	spoken_languages	status	tagline	title	video	vote_average	vote_count
0	False	{'id': 10194, 'name': 'Toy Story Collection', ...	30000000	[{'id': 16, 'name': 'Animation'}, {'id': 35, '...	http://toystory.disney.com/toy-story	862	tt0114709	en					Toy Story		Led by Woody, Andy's toys live happily in his ...	...	1995-10-30	373554033.0	81.0	[{'iso_639_1': 'en', 'name': 'English'}]	Released	NaN	Toy Story	False	7.7	5415.0
1 rows × 24 columns</pre></div>



<h4 class="wp-block-heading" id="h-1-2-load-the-ratings-data">1.2 Load the Ratings Data</h4>



<p>We proceed by loading the rating file. This file contains the movie ratings for each user, the movieId, and a timestamp.</p>



<p>In addition, we print the value counts for rankings in our Dataset. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># load the movie ratings
df_ratings=pd.read_csv(path + 'ratings_small.csv', low_memory=False) 

print(df_ratings.shape)
print(df_ratings.columns)
df_ratings.head(3)

rankings_count = df_ratings.rating.value_counts().sort_values()
sns.barplot(x=rankings_count.index.sort_values(), y=rankings_count, color=&quot;b&quot;)
sns.set_theme(style=&quot;whitegrid&quot;)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">(100004, 4)
Index(['userId', 'movieId', 'rating', 'timestamp'], dtype='object')
	userId	movieId	rating	timestamp
0	1		31		2.5		1260759144
1	1		1029	3.0		1260759179
2	1		1061	3.0		1260759182</pre></div>



<p>As we can see, most of the ratings in our Dataset are positive.</p>



<h3 class="wp-block-heading" id="h-step-2-preprocessing-and-cleaning-the-data">Step #2 Preprocessing and Cleaning the Data</h3>



<p>We continue with the preprocessing of the data. The recommendations of a User-based Collaborative Filtering Approach rely solely on the interactions between users and items. This means training a prediction model does not require the meta-information of the movies. Nevertheless, we will load the metadata because it is just nicer to display the recommendations, movie title, release year, and so on, instead of just ids.</p>



<h4 class="wp-block-heading" id="h-2-1-clean-the-movie-data">2.1 Clean the Movie Data</h4>



<p>Unfortunately, the data quality of the movies&#8217; metadata is not excellent, so we need to fix a few things. The following operations will change some data types to integers, extract the release year and genres, and remove some records with incorrect data.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># remove invalid records with invalid ids
df_mmeta = df_moviesmetadata.drop([19730, 29503, 35587])

df_movies = pd.DataFrame()

# extract the release year 
df_movies['year'] = pd.to_datetime(df_mmeta['release_date'], errors='coerce').apply(lambda x: str(x).split('-')[0] if x != np.nan else np.nan)

# extract genres
df_movies['genres'] = df_mmeta['genres'].fillna('[]').apply(literal_eval).apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])

# change the index to movie_id
df_movies['movieId'] = pd.to_numeric(df_mmeta['id'])
df_movies = df_movies.set_index('movieId')

# add vote count
df_movies['vote_count'] = df_movies['vote_count'].astype('int')
df_movies</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">title									vote_count	vote_average	year	genres
		movieId					
862		Toy Story						5415			7.7	1995	[Animation, Comedy, Family]
8844	Jumanji							2413			6.9	1995	[Adventure, Fantasy, Family]
15602	Grumpier Old Men				92				6.5	1995	[Romance, Comedy]
31357	Waiting to Exhale				34				6.1	1995	[Comedy, Drama, Romance]
11862	Father of the Bride Part II		173				5.7	1995	[Comedy]
...	...	...	...	...	...
49279	The Man with the Rubber Head	29				7.6	1901	[Comedy, Fantasy, Science Fiction]
49271	The Devilish Tenant				12				6.7	1909	[Fantasy, Comedy]
49280	The One-Man Band				22				6.5	1900	[Fantasy, Action, Thriller]
404604	Mom								14				6.6	2017	[Crime, Drama, Thriller]
30840	Robin Hood						26				5.7	1991	[Drama, Action, Romance]
22931 rows × 5 columns</pre></div>



<h4 class="wp-block-heading" id="h-2-2-clean-the-ratings-data">2.2 Clean the Ratings Data</h4>



<p>Compared to the movie metadata, not much more needs to be done to the rating data. Here we just put the timestamp into a readable format.</p>



<p>One of the following steps is to use the Reader class from the Surprise library to parse the ratings and put them into a format compatible with standard recommendation algorithms from the Surprise library. The Reader needs the data in the form where each line contains only one rating and respects the following structure:</p>



<p>user; item ; rating ; timestamp</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># drop na values
df_ratings_temp = df_ratings.dropna()

# convert datetime
df_ratings_temp['timestamp'] = pd. to_datetime(df_ratings_temp['timestamp'], unit='s')

print(f'unique users: {len(df_ratings_temp.userId.unique())}, ratings: {len(df_ratings_temp)}')
df_ratings_temp.head()</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">unique users: 671, ratings: 100004
	userId		movieId	rating	timestamp
0	1			31		2.5		2009-12-14 02:52:24
1	1			1029	3.0		2009-12-14 02:52:59
2	1			1061	3.0		2009-12-14 02:53:02
3	1			1129	2.0		2009-12-14 02:53:05
4	1			1172	4.0		2009-12-14 02:53:25</pre></div>



<h3 class="wp-block-heading" id="h-step-3-split-the-data-in-train-and-test">Step #3: Split the Data in Train and Test</h3>



<p>Next, we will split the data into train and test sets. In this way, we ensure that we can later evaluate the performance of our recommender model on data that the model has not yet seen. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># The Reader class is used to parse a file containing ratings.
# The file is assumed to specify only one rating per line, such as in the df_ratings_temp file above.
reader = Reader()
ratings_by_users = Dataset.load_from_df(df_ratings_temp[['userId', 'movieId', 'rating']], reader)

# Split the Data into train and test
train_df, test_df = train_test_split(ratings_by_users, test_size=.2)</pre></div>



<p>Once we have split the data into train and test, we can train the recommender model.</p>



<h3 class="wp-block-heading" id="h-step-4-train-a-movie-recommender-using-collaborative-filtering">Step #4: Train a Movie Recommender using Collaborative Filtering</h3>



<p>Training the SVD model requires only lines of code. The first line creates an untrained model that uses Probabilistic Matrix Factorization for dimensionality reduction. The second line will fit this model to the training data. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># train an SVD model
svd_model = SVD()
svd_model_trained = svd_model.fit(train_df)</pre></div>



<h3 class="wp-block-heading" id="h-step-5-evaluate-prediction-performance-using-cross-validation">Step #5: Evaluate Prediction Performance using Cross-Validation</h3>



<p>Next, it is time to validate the performance of our movie recommendation program. For this, we use k-fold cross-validation. As a reminder, cross-validation involves splitting the Dataset into different folds and then measuring the prediction performance based on each fold.</p>



<p>We can measure model performance using indicators such as mean absolute error (MAE) or mean squared error (MSE). The MAE is the average difference between predicting a movie and the actual ratings. We chose this measure because it is easy to understand.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># 10-fold cross validation 
cross_val_results = cross_validate(svd_model_trained, ratings_by_users, measures=['RMSE', 'MAE', 'MSE'], cv=10, verbose=False)
test_mae = cross_val_results['test_mae']

# mean squared errors per fold
df_test_mae = pd.DataFrame(test_mae, columns=['Mean Absolute Error'])
df_test_mae.index = np.arange(1, len(df_test_mae) + 1)
df_test_mae.sort_values(by='Mean Absolute Error', ascending=False).head(15)

# plot an overview of the performance per fold
plt.figure(figsize=(6,4))
sns.set_theme(style=&quot;whitegrid&quot;)
sns.barplot(y='Mean Absolute Error', x=df_test_mae.index, data=df_test_mae, color=&quot;b&quot;)
# plt.title('Mean Absolute Error')</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="4385" data-permalink="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/image-41-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-41.png" data-orig-size="598,366" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-41" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-41.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-41.png" alt="movie recommender performance" class="wp-image-4385" width="651" height="399" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-41.png 598w, https://www.relataly.com/wp-content/uploads/2021/05/image-41.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/image-41.png 80w" sizes="(max-width: 651px) 100vw, 651px" /></figure>



<p>The chart above shows that the mean deviation of our predictions from the actual rating is a little below 0.7. The result is not terrific but ok for a first model. In addition, there are no significant differences between the performance in the different folds. Let&#8217;s keep in mind that the MAE says little about possible outliers in the predictions. However, since we are dealing with ordinal predictions (1-5), the influence of outliers is naturally limited.</p>



<h3 class="wp-block-heading" id="h-step-6-generate-predictions">Step #6: Generate Predictions </h3>



<p>Finally, we will use our movie recommender to generate a list of suggested movies for a specific test user. The predictions will be based on the user&#8217;s previous movie ratings.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># predict ratings for a single user_id and for all movies
user_id = 400 # some test user from the ratings file

# create the predictions
pred_series= []
df_ratings_filtered = df_ratings[df_ratings['userId'] == user_id]

print(f'number of ratings: {df_ratings_filtered.shape[0]}')
for movie_id, name in zip(df_movies.index, df_movies['title']):
    # check if the user has already rated a specific movie from the list
    rating_real = df_ratings.query(f'movieId == {movie_id}')['rating'].values[0] if movie_id in df_ratings_filtered['movieId'].values else 0
    # generate the prediction
    rating_pred = svd_model_trained.predict(user_id, movie_id, rating_real, verbose=False)
    # add the prediction to the list of predictions
    pred_series.append([movie_id, name, rating_pred.est, rating_real])

# print the results
df_recommendations = pd.DataFrame(pred_series, columns=['movieId', 'title', 'predicted_rating', 'actual_rating'])
df_recommendations.sort_values(by='predicted_rating', ascending=False).head(15)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">		movieId	title								predicted_rating	actual_rating
4234	4993	5 Card Stud							4.721481			0.0
3194	318		The Million Dollar Hotel			4.648623			5.0
442		858		Sleepless in Seattle				4.506962			0.0
236		527		Once Were Warriors					4.484758			4.0
2426	926		Galaxy Quest						4.465653			0.0
6532	905		Pandora's Box						4.452688			0.0
710		260		The 39 Steps						4.390318			0.0
8787	3683	Flags of Our Fathers				4.386821			0.0
5400	899		Broken Blossoms						4.384220			0.0
5068	296		Terminator 3: Rise of the Machines	4.383057			4.0
372		2019	Hard Target							4.365834			0.0
7254	919		Blood: The Last Vampire				4.356012			0.0
3295	4973	Under the Sand						4.355750			0.0
3869	194		Amélie								4.353614			0.0
8631	1948	Crank								4.344286			0.0</pre></div>



<p>Alternatively, we can predict how well a specific user will rate a movie by handing the user_id and the movie_id to the model. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># predict ratings for the combination of user_id and movie_id
user_id = 217 # some test user from the ratings file
movie_id = 4002
rating_real = df_ratings.query(f'movieId == {movie_id} &amp; userId == {user_id}')['rating'].values[0]
movie_title = df_movies[df_movies.index == 862]['title'].values[0]

print(f'Movie title: {movie_title}')
print(f'Actual rating: {rating_real}')

# predict and show the result
rating_pred = svd_model_trained.predict(user_id, movie_id, rating_real, verbose=True)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Movie title: Toy Story
Actual rating: 4.5
user: 217        item: 4002       r_ui = 4.50   est = 3.98   {'was_impossible': False}</pre></div>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>Congratulations on learning how to develop a movie recommendation system in Python! In this article, you learned about the SVD model, which uses matrix factorization and collaborative filtering to predict movie ratings for a given user. We also demonstrated how to perform cross-validation on a movie dataset and use the model to generate movie recommendations.</p>



<p>Several other approaches can be used to develop a movie recommendation system, <a href="https://wp.me/pbUnJO-17g" target="_blank" rel="noreferrer noopener">including content-based filtering</a>, which uses features of the movies themselves (such as genre, director, and cast) to make recommendations, and hybrid systems, which combine the strengths of multiple approaches.</p>



<p>Regardless of the approach used, building a movie recommendation system can be a useful tool for recommending movies to users based on their past preferences and can help increase engagement and satisfaction with a movie streaming service or website.</p>



<p>If you like the post, please let me know in the comments, and don&#8217;t forget to subscribe to our <a href="https://twitter.com/home" target="_blank" rel="noreferrer noopener">Twitter account</a> to stay up to date on upcoming articles.</p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<p>Below are some resources for further reading on recommender systems and content-based models.</p>



<p><strong>Books</strong></p>



<ol class="wp-block-list"><li><a href="https://amzn.to/3T3Sl2V" target="_blank" rel="noreferrer noopener">Charu C. Aggarwal (2016) Recommender Systems: The Textbook</a></li><li><a href="https://amzn.to/3D0P8eX" target="_blank" rel="noreferrer noopener">Kin Falk (2019) Practical Recommender Systems</a></li><li><a href="https://amzn.to/3MAy8j5" target="_blank" rel="noreferrer noopener">Andriy Burkov (2020) Machine Learning Engineering</a></li><li><a href="https://amzn.to/3D0gB0e" target="_blank" rel="noreferrer noopener">Oliver Theobald (2020) Machine Learning For Absolute Beginners: A Plain English Introduction</a></li><li><a href="https://amzn.to/3S9Nfkl" target="_blank" rel="noreferrer noopener">Aurélien Géron (2019) Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems </a></li><li><a href="https://amzn.to/3EKidwE" target="_blank" rel="noreferrer noopener">David Forsyth (2019) Applied Machine Learning Springer</a></li></ol>



<p class="has-contrast-2-color has-base-3-background-color has-text-color has-background"><em>The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.</em></p>



<p><strong>Articles</strong></p>



<ol class="wp-block-list"><li><a href="https://surprise.readthedocs.io/en/stable/getting_started.html" target="_blank" rel="noreferrer noopener">Getting started with Suprise</a></li><li><a href="https://onespire.hu/sap-news-en/history-of-recommender-systems/" target="_blank" rel="noreferrer noopener">About the history of Recommender Systems</a></li><li><a href="https://www.freecodecamp.org/news/singular-value-decomposition-vs-matrix-factorization-in-recommender-systems-b1e99bc73599/" target="_blank" rel="noreferrer noopener"></a><a href="https://www.freecodecamp.org/news/singular-value-decomposition-vs-matrix-factorization-in-recommender-systems-b1e99bc73599/" target="_blank" rel="noreferrer noopener">Singular value decomposition vs. matrix factorization</a></li><li><a href="https://proceedings.neurips.cc/paper/2007/file/d7322ed717dedf1eb4e6e52a37ea7bcd-Paper.pdf" target="_blank" rel="noreferrer noopener">Probabilistic Matrix Factorization</a></li></ol>
<p>The post <a href="https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/">Build a High-Performing Movie Recommender System using Collaborative Filtering in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/building-a-movie-recommender-using-collaborative-filtering/4376/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4376</post-id>	</item>
		<item>
		<title>Forecasting Beer Sales with ARIMA in Python</title>
		<link>https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/</link>
					<comments>https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Wed, 03 Feb 2021 22:23:08 +0000</pubDate>
				<category><![CDATA[ARIMA]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Manufacturing]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Retail]]></category>
		<category><![CDATA[Sales Forecasting]]></category>
		<category><![CDATA[statsmodels]]></category>
		<category><![CDATA[Stock Market Forecasting]]></category>
		<category><![CDATA[Telecommunications]]></category>
		<category><![CDATA[Time Series Forecasting]]></category>
		<category><![CDATA[Use Cases]]></category>
		<category><![CDATA[AI in Business]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[Classic Machine Learning]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<category><![CDATA[Supervised Learning]]></category>
		<category><![CDATA[Univariate Time Series Forecasting]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=2884</guid>

					<description><![CDATA[<p>Time series analysis and forecasting is a tough nut to crack, but the ARIMA model has been cracking it for decades. ARIMA, short for &#8220;Auto-Regressive Integrated Moving Average,&#8221; is a powerful statistical modeling technique for time series analysis. It&#8217;s particularly effective when the time series you&#8217;re analyzing follows a clear pattern, like seasonal changes in ... <a title="Forecasting Beer Sales with ARIMA in Python" class="read-more" href="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/" aria-label="Read more about Forecasting Beer Sales with ARIMA in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/">Forecasting Beer Sales with ARIMA in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Time series analysis and forecasting is a tough nut to crack, but the ARIMA model has been cracking it for decades. ARIMA, short for &#8220;Auto-Regressive Integrated Moving Average,&#8221; is a powerful statistical modeling technique for time series analysis. It&#8217;s particularly effective when the time series you&#8217;re analyzing follows a clear pattern, like seasonal changes in weather or sales. ARIMA has been used to forecast everything from beer sales to order quantities, and this tutorial will show you how to build your own ARIMA model in Python. You&#8217;ll be making predictions like a pro in no time!</p>



<p>This tutorial proceeds in two parts: The first part covers the concepts behind ARIMA. You will learn how ARIMA works, what Stationarity means, and when it is appropriate to use ARIMA. The second part is a Python hands-on tutorial that applies auto-ARIMA to the Sales Forecasting domain. We&#8217;ll be working with a time series of beer sales, and our goal is to predict how the beer sales quantities will evolve in the coming years. First, we check if the time series is stationary. Then we train an ARIMA forecasting model. Finally, we use the model to produce a sales forecast and measure the model&#8217;s performance.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:12px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">About Sales Forecasting</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Sales forecasting is a crucial business strategy that involves predicting future sales volumes for a product (for example, beer) or service. It leverages sophisticated statistical and analytical techniques, such as time series analysis or machine learning algorithms, to scrutinize historical sales data. By identifying trends and patterns within this data, businesses can make informed predictions about their future sales performance.</p>



<p>This strategic forecasting plays a pivotal role in business operations. It is instrumental in guiding key decisions surrounding production, inventory management, staffing, and various other operational elements. By honing in on accurate sales forecasting, businesses can strike the perfect balance &#8211; maintaining enough inventory to meet customer demand without overproducing or overstocking. This equilibrium ensures a smooth flow in the supply chain and avoids unnecessary costs tied to excess production or storage.</p>



<p>Furthermore, sales forecasting serves as a roadmap for business growth. It aids in identifying potential market opportunities and predicting future sales revenue. This valuable foresight enables businesses to strategically plan their expansion, ensuring resources are optimally utilized and future goals are met. With this in-depth understanding of sales forecasting, businesses can stay ahead of market trends, navigate through business challenges, and ultimately steer towards success.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="506" height="508" data-attachment-id="12602" data-permalink="https://www.relataly.com/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly-min.png" data-orig-size="506,508" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="brewery arima beer sales forecasting python tutorial machine learning relataly-min" data-image-description="&lt;p&gt;Businesses rely on sales forecasting to make informed decisions about production, inventory management, staffing, and other key operational aspects.  Image created with Midjourney&lt;/p&gt;
" data-image-caption="&lt;p&gt;Businesses rely on sales forecasting to make informed decisions about production, inventory management, staffing, and other key operational aspects.  Image created with Midjourney&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly-min.png" alt="Businesses rely on sales forecasting to make informed decisions about production, inventory management, staffing, and other key operational aspects.  Image created with Midjourney" class="wp-image-12602" srcset="https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly-min.png 506w, https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly-min.png 140w" sizes="(max-width: 506px) 100vw, 506px" /><figcaption class="wp-element-caption">Businesses rely on sales forecasting to make informed decisions about production, inventory management, staffing, and other key operational aspects. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div>
</div>



<div style="height:26px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading" id="h-introduction-to-arima-time-series-modelling">Introduction to ARIMA Time Series Modelling</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>ARIMA models provide an alternative approach to time series forecasting that differs significantly from machine learning methods. Working with ARIMA requires a good understanding of Stationarity and knowledge of the transformations used to make time-series data stationary. The concept of Stationarity is, therefore, first on our schedule.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h3 class="wp-block-heading" id="h-the-concept-of-stationarity">The Concept of Stationarity</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Stationarity is an essential concept in stochastic processes that describes the nature of a time series. We consider a time series strictly stationary if its statistical properties do not change over time. In this case, summary statistics, such as the mean and variance, do not change over time. However, the time-series data we encounter in the real world often show a trend or significant irregular fluctuations, making them non-stationary or weakly stationary.</p>



<p>So why is Stationarity such an essential concept for ARIMA? If a time series is stationary, we can assume that the past values of the time series are predictive of future development. In other words, a stationary time series exhibits consistent behavior that makes it predictable. On the other hand, a non-stationary time series is characterized by a kind of random behavior that will be difficult to capture in modeling. Namely, if random movements characterized the past, there is a high probability that the future will be no different.</p>



<p>Fortunately, in many cases, it is possible to transform a time series that is non-stationary into a stationary form and, in this way, build better prediction models.</p>



<div style="height:56px" aria-hidden="true" class="wp-block-spacer"></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="802" height="751" data-attachment-id="8592" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/image-25-8/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/05/image-25.png" data-orig-size="802,751" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-25" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/05/image-25.png" src="https://www.relataly.com/wp-content/uploads/2022/05/image-25.png" alt="arima time series forecasting, stationary vs non-stationary data, python tutorial " class="wp-image-8592" srcset="https://www.relataly.com/wp-content/uploads/2022/05/image-25.png 802w, https://www.relataly.com/wp-content/uploads/2022/05/image-25.png 300w, https://www.relataly.com/wp-content/uploads/2022/05/image-25.png 768w" sizes="(max-width: 802px) 100vw, 802px" /><figcaption class="wp-element-caption">A stationary Vs. a non-stationary time series</figcaption></figure>
</div>
</div>



<h3 class="wp-block-heading">How to Test Whether a Time Series is Stationary</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The first step in the ARIMA modeling approach is determining whether a time series is stationary. There are different ways to determine whether a time series is stationary:</p>



<ul class="wp-block-list">
<li><strong>Plotting:</strong> We can plot the time series and visually check if it shows consistent behavior or changes over a more extended period.</li>



<li><strong>Summary statistics</strong>: We can split the time series into different periods and calculate the summary statistics, such as the variance. If these metrics are subject to significant changes, the time series is non-stationary. However, the results will also depend on the respective periods, leading to false conclusions.</li>



<li><strong>Statistic tests</strong>: There are various tests to determine the stationary of a time series, such as Kwiatkowski–Phillips–Schmidt–Shin, Augmented Dickey-Fuller, or Phillips–Perron. These tests systematically check a time series and measure the results against the null hypothesis, providing an indicator of the trustworthiness of the results.</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:56px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-what-is-an-s-arima-model">What is an (S)ARIMA Model?</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>As the name implies, ARIMA uses autoregression (AR), integration (differencing), and moving averages (MA) to fit a linear regression model to a time series. </p>



<h4 class="wp-block-heading" id="h-arima-parameters">ARIMA Parameters</h4>



<p>The default notation for ARIMA is a model with parameters p, d, and q, whereby each parameter takes an integer value: </p>



<ul class="wp-block-list">
<li><strong>d (differencing): </strong>In the case of a non-stationary time series, there is a chance to remove a trend from the data by differencing once or several times, thus bringing the data to a stationary state. The model parameter d determines the order of the differentiation. A value of d = 0 simplifies the ARIMA model to an ARMA model, lacking the integration aspect. If this is the case, we do not need to integrate the function because the time series is already stationary.</li>



<li><strong>p (order of the AR terms):</strong> The autoregressive process describes the dependent relationship between an observation and several lagged observations (lags). Predictions are then based on past data from the same time series using linear functions. p = 1 means the model uses values that lag by one period. </li>



<li><strong> q (order of the MA terms):</strong> The parameter q determines the number of lagged forecast errors in the prediction equation. In contrast to the AR process, the MA process assumes that values at a future point in time depend on the errors made by predictions at current and past points in time. This means that it is not previous events that determine the predictions but rather the previous estimation or prediction errors used to calculate the following time series value.</li>
</ul>



<h4 class="wp-block-heading" id="h-sarima">SARIMA</h4>



<p>In the real world, many time series have seasonal effects. Examples are monthly retail sales figures, temperature reports, weekly airline passenger data, etc. To consider this, we can specify a seasonal range (e.g., m=12 for monthly data) and additional seasonal AR or MA components for our model that deal with seasonality. Such a model is also called a SARIMA model, and we can define it as a model(p, d, q)(P, D, Q)[m]. </p>



<h4 class="wp-block-heading" id="h-auto-s-arima">Auto-(S)ARIMA </h4>



<p>When working with ARIMA, we can set the model parameters manually or use auto-ARIMA and let the model search for the optimal parameters. We do this by varying the parameters and then testing against Stationarity. With the seasonal option enabled, the process tries to identify the optimal hyperparameters for the seasonal components of the model. Auto-ARIMA works by conducting differencing tests to determine the order of differencing,&nbsp;<code>d</code> and then fitting models with parameters in defined ranges, e.g., start_<code>p</code>,&nbsp;<code>max_p</code>&nbsp;as well as <code>start_q</code>,&nbsp;<code>max_q</code>. If our model has a seasonal component, we can also define parameter ranges for the seasonal part of the model. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:56px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading" id="h-creating-a-sales-forecast-with-arima-in-python">Creating a Sales Forecast with ARIMA in Python</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Having grasped the fundamental concepts behind ARIMA (AutoRegressive Integrated Moving Average), we&#8217;re now ready to dive into the practical aspect of crafting a sales forecasting model in Python. Utilizing ARIMA for forecasting sales data is an esteemed practice owing to the algorithm&#8217;s adeptness in modeling seasonal changes combined with long-term trends &#8211; a characteristic commonly exhibited by sales data.</p>



<p>In this tutorial, we&#8217;ll be employing a dataset representing the monthly beer sales across the United States from 1992 through 2018, recorded in millions of US dollars. Our objective is to construct a robust time series model using ARIMA to accurately predict future sales trends.</p>



<p>When it comes to the technological aspect, we&#8217;ll be using the Python-based &#8216;statsmodels&#8217; and &#8216;pmdarima&#8217; libraries to build our ARIMA sales forecasting model. So, if you&#8217;re ready to harness the power of Python and ARIMA for sales prediction, let&#8217;s get started!</p>



<p>The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_87ac48-a9"><a class="kb-button kt-button button kb-btn_a01710-14 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/01%20Time%20Series%20Forecasting%20%26%20Regression/001%20Forecasting%20US%20Beer%20Sales%20with%20(auto)%20ARIMA.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_ff77d5-62 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="512" height="512" data-attachment-id="12612" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/a-car-drinking-beer-after-creating-an-arima-sales-forecast-min-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1.png" data-orig-size="1024,1024" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1.png" src="https://www.relataly.com/wp-content/uploads/2023/03/A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1-512x512.png" alt="A fluffy cat drinking beer after creating an ARIMA sales forecast. Image created with Midjourney" class="wp-image-12612" srcset="https://www.relataly.com/wp-content/uploads/2023/03/A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1.png 140w, https://www.relataly.com/wp-content/uploads/2023/03/A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/A-car-drinking-beer-after-creating-an-ARIMA-sales-forecast-min-1.png 1024w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">A fluffy cat drinking beer after creating an ARIMA sales forecast. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p>Before we start coding, ensure you have set up your Python 3 environment and required packages. If you don&#8217;t have an environment, you can follow&nbsp;this tutorial&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda environment</a>.</p>



<p>Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>



<li><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>
</ul>



<p>In addition, we will be using the <a href="https://www.statsmodels.org/stable/index.html" target="_blank" rel="noreferrer noopener">statsmodels </a>library and <a href="https://pypi.org/project/pmdarima/" target="_blank" rel="noreferrer noopener">pmdarima</a>. </p>



<p>You can install packages using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install &lt;package name&gt;</em></li>



<li><em>conda install &lt;package name&gt;</em>&nbsp;(if you are using the anaconda packet manager)</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h3 class="wp-block-heading" id="h-step-1-load-the-sales-data-to-our-python-project">Step #1 Load the Sales Data to Our Python Project</h3>



<p>In the initial step of this tutorial, we commence by setting up the necessary Python environment. We import several packages that we&#8217;ll be using for data manipulation, visualization, and implementing machine learning models. We then fetch the dataset we&#8217;ll be working with &#8211; the monthly beer sales in the United States from 1992 through 2018. This data is sourced from a publicly accessible URL and loaded into a pandas DataFrame.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># A tutorial for this file is available at www.relataly.com
# Tested with Python 3.88

# Setting up packages for data manipulation and machine learning
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pmdarima as pm
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.tsa.seasonal import seasonal_decompose
import seaborn as sns
sns.set_style('white', { 'axes.spines.right': False, 'axes.spines.top': False})

# Link to the dataset: 
# https://www.kaggle.com/bulentsiyah/for-simple-exercises-time-series-forecasting

path = &quot;https://raw.githubusercontent.com/flo7up/relataly_data/main/alcohol_sales/BeerWineLiquor.csv&quot;
df = pd.read_csv(path)
df.head()</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">		date	beer
0	1/1/1992	1509
1	2/1/1992	1541
2	3/1/1992	1597
3	4/1/1992	1675
4	5/1/1992	1822</pre></div>



<p>As shown above, the sales figures in this dataset stem from the first day of each month.</p>



<h3 class="wp-block-heading" id="h-step-2-visualize-the-time-series-and-check-it-for-stationarity">Step #2 Visualize the Time Series and Check it for Stationarity</h3>



<p>Before modeling the sales data, we visualize the time series and test it for Stationarity. Visualization helps us choose the parameters for our ARIMA model, thus making it an essential step.</p>



<p>First, we will look at the different components of the time series. We do this by using the seasonal_decompose function of the statsmodels library. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Decompose the time series
plt.rcParams[&quot;figure.figsize&quot;] = (10,6)
result = seasonal_decompose(df['beer'], model='multiplicative', period = 12)
result.plot()
plt.show()</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="4890" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/image-62-3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/06/image-62.png" data-orig-size="712,568" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-62" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/06/image-62.png" src="https://www.relataly.com/wp-content/uploads/2021/06/image-62.png" alt="forecasting us beer sales - time series decomposition" class="wp-image-4890" width="754" height="602" srcset="https://www.relataly.com/wp-content/uploads/2021/06/image-62.png 712w, https://www.relataly.com/wp-content/uploads/2021/06/image-62.png 300w" sizes="(max-width: 754px) 100vw, 754px" /></figure>



<p>To test for Stationarity, we use the ADFuller test. It is common to run this test multiple times throughout a data science project. Therefore, we create a function that we can then reuse later.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def check_stationarity(df_sales, title_string, labels):
    # Visualize the data
    fig, ax = plt.subplots(figsize=(16, 8))
    plt.title(title_string, fontsize=14)
    if df_sales.index.size &gt; 12:
        df_sales['ma_12_month'] = df_sales['beer'].rolling(window=12).mean()
        df_sales['ma_25_month'] = df_sales['beer'].rolling(window=25).mean()
        sns.lineplot(data=df_sales[['beer', 'ma_25_month', 'ma_12_month']], palette=sns.color_palette(&quot;mako_r&quot;, 3))
        plt.legend(title='Smoker', loc='upper left', labels=labels)
    else:
        sns.lineplot(data=df_sales[['beer']])
    
    plt.show()
    
    sales = df_sales['beer'].dropna()
    # Perform an Ad Fuller Test
    # the default alpha = .05 stands for a 95% confidence interval
    adf_test = pm.arima.ADFTest(alpha = 0.05) 
    print(adf_test.should_diff(sales))
    
df_sales = pd.DataFrame(df['beer'], columns=['beer'])
df_sales.index = pd.to_datetime(df['date']) 
title = &quot;Beer sales in the US between 1992 and 2018 in million US$/month&quot;
labels = ['beer', 'ma_12_month', 'ma_25_month']
check_stationarity(df_sales, title, labels)</pre></div>



<figure class="wp-block-image size-full"><img decoding="async" width="940" height="495" data-attachment-id="8582" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/arima-time-series/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/05/ARIMA-Time-series.png" data-orig-size="940,495" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ARIMA-Time-series" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/05/ARIMA-Time-series.png" src="https://www.relataly.com/wp-content/uploads/2022/05/ARIMA-Time-series.png" alt="arima plot seaborn beer sales forecasting python" class="wp-image-8582" srcset="https://www.relataly.com/wp-content/uploads/2022/05/ARIMA-Time-series.png 940w, https://www.relataly.com/wp-content/uploads/2022/05/ARIMA-Time-series.png 300w, https://www.relataly.com/wp-content/uploads/2022/05/ARIMA-Time-series.png 768w" sizes="(max-width: 940px) 100vw, 940px" /></figure>



<p>The data does not appear to be stationary. We can see that our time series is steadily increasing and shows annual seasonality. The steady increase indicates a continuous growth in beer consumption over the last decades. The seasonality in the sales data likely results from people drinking more beer in summer than in other seasons.</p>



<h3 class="wp-block-heading" id="h-step-3-exemplary-differencing-and-autocorrelation">Step #3 Exemplary Differencing and Autocorrelation</h3>



<p>The chart from the previous section shows that our time series is non-stationary. The reason is that it follows a clear upward trend. We also know that the time series has a seasonal component. Therefore, we need to define additional parameters and construct a SARIMA model.</p>



<p>Before we use auto-correlation to determine the optimal parameters, we will try manual differencing to make the time series stationary. There is no guarantee that differencing works. It is essential to remember that differencing can sometimes also worsen prediction performance. So be careful, not to overdifference! We could also trust that the auto-ARIMA model chooses the best parameters for us. However, we should always validate the selected parameters.</p>



<p>The ideal differencing parameter is the least number of differencing steps to achieve a stationary time series. We will monitor the results with autocorrelation plots to check whether differencing was successful.</p>



<p>We print the autocorrelation for the original time series and after the first and second-order differencing.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># 3.1 Non-seasonal part
def auto_correlation(df, prefix, lags):
    plt.rcParams.update({'figure.figsize':(7,7), 'figure.dpi':120})
    
    # Define the plot grid
    fig, axes = plt.subplots(3,2, sharex=False)

    # First Difference
    axes[0, 0].plot(df)
    axes[0, 0].set_title('Original' + prefix)
    plot_acf(df, lags=lags, ax=axes[0, 1])

    # First Difference
    df_first_diff = df.diff().dropna()
    axes[1, 0].plot(df_first_diff)
    axes[1, 0].set_title('First Order Difference' + prefix)
    plot_acf(df_first_diff, lags=lags - 1, ax=axes[1, 1])

    # Second Difference
    df_second_diff = df.diff().diff().dropna()
    axes[2, 0].plot(df_second_diff)
    axes[2, 0].set_title('Second Order Difference' + prefix)
    plot_acf(df_second_diff, lags=lags - 2, ax=axes[2, 1])
    plt.tight_layout()
    plt.show()
    
auto_correlation(df_sales['beer'], '', 10)</pre></div>



<figure class="wp-block-image size-full is-resized"><img decoding="async" data-attachment-id="7076" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/image-8-14/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/image-8.png" data-orig-size="826,824" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-8" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/image-8.png" src="https://www.relataly.com/wp-content/uploads/2022/04/image-8.png" alt="ARIMA Python Time Series Forecasting Sales Data, checking for stationarity" class="wp-image-7076" width="561" height="560" srcset="https://www.relataly.com/wp-content/uploads/2022/04/image-8.png 826w, https://www.relataly.com/wp-content/uploads/2022/04/image-8.png 300w, https://www.relataly.com/wp-content/uploads/2022/04/image-8.png 150w, https://www.relataly.com/wp-content/uploads/2022/04/image-8.png 768w" sizes="(max-width: 561px) 100vw, 561px" /></figure>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">(0.019143247561160443, False)</pre></div>



<p id="block-db542169-554a-4820-a6a7-a0df5b3b9b6e">The charts above show that the time series becomes stationary after one order differencing. However, we can see that the lag goes into the negative very quickly, which indicates overdifferencing.</p>



<p>Next, we perform the same procedure for the seasonal part of our time series.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># 3.2 Seasonal part

# Reduce the timeframe to a single seasonal period
df_sales_s = df_sales['beer'][0:12]

# Autocorrelation for the seasonal part
auto_correlation(df_sales_s, '', 10)</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="3102" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/image-20-5/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/03/image-20.png" data-orig-size="831,827" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-20" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/03/image-20.png" src="https://www.relataly.com/wp-content/uploads/2021/03/image-20.png" alt="arima time series components" class="wp-image-3102" width="571" height="568" srcset="https://www.relataly.com/wp-content/uploads/2021/03/image-20.png 831w, https://www.relataly.com/wp-content/uploads/2021/03/image-20.png 150w, https://www.relataly.com/wp-content/uploads/2021/03/image-20.png 768w, https://www.relataly.com/wp-content/uploads/2021/03/image-20.png 120w" sizes="(max-width: 571px) 100vw, 571px" /></figure>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Check if the first difference of the seasonal period is stationary
df_diff = pd.DataFrame(df_sales_s.diff())
df_diff.index = pd.date_range(df_sales_s.diff().iloc[1], periods=12, freq='MS') 
check_stationarity(df_diff, &quot;First Difference (Seasonal)&quot;, ['difference'])</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="3010" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/image-8-9/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/03/image-8.png" data-orig-size="1569,441" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-8" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/03/image-8.png" src="https://www.relataly.com/wp-content/uploads/2021/03/image-8-1024x288.png" alt="seasonality after differencing, arima time series forecasting" class="wp-image-3010" width="687" height="193" srcset="https://www.relataly.com/wp-content/uploads/2021/03/image-8.png 1024w, https://www.relataly.com/wp-content/uploads/2021/03/image-8.png 300w, https://www.relataly.com/wp-content/uploads/2021/03/image-8.png 768w, https://www.relataly.com/wp-content/uploads/2021/03/image-8.png 1536w, https://www.relataly.com/wp-content/uploads/2021/03/image-8.png 1569w" sizes="(max-width: 687px) 100vw, 687px" /></figure>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">(0.99, True)</pre></div>



<p id="block-3731e774-0091-46b9-afa1-2d55e1512fdd">After first order differencing, the seasonal part of the time series is stationary. The autocorrelation plot shows that the values go into the negative but remain within acceptable boundaries. Second-order differencing does not seem to improve these values. Consequently, we conclude that first-order differencing is a good choice for the D parameter. </p>



<h3 class="wp-block-heading" id="h-step-4-finding-an-optimal-model-with-auto-arima">Step #4 Finding an Optimal Model with Auto-ARIMA</h3>



<p>Next, we auto-fit an ARIMA model to our time series. In this way, we ensure that we can later measure the performance of our model against a fresh set of data that the model has not seen so far. We will split our dataset into train and test in preparation for this. </p>



<p>Once we have created the train and test data sets, we can configure the parameters for the auto_arima stepwise optimization. By setting max_d = 1, we tell the model to test no-differencing and first-order differencing. Also, we set max_p and max_q to 3. </p>



<p>To deal with the seasonality in our time series, we set the &#8220;seasonal&#8221; parameter to True and the &#8220;m&#8221; parameter to 12 data points. We turn our model into a SARIMA model that allows us to configure additional D, P, and Q parameters. We define a max value for Q and P of 3. Previously we have already seen that further differencing does not improve the Stationarity. Therefore, we can set the value of D to 1.</p>



<p>After configuring the parameters, we next fit the model to the time series. The model will try to find the optimal parameters and choose the model with the least AIC.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># split into train and test
pred_periods = 30
split_number = df_sales['beer'].count() - pred_periods # corresponds to a prediction horizion  of 2,5 years
df_train = pd.DataFrame(df_sales['beer'][:split_number]).rename(columns={'beer':'y_train'})
df_test = pd.DataFrame(df_sales['beer'][split_number:]).rename(columns={'beer':'y_test'})

# auto_arima
model_fit = pm.auto_arima(df_train, test='adf', 
                         max_p=3, max_d=3, max_q=3, 
                         seasonal=True, m=12,
                         max_P=3, max_D=2, max_Q=3,
                         trace=True,
                         error_action='ignore',  
                         suppress_warnings=True, 
                         stepwise=True)

# summarize the model characteristics
print(model_fit.summary())</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Performing stepwise search to minimize aic
 ARIMA(2,0,2)(1,1,1)[12] intercept   : AIC=inf, Time=3.89 sec
 ARIMA(0,0,0)(0,1,0)[12] intercept   : AIC=3383.210, Time=0.02 sec
 ARIMA(1,0,0)(1,1,0)[12] intercept   : AIC=3351.655, Time=0.38 sec
 ARIMA(0,0,1)(0,1,1)[12] intercept   : AIC=3364.350, Time=1.09 sec
 ARIMA(0,0,0)(0,1,0)[12]             : AIC=3604.145, Time=0.02 sec
 ARIMA(1,0,0)(0,1,0)[12] intercept   : AIC=3349.908, Time=0.11 sec
 ARIMA(1,0,0)(0,1,1)[12] intercept   : AIC=3351.532, Time=0.29 sec
 ARIMA(1,0,0)(1,1,1)[12] intercept   : AIC=3353.520, Time=1.24 sec
 ARIMA(2,0,0)(0,1,0)[12] intercept   : AIC=3312.656, Time=0.10 sec
 ARIMA(2,0,0)(1,1,0)[12] intercept   : AIC=3314.483, Time=0.57 sec
 ARIMA(2,0,0)(0,1,1)[12] intercept   : AIC=3314.378, Time=0.30 sec
 ARIMA(2,0,0)(1,1,1)[12] intercept   : AIC=3305.552, Time=3.02 sec
 ARIMA(2,0,0)(2,1,1)[12] intercept   : AIC=3291.425, Time=4.19 sec
 ARIMA(2,0,0)(2,1,0)[12] intercept   : AIC=3306.914, Time=3.06 sec
 ARIMA(2,0,0)(3,1,1)[12] intercept   : AIC=3276.501, Time=4.67 sec
 ARIMA(2,0,0)(3,1,0)[12] intercept   : AIC=3282.240, Time=5.24 sec
 ARIMA(2,0,0)(3,1,2)[12] intercept   : AIC=inf, Time=7.39 sec
 ARIMA(2,0,0)(2,1,2)[12] intercept   : AIC=inf, Time=4.74 sec
 ARIMA(1,0,0)(3,1,1)[12] intercept   : AIC=3313.877, Time=5.17 sec
 ARIMA(3,0,0)(3,1,1)[12] intercept   : AIC=3246.820, Time=5.72 sec
 ARIMA(3,0,0)(2,1,1)[12] intercept   : AIC=3255.313, Time=5.33 sec
 ARIMA(3,0,0)(3,1,0)[12] intercept   : AIC=3249.998, Time=6.77 sec
 ARIMA(3,0,0)(3,1,2)[12] intercept   : AIC=inf, Time=8.39 sec
 ARIMA(3,0,0)(2,1,0)[12] intercept   : AIC=3259.938, Time=3.55 sec
...
===================================================================================

Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).</pre></div>



<p>Auto-ARIMA has determined that the best model is (3,0,0)(3,1,1). These results match the results from section 3, in which we manually performed differencing. </p>



<h3 class="wp-block-heading" id="h-step-5-simulate-the-time-series-using-in-sample-forecasting">Step #5 Simulate the Time Series using in-sample Forecasting</h3>



<p>Now that we have trained our model, we want to use it to simulate the entire time series. We will do this by calling the predict method in the sample function. The prediction will match the same period as the original time series with which we trained the model. Because the model predicts one step, the prediction results will naturally be close to the actual values.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Generate in-sample Predictions
# The parameter dynamic=False means that the model makes predictions upon the lagged values.
# This means that the model is trained until a point in the time-series and then tries to predict the next value.
pred = model_fit.predict_in_sample(dynamic=False) # works only with auto-arima
df_train['y_train_pred'] = pred

# Calculate the percentage difference
df_train['diff_percent'] = abs((df_train['x_train'] - pred) / df_train['x_train'])* 100

# Print the predicted time-series
fig, ax1 = plt.subplots(figsize=(16, 8))
plt.title(&quot;In Sample Sales Prediction&quot;, fontsize=14)
sns.lineplot(data=df_train[['x_train', 'y_train_pred']], linewidth=1.0)

# Print percentage prediction errors on a separate axis (ax2)
ax2 = ax1.twinx() 
ax2.set_ylabel('Prediction Errors in %', color='purple', fontsize=14)  
ax2.set_ylim([0, 50])
ax2.bar(height=df_train['diff_percent'][20:], x=df_train.index[20:], width=20, color='purple', label='absolute errors')
plt.legend()
plt.show()</pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="521" data-attachment-id="11758" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/image-6/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/12/image-6.png" data-orig-size="1620,825" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-6" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/12/image-6.png" src="https://www.relataly.com/wp-content/uploads/2022/12/image-6-1024x521.png" alt="arima forecast for us bear sales created in python" class="wp-image-11758" srcset="https://www.relataly.com/wp-content/uploads/2022/12/image-6.png 1024w, https://www.relataly.com/wp-content/uploads/2022/12/image-6.png 300w, https://www.relataly.com/wp-content/uploads/2022/12/image-6.png 768w, https://www.relataly.com/wp-content/uploads/2022/12/image-6.png 1536w, https://www.relataly.com/wp-content/uploads/2022/12/image-6.png 1620w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Next, we take a look at the prediction errors.</p>



<h3 class="wp-block-heading" id="h-step-6-generate-and-visualize-a-sales-forecast">Step #6 Generate and Visualize a Sales Forecast</h3>



<p>Now that we have trained an optimal model, we are ready to generate a sales forecast. First, we specify the number of periods that we want to predict. In addition, we create an index from the number of predictions adjacent to the original time series and continue it (prediction_index).</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Generate prediction for n periods, 
# Predictions start from the last date of the training data
test_pred = model_fit.predict(n_periods=pred_periods, dynamic=False)
df_test['y_test_pred'] = test_pred
df_union = pd.concat([df_train, df_test])
df_union.rename(columns={'beer':'y_test'}, inplace=True)

# Print the predicted time-series
fig, ax = plt.subplots(figsize=(16, 8))
plt.title(&quot;Test/Pred Comparison&quot;, fontsize=14)
sns.despine();
sns.lineplot(data=df_union[['y_train', 'y_train_pred', 'y_test', 'y_test_pred']], linewidth=1.0, dashes=False, palette='muted')
ax.set_xlim([df_union.index[150],df_union.index.max()])
plt.legend()
plt.show()</pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="539" data-attachment-id="8529" data-permalink="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/05/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1.png" data-orig-size="1566,825" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/05/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1.png" src="https://www.relataly.com/wp-content/uploads/2022/05/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1-1024x539.png" alt="time series forecast on us beer sales with arima Test Pred Comparison, python tutorial" class="wp-image-8529" srcset="https://www.relataly.com/wp-content/uploads/2022/05/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1.png 1024w, https://www.relataly.com/wp-content/uploads/2022/05/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1.png 300w, https://www.relataly.com/wp-content/uploads/2022/05/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1.png 768w, https://www.relataly.com/wp-content/uploads/2022/05/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1.png 1536w, https://www.relataly.com/wp-content/uploads/2022/05/arima-plot-seaborn-beer-sales-forecasting-python-test-predictions-1.png 1566w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>As shown above, our model&#8217;s forecast continues the seasonal pattern of the beer sales time series. On the one hand, this indicates that US beer sales will continue to rise and, on the other hand, that our model works just fine 🙂</p>



<h3 class="wp-block-heading" id="h-step-7-measure-the-performance-of-the-sales-forecasting-model">Step #7 Measure the Performance of the Sales Forecasting Model</h3>



<p>In this section, we will measure the performance of our ARIMA model. To learn more about this topic, check out <a href="https://www.relataly.com/regression-error-metrics-python/923/" target="_blank" rel="noreferrer noopener">this relataly article measuring regression performance</a>.</p>



<p>The previous section&#8217;s simulation chart shows a few outliers among the prediction errors. Therefore, we focus our analysis on the percentage errors. Two helpful metrics are the mean absolute error (MAPE) and the mean absolute percentage error (MDAPE).</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Mean Absolute Percentage Error (MAPE)
MAPE = np.mean((np.abs(np.subtract(df_test['y_test'], df_test['y_test_pred'])/ df_test['y_test']))) * 100
print(f'Mean Absolute Percentage Error (MAPE): {np.round(MAPE, 2)} %')

# Median Absolute Percentage Error (MDAPE)
MDAPE = np.median((np.abs(np.subtract(df_test['y_test'], df_test['y_test_pred'])/ df_test['y_test'])) ) * 100
print(f'Median Absolute Percentage Error (MDAPE): {np.round(MDAPE, 2)} %')</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Mean Absolute Percentage Error (MAPE): 3.94 %  Median Absolute Percentage Error (MDAPE): 3.49 %</pre></div>



<p>The percent errors show that our ARIMA model achieves a decent predictive performance.</p>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>This Python tutorial has shown how to use SARIMA for sales forecasting. Sales forecasting is important for businesses because it can help them to make informed decisions about production, inventory management, and staffing, among other things. By accurately forecasting sales, businesses can ensure that they have the right amount of product available to meet customer sales, avoid overproduction and excess inventory, and plan for future growth. The use cases presented were forecasting beer sales, and we have used arima to analyze seasonal sales data. </p>



<p>In the first part, we have learned how ARIMA works, what Stationarity is and how to check if a time series is stationary. In the second part, we developed an ARIMA model in Python to create a forecast for US beer sales. For this purpose, we created an in-sample forecast and used Auto-tARIMA to find the optimal parameters for our sales forecasting model.</p>



<p>If you have any questions or suggestions, please let me know in the comments, and I will do my best to answer. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"><div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="506" height="496" data-attachment-id="12603" data-permalink="https://www.relataly.com/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly2-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly2-min.png" data-orig-size="506,496" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Now that we have learned to use ARIMA to forecast beer sales, you really deserved yourself a beer. Cheers! Image created with Midjourney" data-image-description="&lt;p&gt;Now that we have learned to use ARIMA to forecast beer sales, you really deserved yourself a beer. Cheers! Image created with Midjourney&lt;/p&gt;
" data-image-caption="&lt;p&gt;Now that we have learned to use ARIMA to forecast beer sales, you really deserved yourself a beer. Cheers! Image created with Midjourney&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly2-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly2-min.png" alt="Now that we have learned to use ARIMA to forecast beer sales, you really deserved yourself a beer. Cheers! Image created with Midjourney" class="wp-image-12603" srcset="https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly2-min.png 506w, https://www.relataly.com/wp-content/uploads/2023/03/brewery-arima-beer-sales-forecasting-python-tutorial-machine-learning-relataly2-min.png 300w" sizes="(max-width: 506px) 100vw, 506px" /><figcaption class="wp-element-caption">Now that you have learned to use ARIMA to forecast beer sales, you really earned yourself a beer. Cheers! Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div></div>
</div>



<p></p>



<h2 class="wp-block-heading" id="h-sources-and-further-reading">Sources and Further Reading</h2>



<ol class="wp-block-list"><li><a href="https://amzn.to/3MyU6Tj" target="_blank" rel="noreferrer noopener">Charu C. Aggarwal (2018) Neural Networks and Deep Learning</a></li><li><a href="https://amzn.to/3yIQdWi" target="_blank" rel="noreferrer noopener">Jansen (2020) Machine Learning for Algorithmic Trading: Predictive models to extract signals from market and alternative data for systematic trading strategies with Python</a></li><li><a href="https://amzn.to/3S9Nfkl" target="_blank" rel="noreferrer noopener">Aurélien Géron (2019) Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems </a></li><li><a href="https://amzn.to/3EKidwE" target="_blank" rel="noreferrer noopener">David Forsyth (2019) Applied Machine Learning Springer</a></li><li><a href="https://amzn.to/3MAy8j5" target="_blank" rel="noreferrer noopener">Andriy Burkov (2020) Machine Learning Engineering</a></li></ol>



<p class="has-contrast-2-color has-base-3-background-color has-text-color has-background"><em>The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.</em></p>



<p>Want to learn more about time series analysis and prediction?<br>Check out these recent relataly tutorials:</p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/stock-market-prediction-using-a-recurrent-neural-network/122/" target="_blank" rel="noreferrer noopener">Stock Market Prediction &#8211; Building a&nbsp;Univariate Model using Keras Recurrent Neural Networks in Python</a>.</li>



<li><a href="https://www.relataly.com/stock-market-prediction-with-multivariate-time-series-in-python/1815/" target="_blank" rel="noreferrer noopener">Building Multivariate Time Series Models for Stock Market Prediction with Python</a></li>



<li><a href="https://www.relataly.com/multi-step-time-series-forecasting-a-step-by-step-guide/275/" target="_blank" rel="noreferrer noopener">Time Series Forecasting &#8211; Creating a Multi-Step Forecast in Python</a></li>



<li><a href="https://www.relataly.com/measuring-prediction-errors-in-time-series-forecasting/809/" target="_blank" rel="noreferrer noopener">Python Cheat Sheet: Measuring Prediction Errors in Time Series Forecasting</a></li>



<li><a href="https://www.relataly.com/evaluating-time-series-forecasting-models/923/" target="_blank" rel="noreferrer noopener">Evaluate Time Series Forecasting Models with Python</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/">Forecasting Beer Sales with ARIMA in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/forecasting-beer-sales-with-arima-in-python/2884/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2884</post-id>	</item>
	</channel>
</rss>
