<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sanjay Dorairaj on Medium]]></title>
        <description><![CDATA[Stories by Sanjay Dorairaj on Medium]]></description>
        <link>https://medium.com/@postsanjay?source=rss-5e00198e8f63------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vyQLGh9IEk5wGOc2.</url>
            <title>Stories by Sanjay Dorairaj on Medium</title>
            <link>https://medium.com/@postsanjay?source=rss-5e00198e8f63------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:31:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@postsanjay/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The ABCs of starting a Generative AI Business]]></title>
            <link>https://medium.com/@postsanjay/the-abcs-of-starting-a-generative-ai-business-251c0b4a1035?source=rss-5e00198e8f63------2</link>
            <guid isPermaLink="false">https://medium.com/p/251c0b4a1035</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[generative-ai-market]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <dc:creator><![CDATA[Sanjay Dorairaj]]></dc:creator>
            <pubDate>Tue, 28 May 2024 16:39:15 GMT</pubDate>
            <atom:updated>2024-05-28T16:39:15.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*53vkcZ3nzLR-Q6wD" /></figure><p>Generative AI is rapidly democratizing entrepreneurship by making it feasible for individuals to take an idea to market rapidly. This is projected to lead to an explosion of new entrepreneurs, transitioning us from a builder economy, where software developers were a premium, to an idea economy, where the ease of going from idea to product will place a high premium on ideas themselves. As software agents and similar innovations dramatically accelerate time to market, they also bring more capability into the hands of individuals. Where entire teams were previously required to develop and launch production-ready products, this can now be achieved by a single person or a handful of individuals. Eventually, everything but the idea itself will become undifferentiated heavy lifting. The most valuable skills, besides coming up with the original idea, will be entrepreneurial abilities to build a business, successfully take a product to market, and continue to innovate and sustain the product over time.</p><p><strong>TLDR;</strong></p><p>This is an in-depth article that uses a real-life product to demonstrate how to build and launch your Generative AI product in the market. Read the TLDR below if you are looking for a quick summary.</p><p><em>Generative AI is rapidly democratizing entrepreneurship, transitioning us from a builder economy to an idea economy where the ease of transforming concepts into products will place a premium on innovative ideas themselves. This phenomenon is projected to spark an explosion of new entrepreneurs as AI dramatically accelerates product development timelines and brings more capabilities into the hands of individuals.</em></p><p><em>While starting a business was traditionally seen as difficult, Generative AI makes it essential for everyone to develop entrepreneurial skills to identify pain points, build solutions, and potentially take those products to market. Fully production-ready applications serving millions can now be created within two weeks, with that timeline continuing to shrink. As ideas flood the market, it becomes crucial to discern good ideas that solve real problems from bad ones.</em></p><p><em>This article walks through the traditional product launch lifecycle — establishing the business, ideation, development, go-to-market, sales/revenue — demonstrating how Generative AI compresses timelines using a case study: </em><a href="https://emspal.com/"><em>EMS Pal</em></a><em>, a chat app providing EMTs natural language access to medical protocols, that was built and launched as a production-ready product in two weeks. Key steps covered include building an initial proof of concept, productionizing and scaling it on AWS, data collection, analytics, marketing/sales strategies, monetization, funding, legal/regulatory compliance, and proper business establishment.</em></p><p><em>While challenges like product duplication, market fit issues, and legal hurdles exist, the potential rewards of this new AI-powered era are immense. By following the roadmap outlined, aspiring entrepreneurs can navigate this landscape, seize opportunities, and successfully launch Generative AI businesses.</em></p><p><strong>The Emergence of AI-Powered Entrepreneurship</strong></p><p>You may have been told that starting a business is not for everyone. However, the accelerating trends in AI will soon make it essential for everyone to ramp up their entrepreneurial skills. The ease of building new products will enable individuals to identify pain points, quickly build solutions to address those pain points, and take them to market. The traditional friction between ideation and implementation is expected to be significantly reduced by the capabilities AI brings. Fully production-ready products capable of serving millions of customers can now be created in a few weeks, and this timeframe will continue to shrink. As new products flood the market, it will be essential to have the skills to quickly build out the product, register your business, take the product to market and monetize on its success . In other words, developing an entrepreneurial mindset and taking products to market will become increasingly important for everyone.</p><p><strong>The Traditional Product Launch Lifecycle</strong></p><p>Traditionally, product launches have typically followed this lifecycle:</p><ol><li>Establishing the business as a legal entity</li><li>Idea generation</li><li>Product development</li><li>Go-to-market strategy</li><li>Sales and revenue generation</li></ol><p>Embedded within this framework are other activities such as funding the business, accounting, hiring, meeting regulatory requirements, monitoring and managing the business. This framework does not fundamentally change with Generative AI, except that the product development timelines become significantly compressed. In this article, we will walk through each of these steps, illustrating the process using a case study of a new Generative AI application called EMS Pal.</p><p><strong>EMS Pal: A Case Study in Generative AI Entrepreneurship</strong></p><p>As a certified EMT passionate about the field, I recently noticed a pain point during my training. EMTs must have a thorough knowledge of protocols for up to five different counties, each with its unique variations. While the general basics of EMT practice are the same, some counties differ in the scope of practice for EMTs. For example, Alameda County may allow EMTs to administer epinephrine, while Santa Clara County does not. Understanding these differences can be challenging, especially for new EMTs, and having a handy co-pilot to assist in such situations would be invaluable. This seemed like a classic use case for Generative AI. While applications exist that allow users to look up protocols, they often involve searching and scanning to find the desired information. Enabling EMTs to speak or type in natural language and request help on a specific EMS protocol would be highly valuable. Since Generative AI and Retrieval-Augmented Generation (RAG) models naturally support this capability, I decided to create an application that allows EMTs to chat with their local area protocols.</p><p>Initial Proof of Concept (POC): To build the initial POC quickly, I stumbled upon Streamlit, a Python backend (similar to Flask and Fast API) originally created for rendering data and AI/ML visualizations but increasingly being used for streaming applications. I had never used it before but decided to leverage it because first, it was easy to get it running, and, second, its architecture and ecosystem has the basic elements to support multi-turn chat conversations and distributed web services, with stable integrations with LlamaIndex, OpenAI, Pinecone, Neo4j, and other Generative AI platform elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pKnUNqvkaBz-GEHy" /></figure><p>After implementing basic chat support, I introduced RAG to augment the prompt with relevant information from the protocol documentation. One hard requirement I had imposed was to provide source references alongside responses. To achieve this, I split the document into pages and then into chunks, adding metadata to each chunk that included the page number. I made the original protocol documentation available publicly through a read-only s3 bucket so it could be accessed by the application. In my first iteration I used the local in-memory LlamaIndex VectorStore for the embeddings. Once the basic RAG setup was in place, I could chat with the LLM and retrieve and render the corresponding source references. I deployed the POC on an EC2 instance within AWS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E8BN5Y1Pi6hzHm9Z" /></figure><p>Productionizing: As more users started using EMS Pal, the single EC2 instance could not scale. Since I was working with a Python backend, the logical step was to move the code into a Docker image and push it to AWS Fargate. I set up an Application Load Balancer that pointed to my Fargate cluster, configuring it to auto-scale in response to user requests. Between the ALB, Fargate, and Streamlit, I have not had issues with unavailability, despite one-hour request counts peaking at 60K and one-hour active connections peaking at over 14K.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LFGn4sJZT1lcnM8n" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8FCRajrfE6hjMmN_" /></figure><p>My initial POC had all the protocol documents stored locally within the EC2 instance. The combination of the local in-memory vector store and local storage introduced large startup latencies. The next step was to move the vector store to a remote Vector DB. I chose Pinecone since it was easy to integrate with and supported desired features like metadata injection. To enable logical separation between documents for different local areas, like Santa Clara and Alameda County, I placed each set of local area documents in a separate namespace. Using Pinecone namespaces allowed me to scale cost-effectively without needing a separate Pinecone index and additional cost for this isolation. At last check, each Pinecone index supported up to 10K namespaces, and since there are fewer than 1,000 local areas, this put me in a comfortable position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*TzV1ikLFnPjcerGr" /></figure><p>The final step in the productionizing process was setting up the RAG pipeline. Each document pertaining to a particular local area or county needs to go through a pre-processing step before being added to the Pinecone index. The pipeline allowed me to upload county-specific documents as a zip file and trigger a lambda to perform the processing — unpack docs, paginate, add chunks and metadata to the corresponding Pinecone index. This allowed me to drop new local area protocols into S3. The frontend would make calls to Pinecone to fetch the namespaces and display them in a drop-down list for the user to make their selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MI3uCB9NLtwSjKlt" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5N9mmfD_zNgQfWE7" /></figure><p><strong>Note</strong>:</p><ol><li><em>Support for Knowledge Graphs:</em> While the current mechanism has been working well, I am exploring migrating to using a knowledge graph to allow the LLM to understand context across various pages of the document and hierarchical structures inside tables. The current implementation treats everything as text and does not capture information in document hierarchies. I am evaluating Neo4j as a method for adding this support since it has good integration with LlamaIndex.</li><li><em>Need for an Evaluation Framework:</em> As I switch between different RAG architectures (Vector store versus Knowledge Graphs) or tweak an existing RAG architecture, I need to know how these changes impact the performance of my RAG. To address this, I am integrating my application with RAGAS, a powerful yet simple-to-use RAG evaluation framework.</li><li><em>Migrating to React: I</em> am also considering migrating the frontend from Streamlit to React/Lambda since a majority of my users are mobile users and as of this moment Streamlit is not very mobile friendly with several libraries erroring out and not loading on my IPhone.</li></ol><p><strong>Data Collection:</strong></p><p>EMS protocol information is not easy to obtain. The first challenge is finding all the local areas in the US, which is not well-documented. The second step is to find the corresponding protocols. I found a website,<a href="https://www.acidremap.com/"> https://www.acidremap.com/</a>, that listed several local areas and used that data as the collection of local areas. While some local areas have all their data in a single PDF file, I often needed to scrape websites to gather the protocol data. I built a simple parser using JupyterNB to perform multi-level scraping of protocol websites to download the available data. With these tools, I have been able to download over 100 of the most populated local area protocols and will continue until I have obtained them all.</p><p><strong>Analytics:</strong></p><p>As the application starts getting used, it is essential to understand user adoption and the application’s performance.</p><p><em>Performance Metrics: </em>The application monitoring support on AWS Fargate and the Application Load Balancer is outstanding by default, which allowed me to quickly understand how the application was performing. I did run into an issue during troubleshooting when I needed to look at Lambda logs, so I enabled that through <a href="https://docs.aws.amazon.com/AmazonCloudWatch">Amazon CloudWatch</a>. I also enabled log groups for my Lambda function to facilitate further troubleshooting using CloudWatch. The typical performance metrics to monitor are ALB and Cluster availability, latency, and the cluster CPU and memory performance and load.</p><p><em>Business Metrics: F</em>or business metrics, I integrated the application with Google Analytics. To do this, I went to <a href="http://analytics.google.com/">analytics.google.com</a>, created an application, and used the provided code within my app. This allowed me to analyze the application’s usage. The ALB and Cluster metrics also provided valuable information about business metrics.</p><p><strong>Marketing:</strong></p><p>Once you have a product, the next step is to get it in front of users. There are several ways to achieve this:</p><ol><li><em>Leverage your immediate networks: T</em>he easiest way is when you have a willing set of users in close proximity, such as at your workplace, among friends, or within your social network. You can reach them by simply sharing your product or creating a post to spread the word. In my case, I created a LinkedIn post to raise awareness. While EMTs are not generally on LinkedIn, I could still connect with local EMS service providers, including ambulance companies and the Santa Clara Department of Health, to explore further opportunities and use cases related to the product.</li><li><em>Find where your users congregate: I</em>n my case, after some research, I found that most EMS professionals hang out on popular <a href="https://www.reddit.com/">Reddit</a> channels like /ems, /newEmt, and others. I joined Reddit and created posts to announce the availability of EMS Pal. The initial reaction to the application was great, with several users requesting me to add their local areas as well.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9uenaFAgI30zL81o" /></figure><p><em>Target your audience at scale: </em>While I was gaining some traction on Reddit, I wanted to let more people know about the application. Most social platforms have their ad platforms, including Reddit. Since my end-users were mostly on Reddit, the next step for me was to leverage <a href="https://ads.reddit.com/">Reddit’s ad campaigns</a> to spread the word even further. I started a campaign to promote EMS Pal on Reddit, ran it over a few days, and achieved a CTR of about 0.5%. If I discovered an issue with the application, I would intermittently pause the ad campaign, make tweaks, and run it again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vds-o56X5j-l-_x_" /></figure><p><em>Seek out influencers: </em>Influencer marketing is gaining traction and can be a cost-effective way to grow your product’s reach. In the world of EMS, there are many influencers with tens of thousands of dedicated followers. You can reach them through influencer marketing agencies or try to contact them directly through their Facebook or social media pages. In my case, I reached out to a few influencers and am waiting to take the conversation with them to the next step.</p><p><em>Establish social media pages: </em>Finally, you can draw attention to your application by setting up your social media platform pages. Facebook and Instagram are still the most popular, although you will need to look at your specific user base to understand the right social platform to invest in. For EMS Pal, popular haunts for EMS users were Facebook, Reddit, TikTok, and Instagram. Remember that social media pages are a function of the number of followers you have and are a great way to nurture your users but not necessarily a great way to drive awareness. Few products can obtain a large follower base on social media, and a lot depends on the type of information you share and the engagement it generates. However, for users interested in keeping track of what you are doing, they are a great way to communicate.</p><p>As part of your marketing initiatives, you may want to choose a Customer Relationship Management (CRM) tool like <a href="https://www.hubspot.com/products/crm">Hubspot</a>, <a href="https://www.salesforce.com/crm/">Salesforce</a>, or one of several cheaper alternatives, like <a href="https://www.zoho.com/crm/">Zoho</a> or <a href="https://app.convertkit.com/users/login">Convertkit</a>, to help you manage leads. The CRM allows you to track customer leads and continue to engage with them. Most of these CRM platforms have a free tier that will be sufficient for any initial work that you are trying to do.</p><p>It will be excellent if you can find your product-market fit with your first launch, but that is rarely the case. Several things could happen. One possibility is that there may be some initial interest in your product, but unless you add compelling new features, you may not be able to keep your users interested. Another problem you may encounter is that your product is believed to be generally useful, but you need to further segment the market to find your target audience. For example, if there already exists a popular EMS Protocol application (although not a Generative AI-powered one), there will still be significant inertia for an organization to move their EMS users to the new tool. Your product will need to cross a certain threshold of value creation to get users to adopt your tool. In this case, you may need to conduct market research to understand if there is a segment of the market not catered to by an existing tool that you can convert.</p><p><strong>Sales, Revenue, and Funding:</strong></p><p>While your initial intention in launching your application may be to help your customers, eventually, you will need to find a funding source to sustain your product. This could be in the form of your investment, seeking external investment, or charging your users a fee for using the product. The third option is the most difficult to obtain initially, as you will likely need to go through a phase where you fund the build-out of your product and have no way to generate revenue during this time.</p><p>If you are seeking funding, you will need to articulate the revenue-generating or customer-creation value of your product, typically in the form of a pitch deck. Early on, you are typically talking to friends and family for investments, whereas later on, you seek angel investors and then move on to Series X funding. Remember that you will probably be required to put up some of your own initial money to show your commitment to early investors and that you have some skin in the game.</p><p>As you reach the point where you are seeing revenue-generating potential, you will need to choose a strategy for signing up users and monetizing on your application. Popular models for Generative AI products are fixed and variable subscription fees. The reason for the variable subscription fees is that the cost associated with using LLMs is also variable, meaning as users consume more LLM requests, your charges go up. In this case, you could create a new high subscription tier, limit the number of transactions a user can execute, or allow them to purchase additional credits beyond the limits of their currently subscribed tier.</p><p>Implementing support for charging your customers has been significantly simplified by payment platforms like Stripe and Paypal, which can handle the entire subscription lifecycle of your users through simple APIs.</p><p><strong>Legal Considerations</strong></p><p>When developing Generative AI products, particularly in sensitive domains like healthcare or legal, it is crucial to consider potential legal implications and liabilities. In the case of EMS Pal, which provides medical protocol information, it was essential to clearly articulate that the chat assistant could provide factually incorrect information and that users should refer to official protocol documents as the source of truth.</p><p>To address this, I implemented a terms and conditions agreement that users must accept before using the application. This agreement explicitly stated that the information provided by the chat assistant should not be considered authoritative or a substitute for official medical protocols. It also included a disclaimer that the user assumes all risks associated with relying on the information provided by the application.</p><p>In general, when building Generative AI products, it is advisable to consult with legal experts to ensure compliance with relevant laws and regulations. Some key considerations include:</p><ol><li><em>Data Privacy and Security: </em>If your application processes or stores user data, you must comply with data privacy laws such as GDPR and CCPA. Implement robust security measures to protect user data and ensure transparency about your data collection and usage practices.</li><li><em>Intellectual Property Rights:</em> Ensure that you have the necessary rights to use any third-party data, models, or components in your application. This may involve obtaining licenses or seeking permission from the rightful owners.</li><li><em>Liability and Disclaimers: </em>As demonstrated in the EMS Pal case, it is essential to include clear disclaimers and limitations of liability in your terms of service or end-user license agreement. This can help protect you from potential legal claims arising from the use or misuse of your application.</li><li><em>Regulatory Compliance: </em>Depending on your application’s domain and functionality, you may need to comply with industry-specific regulations. For example, applications in the healthcare or financial sectors may be subject to stringent regulatory requirements.</li><li><em>Ethical Considerations:</em> As Generative AI technology continues to evolve, ethical concerns such as bias, transparency, and accountability become increasingly important. Consider implementing ethical guidelines and principles to ensure the responsible development and use of your Generative AI product.</li></ol><p><strong>Establishing a Business</strong></p><p>When you decide to start monetizing your product, you will need to ensure that you are established as a proper legal entity from the government’s perspective and pay taxes to operate as such. There are generally a few options to consider when registering your business. You can register it as a C-Corp, which is the form that venture capitalists prefer, establish it as a single-owner or partner LLC, or create a non-profit organization. My recommendation would be to start as a single-owner LLC. It allows you to write off your business expenses on your personal taxes, as opposed to carrying your expenses into a C-Corp, where you may never be able to write them off. My recommendation would also to start your register your business as a generic automation or productivity enhancement platform so that the same LLC or C-Corp can scale to new products that you develop, or you may end up having to update your mission as your product portfolio grows. Note that there are both federal and state carrying costs to maintain your business. You will need to have a registered agent in the state where you incorporate and file regular forms and pay your taxes to both federal and state tax authorities.</p><p><strong>Conclusion</strong></p><p>The rise of Generative AI has ushered in a new era of entrepreneurship, empowering individuals to rapidly turn ideas into viable products and businesses. This article provided a comprehensive guide, leveraging the EMS Pal case study to illustrate the steps from ideation and development to marketing, sales, funding, and legal establishment. While challenges exist, the potential rewards are immense as barriers to entry are lowered. However, this is merely the beginning — as Generative AI continues advancing, numerous other aspects will emerge requiring further exploration around ethical implications, new frameworks and best practices, impacts across industries, and novel business models and revenue streams. This article aimed to provide practical guidance, but constant adaptation and learning will be key for entrepreneurs to thrive in this transformative AI-powered landscape.</p><p><strong>Frequently Asked Questions?</strong></p><p>What is Generative AI? Generative AI refers to AI systems that can generate new data, such as text, images, audio, or code, based on the training data they’ve been exposed to.</p><p>What is an LLM? LLM stands for Large Language Model, which refers to advanced AI models that can generate human-like text based on the input data they’ve been trained on. LLMs have since evolved to understand and generate images,audio, video and other content types. Examples include GPT-4, Claude, Mistral, PaLM, and Llama3.</p><p>What is RAG? RAG stands for Retrieval-Augmented Generation, which is a technique that combines traditional language models with information retrieval systems. RAG models can generate text while also retrieving and incorporating relevant information from external data sources.</p><p>What is a Vector Store? A Vector Store is a database optimized for storing and querying high-dimensional vector embeddings. It is often used in combination with LLMs to efficiently search and retrieve relevant information from large datasets. Pinecone is a type of vector store database.</p><p>What is a Knowledge Graph? A Knowledge Graph is a way of representing information in a graph structure, where entities (nodes) are connected by relationships (edges). Knowledge Graphs can help LLMs better understand the context and relationships within data. Neo4j is a type of graph database.</p><p>What is Pinecone? Pinecone is a managed vector database service that makes it easy to build and deploy applications that use vector embeddings, such as those generated by LLMs.</p><p>What is LlamaIndex? LlamaIndex is an open-source Python library that provides a framework for building Retrieval-Augmented Generation (RAG) systems. It simplifies the process of indexing, querying, and integrating external data sources with LLMs.</p><p>What is RAGAS? RAGAS (Retrieval-Augmented Generation Evaluation Suite) is an open-source framework for evaluating and benchmarking the performance of RAG systems. It provides a standardized way to measure the accuracy, relevance, and coherence of RAG outputs.</p><p>What is a Docker Image? A Docker Image is a lightweight, standalone, executable package that includes everything needed to run a piece of software, including code, runtime, system tools, and libraries. Docker Images are used to package and deploy applications consistently across different environments.</p><p>What is AWS Fargate? AWS Fargate is a serverless compute engine for containers that works with both Amazon Elastic Kubernetes Service (EKS) and Amazon Elastic Container Service (ECS). It allows you to run containers without having to manage servers or clusters, making it easier to deploy and scale containerized applications.</p><p>You can also find this article <a href="https://www.linkedin.com/pulse/abcs-launching-your-generative-ai-business-aws-sanjay-dorairaj-5h2kc/?trackingId=7fWRncP6Tv6XGF9m1WBkIQ%3D%3D">here on LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=251c0b4a1035" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COVID-19 Virus — Investigating factors impacting its spread]]></title>
            <link>https://medium.com/@postsanjay/covid-19-virus-investigating-factors-impacting-its-spread-42aea8d3a748?source=rss-5e00198e8f63------2</link>
            <guid isPermaLink="false">https://medium.com/p/42aea8d3a748</guid>
            <dc:creator><![CDATA[Sanjay Dorairaj]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 04:22:08 GMT</pubDate>
            <atom:updated>2020-03-30T04:29:59.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>COVID-19 Virus — Investigating factors impacting its spread</h3><p>The spring of 2020 has been dominated by the emergence of the COVID-19 virus. This has been characterized by the fast rate of spread, the rising number of casualties, significant damage to our economies and changes to our lifestyle.</p><p>Several folks have been looking for trends and patterns that might provide some clues to how the virus spreads. I was curious too and started to look at data on the virus and see if there were some correlations that could be uncovered that could provide some clues into factors that impacted the spread of the virus.</p><p>One correlation I wanted to explore was the association between the number of cases and temperature. With summer approaching in most parts of the world, I was hoping that perhaps there was a chance that warmer weather discourages the spread of the virus giving us some welcome relief soon.</p><p>The spreadsheet that I used is available for download here — <a href="https://docs.google.com/spreadsheets/d/1kycqyELGDLQB-mZU7q7u6zL88ISiPmVHaCzCqHCAW98/edit?usp=sharing">https://docs.google.com/spreadsheets/d/1kycqyELGDLQB-mZU7q7u6zL88ISiPmVHaCzCqHCAW98/edit?usp=sharing</a></p><h3><strong>Country temperatures and proliferation of the virus</strong></h3><p>Here is what I found with the limited data that I had gathered and the limited analysis that I concluded. None of this is conclusive and I am sure that a lot more can be done to cross-analyze the results especially with factors such as people-mobility, which is also a significant factor impacting the analysis. Another factor that I hand-waved was the disparity in temperatures across various cities within a country. The quick analysis I did simply picked the first popular city by alphabetical order in the temperature dataset I found. The references section shows the source of the data that I used to determine the total cases and temperatures.</p><p>Below is a scatter chart showing total cases versus temperature as of March 28th 2020</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dK1Sxg1NX37jIkUvdJ75UQ.png" /></figure><p>The initial chart shows that at a cutoff temperature of around 60 degrees Fahrenheit and higher , <strong>the number of cases are appear to be lower than at temperatures below 60 degrees.</strong></p><p>I re-drew the chart, this time by limiting the cut of total cases to around 20000 to get a more granular look at this association. I added some jitter to the temperature column to get a better sense of the spread.</p><p>This is what I found</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idk_GgeUCjS1RwvIUiDhMw.png" /></figure><p>Interestingly, there appear to be three visible segments. The first segment appeared to be solely countries with really lower temperatures, less than 4 degrees Fahrenheit. A second segment appears to be for countries with temperatures between 30 and 50 degrees Fahrenheit. The third segment, with the lowest number of cases starts at around 55 degrees Fahrenheit and higher temperatures. This appears to show a general trend in declining counts with temperatures.</p><p>A quick correlation analysis for just countries in the third segment shows a week negative correlation of 0.25 between temperature and total number of cases, which is not too good of an indicator of a clear association.</p><h3>Conclusion</h3><p>There is some comfort in the visual cues that generally seem to indicate fewer occurrences in places with warmer temperatures although none of it is conclusive. I am hoping that as more data streams from other countries and as I improve the quality of data used, perhaps, more definitive patterns will emerge. This was just a quick attempt to try to satisfy my curiosity and hopefully others can also take a look at the data and continue the investigation.</p><h3>References</h3><ol><li><a href="https://en.wikipedia.org/wiki/List_of_cities_by_average_temperature">https://en.wikipedia.org/wiki/List_of_cities_by_average_temperature</a></li><li><a href="https://en.wikipedia.org/wiki/List_of_countries_by_net_migration_rate">https://en.wikipedia.org/wiki/List_of_countries_by_net_migration_rate</a></li><li><a href="https://www.worldometers.info/coronavirus/">https://www.worldometers.info/coronavirus/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42aea8d3a748" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile Devices Display Terminology Explained — Resolution, Aspect Ratio, Screen Size, Pixel Ratio…]]></title>
            <link>https://medium.com/@postsanjay/mobile-devices-display-terminology-explained-resolution-aspect-ratio-screen-size-pixel-ratio-58b936c3975d?source=rss-5e00198e8f63------2</link>
            <guid isPermaLink="false">https://medium.com/p/58b936c3975d</guid>
            <category><![CDATA[display]]></category>
            <category><![CDATA[definition]]></category>
            <category><![CDATA[devices]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Sanjay Dorairaj]]></dc:creator>
            <pubDate>Sat, 15 Feb 2020 01:57:09 GMT</pubDate>
            <atom:updated>2020-02-15T01:57:09.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mobile Devices Display Terminology Explained — Resolution, Aspect Ratio, Screen Size, Pixel Ratio, PPI, Pixel Aspect Ratio and Device Pixel Ratio</h3><p>This write-up is to provide some clarifications related to various aspects of the Display component of Mobile Devices</p><p>Assume that the below table represents a mobile device screen, that has a resolution of 16 x 12 pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*ThXcv-LLEms5XkJQ" /></figure><p><strong>Resolution</strong> refers to the number of pixels along the width and the number of pixels along the height. So, 16 X 12 means there are 16 pixels horizontally and 12 pixels vertically. Altogether, there are 16X12 or 192 pixels on the device.</p><p><strong>Aspect Ratio</strong> is a function of resolution and can be referred to as the reduced/simplest resolution ratio. For example, since the resolution is 16X12 and the greatest common factor (GCF) of 16 and 12 is 4, the aspect ratio is 4:3</p><p><strong>Screen size </strong>measured in inches is the diagonal length of the screen, measured in inches. See figure.</p><p><strong>Pixels Per Inch (PPI) </strong>is a function of the Resolution and the Screen Size. It can be computed as below and is a measure of the pixel density.</p><p>For example, let’s take the example of the IPad 3rd generation device.</p><p>The screen size is 9.7 inches and resolution is 1536 X 2048.</p><ul><li>The number of pixels along the diagonal can be computed using the Pythogorus theorem i.e. sqrt(1536² + 2048²) and that is equal to 2560</li><li>PPI (pixels per inch) is the diagonal number of pixels divided by the screen size i.e. 2560/9.7 which is roughly equal to 256.</li></ul><p><strong>Pixel Aspect Ratio</strong> is different from aspect ratio and is a measure of the each pixel’s width to height. Devices sometimes have different pixel aspect ratio. This implies that even though applications program using a certain device resolution, the pixel aspect ratio can cause the resulting web page to not match the expected result.</p><p>For example, let’s assume a web page is programmed to work on a resolution of 2048 X 1536 pixels.<strong> If this web page is rendered on devices with different pixel aspect ratios 1 and 1.5, in the first case the image would be as expected but in the second case the web page would be stretched horizontal since every horizontal pixel is 1.5 times the pixel width for the first device</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*eX-cw7Wm76WJQrwC" /></figure><p>This is obviously undesirable behavior.</p><p><strong>Device Pixel ratio</strong> attempts to solve the issue with varying pixel aspect ratios. It allows for a programmer to not have to worry about the underlying pixel aspect ratio. This implies that the content that we render uses a standard pixel ratio across all device types. Internally, the device software is able to convert the pixel ratio into the device pixel ratio such that the content appears the same on all device types, regardless of differences in pixel ratio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*I3COMGAtLHALP5lJ" /></figure><p>While this may not make sense when using smaller pixel sizes, for larger images the effect will be noticeable and the user will not see any differences in the way the content in rendered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58b936c3975d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hidden Markov Models Simplified]]></title>
            <link>https://medium.com/@postsanjay/hidden-markov-models-simplified-c3f58728caab?source=rss-5e00198e8f63------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3f58728caab</guid>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Sanjay Dorairaj]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 05:37:46 GMT</pubDate>
            <atom:updated>2018-03-20T13:56:34.118Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sanjay Dorairaj</h4><h4>Adapted from HMM/NLP lectures by James Kunz et al @UC Berkeley</h4><h4>Overview</h4><p>Hidden Markov Models (HMMs) are a class of probabilistic graphical model that allow us to predict a sequence of unknown (hidden) variables from a set of observed variables. A simple example of an HMM is predicting the weather (hidden variable) based on the type of clothes that someone wears (observed). An HMM can be viewed as a Bayes Net unrolled through time with observations made at a sequence of time steps being used to predict the best sequence of hidden states.</p><p>The below diagram from Wikipedia shows an HMM and its transitions. The scenario is a room that contains urns <strong>X1, X2 and X3</strong>, each of which contains a known mix of balls, each ball labeled <strong>y1, y2, y3 and y4</strong>. A sequence of four balls is randomly drawn. In this particular case, <strong>the user observes a sequence of balls y1,y2,y3 and y4 and is attempting to discern the hidden state which is the right sequence of three urns that these four balls were pulled from.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*s4wQ8nTIb2122-9s.png" /></figure><p><strong>Figure 1: HMM hidden and observed states</strong></p><p><strong>Source: </strong><a href="https://en.wikipedia.org/wiki/Hidden_Markov_model#/media/File:HiddenMarkovModel.svg">https://en.wikipedia.org/wiki/Hidden_Markov_model#/media/File:HiddenMarkovModel.svg</a></p><p>In this post, we focus on the use of Hidden Markov Models for Parts of Speech (POS) diagram and walk through the intuition and the code for POS tagging using HMMs.</p><p>Complete source code for this post is available in Github at <a href="https://github.com/dorairajsanjay/hmm_tutorial">https://github.com/dorairajsanjay/hmm_tutorial</a></p><h3>Why Hidden, Markov Model?</h3><p>The reason it is called a Hidden Markov Model is because we are constructing an inference model based on the assumptions of a Markov process. The Markov process assumption is simply that the “future is independent of the past given the present”. In other words, assuming we know our present state, we do not need any other historical information to predict the future state.</p><p>To make this point clear, let us consider the scenario below where the weather, the hidden variable, can be hot, mild or cold and the observed variables are the type of clothing worn. The arrows represent transitions from a hidden state to another hidden state or from a hidden state to an observed variable.</p><p>Notice that, true to the Markov assumption, each state only depends on the previous state and not on any other prior states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*5TVny7wCY_3fOpPP.png" /></figure><p><strong>Figure 2: HMM State Transitions</strong></p><h3>Intuition behind HMMs</h3><p>HMMs are probabilistic models. They allow us to compute the joint probability of a set of hidden states given a set of observed states. The hidden states are also referred to as latent states. Once we know the joint probability of a sequence of hidden states, we determine the best possible sequence i.e. the sequence with the highest probability and choose that sequence as the best sequence of hidden states.</p><p>The ratio of hidden states to observed states is not necessarily 1 is to 1 as is evidenced by <strong>Figure 1</strong> above. The key idea is that one or more observations allow us to make an inference about a sequence of hidden states.</p><p>In order to compute the joint probability of a sequence of hidden states, we need to assemble three types of information.</p><p>Generally, the term “states” are used to refer to the hidden states and “observations” are used to refer to the observed states.</p><ol><li><strong>Transition data</strong> — the probability of transitioning to a new state conditioned on a present state.</li><li><strong>Emission data</strong> — the probability of transitioning to an observed state conditioned on a hidden state.</li><li><strong>Initial state information</strong> — the initial probability of transitioning to a hidden state. This can also be looked at as the prior probability.</li></ol><p>The above information can be computed directly from our training data. For example, in the case of our weather example in <strong>Figure 2</strong>, our training data would consist of the hidden state and observations for a number of days. We could build our transition matrices of transitions, emissions and initial state probabilities directly from this training data.</p><p>The example tables show a set of possible values that could be derived for the weather/clothing scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-fvkE-8eNDsdhb-z.png" /></figure><p><strong>Figure 3: HMM State Transitions — Weather Example</strong></p><p>Once this information is known, then the joint probability of the sequence, by the conditional probability chain rule and by Markov assumption, can be shown to be proportional to <strong>P(Y) </strong>below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*LKoUMyFT4R9jQRPb.png" /></figure><p><strong>Figure 4: HMM — Basic Math (HMM lectures)</strong></p><p>Note that as the number of observed states and hidden states gets large the computation gets more computationally intractable. If there are k possible values for each hidden sequence and we have a sequence length of n, there there are <strong>n^k</strong> total possible sequences that must be all scored and ranked in order to determine a winning candidate.</p><h3>Variations of the Hidden Markov Model — HMM EM</h3><p>The probability distributions of hidden states is not always known. In this case, we use Expectation Maximization (EM) models in order to determine hidden state distributions. A popular algorithm is the Baum-Welch algorithm (<a href="https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm">https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm</a>)</p><h3>Primer on Dynamic Programming and Summation Rules</h3><h3>Dynamic Programming</h3><p>As seen in the above sections on HMM, the computations become intractable as the sequence length and possible values of hidden states become large. It has been found that the problem of scoring an HMM sequence can be solved efficiently using dynamic programming, which is nothing but <strong>cached recursion.</strong></p><p>Shown below is an image of the recursive computation of a fibonnaci series</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*2BGyL3mJZLna2cOn.png" /></figure><p><strong>Figure 5: Fibonnacci Series — Tree</strong></p><p>One of the things that becomes obvious when looking at this picture is that several results (fib(x) values) are reused in the computation. By caching these results, we can greatly speed up our operations</p><h3>Fibonacci Computation without Dynamic Programming</h3><pre><strong>import</strong> <strong>time</strong></pre><pre><em># non-cached recursion</em><br><strong>def</strong> fib(x):<br>    <br>    <strong>if</strong> x == 0:<br>        <strong>return</strong> 0<br>    <strong>elif</strong> x == 1:<br>        <strong>return</strong> 1<br>    <strong>else</strong>:<br>        <strong>return</strong> fib(x-1) + fib(x-2)<br>    <br>startTime = time.time()</pre><pre><strong>print</strong>(&quot;<strong>%-14s</strong>:<strong>%d</strong>&quot; % (&quot;Result&quot;,fib(32)))<br><strong>print</strong>(&quot;<strong>%-14s</strong>:<strong>%.4f</strong> seconds&quot; % (&quot;Elapsed time&quot;,time.time() - startTime))</pre><pre>Result        :2178309<br>Elapsed time  :2.0062 seconds</pre><h3>Fibonacci Computation with Dynamic Programming</h3><pre>fib_cache = {}<br><strong>def</strong> fib(x):<br>    <br>    <strong>if</strong> fib_cache.get(x) != None:<br>        <strong>return</strong> fib_cache[x]<br>    <br>    result = None<br>    <strong>if</strong> x == 0:<br>        result = 0<br>    <strong>elif</strong> x == 1:<br>        result = 1<br>    <strong>else</strong>:<br>        result = fib(x-1) + fib(x-2)<br>        <br>    <strong>if</strong> fib_cache.get(x) == None:<br>        fib_cache[x] = result<br>        <br>    <strong>return</strong> result<br>    <br>startTime = time.time()</pre><pre><strong>print</strong>(&quot;<strong>%-14s</strong>:<strong>%d</strong>&quot; % (&quot;Result&quot;,fib(32)))<br><strong>print</strong>(&quot;<strong>%-14s</strong>:<strong>%.4f</strong> seconds&quot; % (&quot;Elapsed time&quot;,time.time() - startTime))</pre><pre>Result        :2178309<br>Elapsed time  :0.0007 seconds</pre><p>Notice the significant improvement in performance when we move to dynamic programming or cached recursion. We use this same idea when trying to score HMM sequences as well using an algorithm called the Forward-Backward algorithm which we will talk about later</p><h3>Manipulating Summations</h3><p>Here we look at an idea that will be leveraged in the forward backward algorithm. This is idea that double summations of terms can be rearrangeed as a product of each of the individual summation.</p><p>The example below explains this idea further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*i7XK2mkQZgsmolA-.png" /></figure><p><strong>Figure 6: HMM — Manipulation Summations</strong></p><p>The code below demonstrates this equivalency relationship</p><pre><em># double summations</em></pre><pre>x = [1,2,3]<br>y = [10,20,30]</pre><pre>total = 0<br><strong>for</strong> i <strong>in</strong> x:<br>    <strong>for</strong> j <strong>in</strong> y:<br>        <br>        total = total + i*j<br>        <br><strong>print</strong> total</pre><pre>360</pre><pre><em># product of individual summations</em></pre><pre>total = 0<br>total1 = 0<br><strong>for</strong> i <strong>in</strong> x:<br>    total1 = total1 + i<br>    <br>total2 = 0<br><strong>for</strong> j <strong>in</strong> y:<br>    total2 = total2 + j<br>    <br>total = total1*total2</pre><pre><strong>print</strong> total</pre><pre>360</pre><h3>Manipulating Maxes</h3><p>Similar to manipulating double summations, the max of a double maxation can be viewed as the product of each of the individual maxations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*sXOjfIZXAK0OwCU7.png" /></figure><p><strong>Figure — 7: HMM — Manipulation Maxes</strong></p><pre><em># double maxation</em></pre><pre>x = [1,2,3]<br>y = [10,20,30]</pre><pre><em># form 1</em><br>form1 = []<br><strong>for</strong> i <strong>in</strong> x:<br>    <strong>for</strong> j <strong>in</strong> y:<br>        <br>        form1.append(i*j)<br>        <br><strong>print</strong> &quot;form1:&quot;,form1<br><strong>print</strong> &quot;max(form1):&quot;,max(form1)</pre><pre>form1: [10, 20, 30, 20, 40, 60, 30, 60, 90]<br>max(form1): 90</pre><pre><em># product of individual maxations</em></pre><pre>form2_1 = []<br>form2_2 = []<br><strong>for</strong> i <strong>in</strong> x:<br>    form2_1.append(i)<br><strong>for</strong> j <strong>in</strong> y:<br>    form2_2.append(j)<br>    <br><strong>print</strong> &quot;<strong>\n</strong>form2_1&quot;,form2_1<br><strong>print</strong> &quot;form2_2&quot;,form2_2<br><strong>print</strong> &quot;max(form2_1) * max(form2_2)&quot;, max(form2_1) * max(form2_2)</pre><pre>form2_1 [1, 2, 3]<br>form2_2 [10, 20, 30]<br>max(form2_1) * max(form2_2) 90</pre><h3>Training an HMM</h3><p>In this section, we will consider the toy example below and use the information from that example to train our simple HMM model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WOEUK6_LfI4LvvEc.png" /></figure><p><strong>Figure — 8: HMM — Toy Example — Graph</strong></p><h3>State transition and emission probabilities</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/0*zl426F2RFjBKW9_K.png" /></figure><p><strong>Figure — 9: HMM — Toy Example — Transition Tables</strong></p><h3>Scoring a known sequence given observed text</h3><p>In this example, we score a known sequence given some text</p><p>Let us consider the below sequence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*8h37cUfOy_XI3SMo.png" /></figure><p><strong>Figure — 10: HMM — Toy Example — Graph</strong></p><p>The score for this sequence can be computed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*OPt-qolu7wpVgrq3.png" /></figure><p><strong>Figure — 11: HMM — Toy Example — Scoring Known Sequence</strong></p><p>The joint probability for our unknown sequence is therefore</p><p>P(A,B,A,Red,Green,Red) = [P(y_0=A) <em>P(x_0=Red/y_0=A)] </em>[P(y_1=B|y_0=A|)</p><p>P(x_1=Green/y_1=B)] <em>[P(y_2=A|y_1=B) </em>P(x_2=Red/y_2=A)]</p><p>=(1∗1)∗(1∗0.75)∗(1∗1)(1)(1)=(1∗1)∗(1∗0.75)∗(1∗1)</p><p>=0.75(2)(2)=0.75</p><h3>Scoring a set of sequences given some observations</h3><p>Assuming that we need to determine the parts of speech tags (hidden state) given some sentence (the observed values), we will need to first score every possible sequence of hidden states and then pick the best sequence to determine the parts of speech for this sentence.</p><p>We will score this using the below steps</p><ol><li>Generate the initial, transition and emission probability distribution from the sample data.</li><li>Generate a list of all unknown sequence</li><li>Score all unknown sequences and select the best sequence</li></ol><h3>Generate list of unknown sequences</h3><pre><em># given states - what are the possible combinations</em><br><em># total number of combinations is (number of possible states)^(sequence length)</em></pre><pre><strong>def</strong> generate_sequence(states,sequence_length):<br>    <br>    all_sequences = []<br>    nodes = []<br>    <br>    depth = sequence_length<br>    <br>    <strong>def</strong> gen_seq_recur(states,nodes,depth):</pre><pre>        <strong>if</strong> depth == 0:<br>            <em>#print nodes</em><br>            all_sequences.append(nodes)<br>        <strong>else</strong>:<br>            <strong>for</strong> state <strong>in</strong> states:<br>                temp_nodes = list(nodes)<br>                temp_nodes.append(state)<br>                gen_seq_recur(states,temp_nodes,depth-1)<br>    <br>    gen_seq_recur(states,[],depth)<br>                <br>    <strong>return</strong> all_sequences</pre><h3>Score all possible sequences</h3><pre><strong>def</strong> score_sequences(sequences,initial_probs,transition_probs,emission_probs,obs):<br>    <br>    best_score = -1<br>    best_sequence = None<br>    <br>    sequence_scores = []</pre><pre>    <strong>for</strong> seq <strong>in</strong> sequences:</pre><pre>        total_score = 1<br>        total_score_breakdown = []<br>        first = True<br>        <strong>for</strong> i <strong>in</strong> range(len(seq)):<br>            state_score = 1</pre><pre>            <em># compute transitition probability score</em><br>            <strong>if</strong> first == True:<br>                state_score *= initial_probs[seq[i]]</pre><pre>                <em># reset first flag</em><br>                first = False<br>            <strong>else</strong>:  <br>                state_score *= transition_probs[seq[i] + &quot;|&quot; + seq[i-1]]</pre><pre>            <em># add to emission probability score</em><br>            state_score *= emission_probs[obs[i] + &quot;|&quot; + seq[i]]</pre><pre>            <em># update the total score</em><br>            <em>#print state_score</em><br>            total_score_breakdown.append(state_score)<br>            total_score *= state_score<br>            <br>        sequence_scores.append(total_score)<br>        <br>    <strong>return</strong> sequence_scores</pre><pre><em># pretty printing our  distributions</em><br><strong>from</strong> <strong>sets</strong> <strong>import</strong> Set<br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>from</strong> <strong>tabulate</strong> <strong>import</strong> tabulate</pre><pre><strong>def</strong> pretty_print_probs(distribs):<br>    <br>    rows = Set()<br>    cols = Set()<br>    <strong>for</strong> val <strong>in</strong> distribs.keys():<br>        temp = val.split(&quot;|&quot;)<br>        rows.add(temp[0])<br>        cols.add(temp[1])<br>        <br>    rows = list(rows)<br>    cols = list(cols)</pre><pre>    df = []<br>    <strong>for</strong> i <strong>in</strong> range(len(rows)):<br>        temp = []<br>        <strong>for</strong> j <strong>in</strong> range(len(cols)):</pre><pre>            temp.append(distribs[rows[i]+&quot;|&quot;+cols[j]])<br>            <br>        df.append(temp)<br>        <br>    I = pd.Index(rows, name=&quot;rows&quot;)<br>    C = pd.Index(cols, name=&quot;cols&quot;)<br>    df = pd.DataFrame(data=df,index=I, columns=C)<br>    <br>    <strong>print</strong> tabulate(df, headers=&#39;keys&#39;, tablefmt=&#39;psql&#39;)</pre><pre><strong>def</strong> initializeSequences(_obs):<br>    <em># Generate list of sequences</em><br>    <br>    seqLen = len(_obs)</pre><pre>    seqs = generate_sequence(states,seqLen)</pre><pre>    <em># Score sequences</em><br>    seq_scores = score_sequences(seqs,initial_probs,transition_probs,emission_probs,obs)<br>    <br>    <strong>return</strong> (seqLen,seqs,seq_scores)</pre><h3>Compute the best sequence (Viterbi)</h3><p>Note that selecting the best scoring sequence is also known as the <strong>Viterbi</strong> score. The alternative approach is the <strong>Minimum Bayes Risk</strong> approach which selects the highest scoring position across all sequence scores.</p><h3>Example 1</h3><p>Let us consider the below graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*JNk2-2HK0wSFhn6i.png" /></figure><p><strong>Figure — 12: HMM — Toy Example — Scoring an Unknown Sequence</strong></p><pre><em># We can use a dictionary to capture our state transitions</em></pre><pre><em># set of hidden states</em><br>states = [&#39;A&#39;,&#39;B&#39;]</pre><pre><em># set of observations</em><br>obs = [&#39;Red&#39;,&#39;Green&#39;,&#39;Red&#39;]</pre><pre><em># initial state probability distribution (our priors)</em><br>initial_probs = {&#39;A&#39;:1.0,&#39;B&#39;:0.0}</pre><pre><em># transition probabilities</em><br>transition_probs = {&#39;A|A&#39;:0,&#39;A|B&#39;:1,&#39;B|A&#39;:1,&#39;B|B&#39;:0}</pre><pre><em># emission probabilities</em><br>emission_probs = {&#39;Red|A&#39;:1,&#39;Green|A&#39;:0,&#39;Red|B&#39;:0.25,&#39;Green|B&#39;:0.75}</pre><pre><em># Generate list of sequences</em><br>sequence_length,sequences,sequence_scores = initializeSequences(obs)</pre><pre><em># print results</em></pre><pre><strong>print</strong>(&quot;Initial Distributions&quot;)<br><strong>print</strong> initial_probs</pre><pre><strong>print</strong>(&quot;<strong>\n</strong>Transition Probabilities&quot;)<br>pretty_print_probs(transition_probs)</pre><pre><strong>print</strong>(&quot;<strong>\n</strong>Emission Probabilities&quot;)<br>pretty_print_probs(emission_probs)</pre><pre><strong>print</strong>(&quot;<strong>\n</strong>Scores&quot;)</pre><pre><em># Display sequence scores</em><br><strong>for</strong> i <strong>in</strong> range(len(sequences)):<br>    <strong>print</strong>(&quot;Sequence:<strong>%10s</strong>,Score:<strong>%0.4f</strong>&quot; % (sequences[i],sequence_scores[i]))</pre><pre>Initial Distributions<br>{&#39;A&#39;: 1.0, &#39;B&#39;: 0.0}</pre><pre>Transition Probabilities<br>+--------+-----+-----+<br>| rows   |   A |   B |<br>|--------+-----+-----|<br>| A      |   0 |   1 |<br>| B      |   1 |   0 |<br>+--------+-----+-----+</pre><pre>Emission Probabilities<br>+--------+-----+------+<br>| rows   |   A |    B |<br>|--------+-----+------|<br>| Green  |   0 | 0.75 |<br>| Red    |   1 | 0.25 |<br>+--------+-----+------+</pre><pre>Scores<br>Sequence:[&#39;A&#39;, &#39;A&#39;, &#39;A&#39;],Score:0.0000<br>Sequence:[&#39;A&#39;, &#39;A&#39;, &#39;B&#39;],Score:0.0000<br>Sequence:[&#39;A&#39;, &#39;B&#39;, &#39;A&#39;],Score:0.7500<br>Sequence:[&#39;A&#39;, &#39;B&#39;, &#39;B&#39;],Score:0.0000<br>Sequence:[&#39;B&#39;, &#39;A&#39;, &#39;A&#39;],Score:0.0000<br>Sequence:[&#39;B&#39;, &#39;A&#39;, &#39;B&#39;],Score:0.0000<br>Sequence:[&#39;B&#39;, &#39;B&#39;, &#39;A&#39;],Score:0.0000<br>Sequence:[&#39;B&#39;, &#39;B&#39;, &#39;B&#39;],Score:0.0000</pre><h3>Example 2 — Parts of Speech (POS)Tagging Example</h3><p>In the example below, we look at Parts of Speech tagging for a simple sentence. The sequence of words in the sentence are the observations and the Parts of Speech are the hidden states. Given a sentence, we are looking to predict the corresponding POS tags.</p><p>Let us consider the below graph, where the states are known and represent the POS tags and the red/green circles represent the observations or the sequence of words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*DwDHbkHP-C7Q8GwI.png" /></figure><p><strong>Figure — 13: HMM — Toy Example — Scoring an Unknown Sequence</strong></p><p>The code below initializes probability distributions for our priors, hidden states and observations. It then generates a set of all possible sequences for the hidden states. We will use this later to compute the score for each possible sequence.</p><pre><em># generate new sequences</em></pre><pre>states = [&#39;Noun&#39;,&#39;Verb&#39;,&#39;Determiner&#39;]<br>initial_probs = {&#39;Noun&#39;:0.9,&#39;Verb&#39;:0.05,&#39;Determiner&#39;:0.05}<br>transition_probs = {&#39;Noun|Noun&#39;:0.1,&#39;Noun|Verb&#39;:0.1,&#39;Noun|Determiner&#39;:0.8,<br>                    &#39;Verb|Noun&#39;:0.8,&#39;Verb|Verb&#39;:0.1,&#39;Verb|Determiner&#39;:0.1,<br>                    &#39;Determiner|Noun&#39;:0.1,&#39;Determiner|Verb&#39;:0.8,&#39;Determiner|Determiner&#39;:0.1}<br>emission_probs = {&#39;Bob|Noun&#39;:0.9,&#39;ate|Noun&#39;:0.05,&#39;the|Noun&#39;:0.05,&#39;fruit|Noun&#39;:0.9,\<br>                  &#39;Bob|Verb&#39;:0.05,&#39;ate|Verb&#39;:0.9,&#39;the|Verb&#39;:0.05,&#39;fruit|Verb&#39;:0.05,\<br>                  &#39;Bob|Determiner&#39;:0.05,&#39;ate|Determiner&#39;:0.05,&#39;the|Determiner&#39;:0.9,&#39;fruit|Determiner&#39;:0.05}</pre><pre><strong>print</strong>(&quot;Initial Distributions&quot;)<br><strong>print</strong> initial_probs</pre><pre><strong>print</strong>(&quot;<strong>\n</strong>Transition Probabilities&quot;)<br>pretty_print_probs(transition_probs)</pre><pre><strong>print</strong>(&quot;<strong>\n</strong>Emission Probabilities&quot;)<br>pretty_print_probs(emission_probs)</pre><pre>Initial Distributions<br>{&#39;Verb&#39;: 0.05, &#39;Noun&#39;: 0.9, &#39;Determiner&#39;: 0.05}</pre><pre>Transition Probabilities<br>+------------+--------+--------+--------------+<br>| rows       |   Verb |   Noun |   Determiner |<br>|------------+--------+--------+--------------|<br>| Verb       |    0.1 |    0.8 |          0.1 |<br>| Noun       |    0.1 |    0.1 |          0.8 |<br>| Determiner |    0.8 |    0.1 |          0.1 |<br>+------------+--------+--------+--------------+</pre><pre>Emission Probabilities<br>+--------+--------+--------+--------------+<br>| rows   |   Verb |   Noun |   Determiner |<br>|--------+--------+--------+--------------|<br>| Bob    |   0.05 |   0.9  |         0.05 |<br>| fruit  |   0.05 |   0.9  |         0.05 |<br>| the    |   0.05 |   0.05 |         0.9  |<br>| ate    |   0.9  |   0.05 |         0.05 |<br>+--------+--------+--------+--------------+</pre><pre>obs = [&#39;Bob&#39;,&#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;]</pre><pre><em># print results</em><br><strong>print</strong>(&quot;<strong>\n</strong>Scores&quot;)</pre><pre><em># Generate list of sequences</em><br>sequence_length,sequences,sequence_scores = initializeSequences(obs)</pre><pre><em># Display sequence scores</em><br><strong>for</strong> i <strong>in</strong> range(len(sequences)):<br>    <strong>print</strong>(&quot;Sequence:<strong>%-60s</strong> Score:<strong>%0.6f</strong>&quot; % (sequences[i],sequence_scores[i]))<br>    <br><em># Display the winning score</em><br><strong>print</strong>(&quot;<strong>\n</strong> Best Sequence&quot;)<br><strong>print</strong>(sequences[sequence_scores.index(max(sequence_scores))],max(sequence_scores))</pre><pre>Scores<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                             Score:0.000002<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                             Score:0.000001<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]                       Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                             Score:0.000015<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                             Score:0.000001<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]                       Score:0.000006<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]                       Score:0.000262<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]                       Score:0.000002<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]                 Score:0.000002<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                             Score:0.000262<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                             Score:0.000117<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]                       Score:0.000015<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                             Score:0.000262<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                             Score:0.000015<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]                       Score:0.000117<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]                       Score:0.302331<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]                       Score:0.002100<br>Sequence:[&#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]                 Score:0.002100<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                       Score:0.000015<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                       Score:0.000006<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]                 Score:0.000001<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                       Score:0.000002<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                       Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]                 Score:0.000001<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]                 Score:0.000262<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]                 Score:0.000002<br>Sequence:[&#39;Noun&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]           Score:0.000002<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                             Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                             Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                             Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                             Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]                       Score:0.000001<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]                 Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                             Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                             Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                             Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                             Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]                       Score:0.000117<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]                       Score:0.000001<br>Sequence:[&#39;Verb&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]                 Score:0.000001<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]                 Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                       Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]                 Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]                 Score:0.000006<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]                 Score:0.000000<br>Sequence:[&#39;Verb&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]           Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                       Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                       Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                       Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                       Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]                 Score:0.000006<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]           Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                       Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                       Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                       Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                       Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]                 Score:0.000117<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]                 Score:0.000001<br>Sequence:[&#39;Determiner&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]           Score:0.000001<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Noun&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Verb&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Determiner&#39;]           Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Noun&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Verb&#39;]                 Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Verb&#39;, &#39;Determiner&#39;]           Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Noun&#39;]           Score:0.000001<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Verb&#39;]           Score:0.000000<br>Sequence:[&#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;]     Score:0.000000</pre><pre> Best Sequence<br>([&#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;], 0.30233088000000014)</pre><h3>Computing the Minimum Bayes Risk (MBR) Score</h3><p>Here, we try to find out the best possible value for a particular y location location where y represents our hidden states starting from y=0,1…n-1, where n is the sequence length</p><p>For example, if we need to first pick the position we are interested in, let’s say we are in the second position of the hidden sequence i.e. y1. We examine the set of sequences and their scores, only this time, we group sequences by possible values of y1 and compute the total scores within each group. The group with the highest score is the forward/backward score</p><p>This is demonstrated in the code block below</p><pre><em># initialize the observations</em><br>obs = [&#39;Bob&#39;,&#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;]<br>obs = [&#39;Bob&#39;,&#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;Bob&#39;,&#39;ate&#39;,&#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;]</pre><pre><em>## recompute sequences and sequence scores</em><br>sequence_length,sequences,sequence_scores = initializeSequences(obs)</pre><pre><em>## compute MBR for a particular position</em><br>mbr_index = 4 <em># MBR 0-based</em></pre><pre>fb_scores = {}</pre><pre><em># display sequence scores</em><br><strong>for</strong> i <strong>in</strong> range(len(sequences)):<br>    <br>    <strong>if</strong> fb_scores.get(sequences[i][mbr_index]) == None:<br>        fb_scores[sequences[i][mbr_index]] = sequence_scores[i]<br>    <strong>else</strong>:<br>        fb_scores[sequences[i][mbr_index]] += sequence_scores[i]<br>        <br><strong>print</strong> &quot;Minimum Bayes Risk Scores for :&quot;<br><strong>for</strong> key <strong>in</strong> fb_scores:<br>    <strong>print</strong>(&quot;<strong>%-20s</strong> <strong>%0.8f</strong>&quot; % (key,fb_scores[key]))<br>    <br>best_fb_score = max(fb_scores.values())<br>best_y = [key <strong>for</strong> (key,value) <strong>in</strong> fb_scores.items() <strong>if</strong> value == best_fb_score]<br><strong>print</strong> &quot;<strong>\n</strong>Best Score:<strong>%0.8f</strong>, <strong>\n</strong>State Index:<strong>%d</strong> <strong>\n</strong>Best y state:<strong>%s</strong>&quot; % (best_fb_score,mbr_index,best_y )</pre><pre>Minimum Bayes Risk Scores for :<br>Verb                 0.00001816<br>Noun                 0.00000108<br>Determiner           0.00008688</pre><pre>Best Score:0.00008688, <br>State Index:4 <br>Best y state:[&#39;Determiner&#39;]</pre><h3>Optimizing the efficiency of HMM computations using Dynamic Programming</h3><p>Since predicting the optimal sequence using HMM can become computational tedious as the number of the sequence length increases, we resort to dynamic programming (cached recursion) in order to improve its performance.</p><h3>Examining computation complexity as the sequence length increases</h3><p>In this section, we will increase our sequence length to a much longer sentence and examine the impact on computation time. The same performance issues will also be encountered if the number of states is large, although in this case, we will only tweak the sequence length.</p><pre><em># initialize a new sequence of observations</em><br>obs = [&#39;Bob&#39;,&#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;Bob&#39;,&#39;ate&#39;,&#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;]</pre><pre><em># print results</em></pre><pre><strong>import</strong> <strong>time</strong><br>startTime = time.time()</pre><pre><em>## recompute sequences and sequence scores</em><br>sequence_length,sequences,sequence_scores = initializeSequences(obs)</pre><pre><em># Display partial list of sequence scores</em><br>rangeLen = 0<br><strong>if</strong> len(sequences) &gt; 10:<br>    rangeLen = 10<br><strong>else</strong>:<br>    rangeLen = len(sequences)<br>    <br><strong>for</strong> i <strong>in</strong> range(rangeLen):<br>    <strong>print</strong>(&quot;Sequence:<strong>%-60s</strong> Score:<strong>%0.6f</strong>&quot; % (sequences[i],sequence_scores[i]))<br>    <br><em># Display the winning score</em><br><strong>print</strong>(&quot;<strong>\n</strong> Best Sequence&quot;)<br><strong>print</strong>(sequences[sequence_scores.index(max(sequence_scores))],max(sequence_scores))</pre><pre><em># print time</em><br><strong>print</strong>(&quot;<strong>\n</strong> Sequence length:<strong>%5d</strong>, State count: <strong>%5d</strong>, Time taken:<strong>%0.4f</strong> seconds&quot; %\<br>      (sequence_length,len(initial_probs),time.time()-startTime))</pre><pre>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Noun&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Verb&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Noun&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Verb&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Determiner&#39;] Score:0.000000<br>Sequence:[&#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Noun&#39;, &#39;Noun&#39;] Score:0.000000</pre><pre> Best Sequence<br>([&#39;Noun&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Determiner&#39;, &#39;Noun&#39;, &#39;Noun&#39;, &#39;Verb&#39;, &#39;Verb&#39;, &#39;Determiner&#39;, &#39;Noun&#39;], 5.92297667290203e-05)</pre><pre> Sequence length:   11, State count:     3, Time taken:2.7134 seconds</pre><p>Notice that the time taken get very large even for small increases in sequence length and for a very a small state count.</p><h3>Dynamic Programming Intuition for HMMs</h3><h3>Intuition behind the Dynamic Programming algorithm for computing MBR scores</h3><p>Dynamic programming is implemented using cached recursion. Formulating a problem recursively and caching intermediate values allows for exponential improvements in performance compared to other methods of computation.</p><p>The MBR solution can be computed using dynamic programming. MBR allows us to compute the sum over all sequences conditioned on keeping one of the hidden states at a particular position fixed. This in turn allows us to determine the best score for a given state at a given position. We do this by computing the best score for every state at that position and pick the state that has the highest score.</p><p>Consider the example of a sequence of four words — “Bob ate the fruit”. Let us assume that we would like to compute the MBR score conditioned on the hidden state at position 1 (y1) being a Noun (N).</p><p>This computation can be mathematically shown to be equivalent to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bDxCtprGxAhjpjej.png" /></figure><p><strong>Figure — 14: HMM — Dynamic Programming — Finding the MBR Score Source: UC Berkeley lectures</strong></p><p>We break up the computation into two parts. In the first part, we compute <strong>alpha</strong>, the sum of all possible ways that the sequence can end up as a Noun in position 1 and in the second part, we compute beta, the sum of all possible ways that the sequence can start as a Noun.</p><h3>Forward/Backward Algorithm for computing the MBR scores</h3><p>The below code computes our alpha and beta values. We make dynamic caching an argument in order to demonstrate performance differences with and without caching.</p><pre>alpha_cache = {}</pre><pre><strong>def</strong> alpha(pos,state,textList,cachedRecursion = True):<br>    <br>    <strong>if</strong> cachedRecursion == True:<br>        <br>        <em># if cache is enabled, try to read from cache</em><br>        <strong>if</strong> alpha_cache.get((pos,state)) != None:<br>            <strong>return</strong> alpha_cache[(pos,state)]<br>        <br>    <strong>if</strong> pos == 0:<br>        <strong>return</strong> initial_probs[state] * emission_probs[textList[pos] + &quot;|&quot; + state]<br>    <strong>else</strong>:<br>        total = 0<br>        <strong>for</strong> state_val <strong>in</strong> states:<br>            total += alpha(pos-1,state_val,textList,cachedRecursion) \<br>            * transition_probs[state+&quot;|&quot;+state_val] * emission_probs[textList[pos]+&quot;|&quot;+state]<br>        <br>        <em># if cache is enabled, then cache</em><br>        <strong>if</strong> cachedRecursion == True:<br>            <strong>if</strong> alpha_cache.get((pos,state)) == None:<br>                alpha_cache[(pos,state)] = total<br>        <br>        <strong>return</strong> total</pre><pre>beta_cache = {}</pre><pre><strong>def</strong> beta(pos,state,textList,currIndex=0,currState=None,cachedRecursion = True):<br>    <br>    <strong>if</strong> cachedRecursion == True:<br>        <br>        <em># if cache is enabled, try to read from cache</em><br>        <strong>if</strong> beta_cache.get((currIndex,currState)) != None:<br>            <strong>return</strong> beta_cache[(currIndex,currState)]<br>        <br>    <strong>if</strong> currIndex == 0:<br>        currIndex = len(textList)<br>        <br>        <strong>if</strong> pos == currIndex - 1:<br>            <strong>return</strong> 1<br>        <br>        total = 0<br>        <strong>for</strong> state_val <strong>in</strong> states:<br>            tempSum = beta(pos,state,textList,currIndex-1,state_val,cachedRecursion) <br>            <br>            total += tempSum<br>        <br>        <em># if cache is enabled, then cache</em><br>        <strong>if</strong> cachedRecursion == True:<br>            <strong>if</strong> beta_cache.get((currIndex,currState)) == None:<br>                beta_cache[(currIndex,currState)] = total<br>                <br>        <strong>return</strong> total<br>    <br>    <strong>elif</strong> currIndex == pos+1:</pre><pre>        <strong>return</strong> transition_probs[currState+&quot;|&quot;+state] * emission_probs[textList[currIndex]+&quot;|&quot;+currState]<br>  <br>    <strong>else</strong>:<br>        total = 0<br>        <strong>for</strong> state_val <strong>in</strong> states:<br>            <br>            inStateProb = transition_probs[currState+&quot;|&quot;+state_val] * emission_probs[textList[currIndex]+&quot;|&quot;+currState]<br>            tempSum = inStateProb *beta(pos,state,textList,currIndex-1,state_val,cachedRecursion) </pre><pre>            total += tempSum<br>            <br>        <em># if cache is enabled, then cache</em><br>        <strong>if</strong> cachedRecursion == True:<br>            <strong>if</strong> beta_cache.get((currIndex,currState)) == None:<br>                beta_cache[(currIndex,currState)] = total<br>                <br>        <strong>return</strong> total</pre><h3>Dynamic Programming Performance Improvements</h3><p>We will now test out the dynamic programming algorithm with and without caching enabled to look at performance improvements.</p><p>For our dataset, we will use a much longer sequence since we have a much more efficient algorithm.</p><pre><em># set observations</em><br>obs = [&#39;Bob&#39;,&#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;Bob&#39;,&#39;ate&#39;,\<br>       &#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;Bob&#39;,&#39;ate&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;the&#39;,&#39;fruit&#39;,&#39;Bob&#39;]</pre><pre>position = 4<br>part_of_speech = &quot;Determiner&quot;</pre><h3>Forward/Backward algorithm for computing MBR score without caching</h3><pre><em># measure time taken without caching (dynamic programming)</em><br><strong>import</strong> <strong>time</strong></pre><pre>startTime = time.time()</pre><pre><em># variables for saving alpha and beta values</em><br>alpha_cache = {}<br>beta_cache = {}</pre><pre><em># get alpha</em><br>alpha_res = alpha(position,part_of_speech,obs,cachedRecursion=False)  </pre><pre><em># get beta</em><br>beta_res = beta(position,part_of_speech,obs,cachedRecursion=False)</pre><pre>mbr_score = alpha_res * beta_res</pre><pre><strong>print</strong>(&quot;MBR Score for Position:<strong>%d</strong> and POS:<strong>%s</strong> is <strong>%0.8f</strong>&quot; % (position,part_of_speech,mbr_score))<br><em># print time</em><br><strong>print</strong>(&quot;<strong>\n</strong> Time taken:<strong>%0.4f</strong> seconds&quot; % (time.time()-startTime))</pre><pre>MBR Score for Position:4 and POS:Determiner is 0.00000004</pre><pre> Time taken:3.7872 seconds</pre><h3>Forward/Backward algorithm for computing MBR score with caching</h3><pre><em># measure time taken with caching (dynamic programming)</em><br><strong>import</strong> <strong>time</strong></pre><pre>startTime = time.time()</pre><pre><em># variables for saving alpha and beta values</em><br>alpha_cache = {}<br>beta_cache = {}</pre><pre><em># get alpha</em><br>alpha_res = alpha(position,part_of_speech,obs,cachedRecursion=True)  </pre><pre><em># get beta</em><br>beta_res = beta(position,part_of_speech,obs,cachedRecursion=True)</pre><pre>mbr_score = alpha_res * beta_res</pre><pre><strong>print</strong>(&quot;MBR Score for Position:<strong>%d</strong> and POS:<strong>%s</strong> is <strong>%0.8f</strong>&quot; % (position,part_of_speech,mbr_score))<br><em># print time</em><br><strong>print</strong>(&quot;<strong>\n</strong> Time taken:<strong>%0.4f</strong> seconds&quot; % (time.time()-startTime))</pre><pre>MBR Score for Position:4 and POS:Determiner is 0.00000004</pre><pre> Time taken:0.0010 seconds</pre><p>Notice the significant improvements in time when we use the version with cached recursion.</p><h3>Conclusion</h3><p>HMMs are used in a variety of scenarios including Natural Language Processing, Robotics and Bio-genetics. In this post, we saw some of the basics of HMMs, especially in the context of NLP and Parts of Speech tagging. In later posts, I hope to elaborate on other HMM concepts based on Expectation Maximization and related algorithms.</p><p>I want to acknowledge my gratitude to James Kunz and Ian Tenney, lecturers at the UC Berkeley Information and Data Science program, for their help and support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3f58728caab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>