<?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 Peyman Kor on Medium]]></title>
        <description><![CDATA[Stories by Peyman Kor on Medium]]></description>
        <link>https://medium.com/@peymankor?source=rss-d7edd6a4f65d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Om5LrB-tD6uKrshS1jX9jg.jpeg</url>
            <title>Stories by Peyman Kor on Medium</title>
            <link>https://medium.com/@peymankor?source=rss-d7edd6a4f65d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:19:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@peymankor/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[Learn Reinforcement Learning from Human Feedback (RLHF): Your 9-Hour Study Plan]]></title>
            <link>https://pub.towardsai.net/learn-reinforcement-learning-from-human-feedback-rlhf-your-9-hour-study-plan-2bb0b8314e94?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bb0b8314e94</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[rlhf]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 15:00:35 GMT</pubDate>
            <atom:updated>2025-01-31T12:56:51.177Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to understanding RLHF and its role in LLMs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIFnQAjAd-Ty8-pHz1teeQ.png" /><figcaption>A visual explanation of RLHF — Image Source: Author</figcaption></figure><h3>Introduction</h3><p>This blog post is for people who have heard the term Reinforcement Learning from Human Feedback (RLHF) and are curious about this method. In this blog, you will learn how RLHF works, why it matters, and how you can master the fundamentals in just 9 hours.</p><p>In short, RLHF has been developed to transform Large Language Models (LLM) from <em>AI models</em> to <em>AI assistants</em>. That is the core idea. This means that AI companies (OpenAI, Google, or Anthropic, etc.) can make AI products that are more helpful and useful for their customers. Indeed that is a crucial aspect of any product development strategy because ultimately, you want to build products that are useful for your human customers.</p><h3>Background on Foundation Models</h3><p>Now let’s see how modern Large Language Models (LLMs) are trained and developed. The training process of these models typically involves three phases:</p><h4>Phase 1: Pre-training</h4><p>In this phase, the model learns from vast amounts of internet data (typically trillions of tokens) to predict the next word in a sequence. Think of it as learning the statistical patterns of language. For example, given the phrase “My favorite football team in UK is the ___“, the model learns that ” <em>Manchester United</em> or <em>Liverpool</em> are more likely completions (higher probability) than “car” or “pizza”. This phase helps the model to develop a basic understanding of language structure and meaning. To get an intuition about how the probability of the next word is predicted, I encourage you to go and play with the Transformer Explainer website [here (<a href="https://poloclub.github.io/transformer-explainer/">https://transformer.huggingface.co/</a>). You add a sentence at the top, and on the far right side, you can see the probability of the next word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCe4wxWx5UIV_-mrtSGh9w.png" /><figcaption>How transformers work (Phase 1): A visual guide — Image Source: Author, adapted from the public website <a href="https://poloclub.github.io/transformer-explainer/">https://poloclub.github.io/transformer-explainer/</a>&quot;</figcaption></figure><p>If you look at the far right part of the above figure, you can see the likelihood of each word to complete the sentence:</p><blockquote>“My favorite football team in UK is the ___“</blockquote><p>As you can see, here are the probabilities of completion of the sentence:</p><ul><li>Manchester: around 6%</li><li>Rams?? : around 5 %</li><li>List goes on</li></ul><h4>Phase 2: Supervised Fine-tuning (SFT)</h4><p>Language is inherently flexible — there are many valid ways to respond<br>to any prompt. For example, if asked “How do I make pasta?”, valid<br>responses could include:</p><p><em>A) You can learn by watching YouTube</em></p><p><em>B) Giving you a listing of ingredients, explaining cooking steps,<br>or suggesting serving sizes.</em></p><p>And of course, as a user, you prefer option B, which is a completion you prefer. In the Supervised Fine-tuning stage (Phase 2), we show the model good examples of questions and answers to teach it how to respond well. The data used in this phase is typically collected from highly educated workers. They are high-quality data. Here are some examples of supervised fine-tuning datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOL0zdHwSI6ZytCnuBfFuA.png" /><figcaption>An example of supervised fine-tuning (SFT) data — Image Source: Author, originally from the OpenAI paper [1]</figcaption></figure><h4>Phase 3: Reinforcement Learning from Human Feedback (RLHF)</h4><p>Even after phase 2, some responses are better than others from a human<br>perspective. In Phase 3 we show the model’s various responses and ask<br>humans to rate them. Essentially, we would like to optimize the model for<br>the output to get higher ratings from humans. This stage that brings<br>human feedback into the loop is called <strong>Reinforcement Learning from Human Feedback (RLHF).</strong></p><p>Here is a simple example. We give the prompt “Explain the moon landing to a 6-year-old in a few sentences” to LLM — Then LLM gives two possible answers, and we ask humans which one they prefer. Then, this preference becomes a “signal” to LLMs, so that they need to make more of the response that humans would like to see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_DfdeNJ-nY5TzkIYFl_mg.png" /><figcaption>Human preference — Image Source: Adapted from a public presentation, available , <a href="https://docs.google.com/presentation/d/13Tylt2SvKvBL2hgILy5CmBtPDv3rXlVrQp01OzAe5Xo/edit#slide=id.g238b2698243_0_252">here</a></figcaption></figure><p>Now with this background, let’s see how we can learn about RLHF.</p><h3>Study Roadmap</h3><p>To help you navigate this topic, I’ve organized learning resources into five main categories.</p><ol><li><strong>Introductory Tutorials</strong></li><li><strong>Key Research Papers</strong></li><li><strong>Hands-on Codes</strong></li><li><strong>Online Courses</strong></li><li><strong>RLHF Book</strong></li></ol><p>Let&#39;s get started:</p><p><strong>1. Introductory Tutorials</strong></p><p>Here the goal is to get a high-level understanding of RLHF. I suggest<br>you start with Chip Huyen’s blog post on RLHF. It is a great introduction to the topic. then you can continue with rest. I should note that <a href="https://twitter.com/natolambert?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Nathan Lambert</a> is quite active on Twitter about this topic, and I suggest following him if you want to keep updated with RLHF.</p><p><strong>Resources:</strong></p><ol><li>📚 20m:<strong> Introduction to RLHF</strong> by Chip Huyen [<a href="https://t.ly/kt7vZ">Read<br> here</a>]<br>2. 📺 40m: <strong>RLHF: From Zero to ChatGPT</strong> by Nathan Lambert [<a href="https://t.ly/gOj_-">Watch<br> here</a>]<br>3. 📺 60m:<strong> Lecture on RLHF</strong> by Hyung Won Chung [<a href="https://t.ly/S4LWN">See<br> here</a>]</li></ol><p><strong>2. Key Research Papers</strong></p><p>Here are some important research papers that I think are worth reading to get a deeper understanding of RLHF.</p><p><strong>Resources:</strong></p><p>- 📚 30m: <strong>InstructGPT Paper</strong> — Applying RLHF to a general language<br> model [<a href="https://t.ly/iBARr">Read here</a>]<br>- 📚 30m: <strong>DPO Paper by Rafael Rafailov</strong> [<a href="https://arxiv.org/pdf/2305.18290">Read here</a>]<br>- 📚 30m: <strong>Artificial Intelligence, Values, and Alignment</strong> — [<a href="https://t.ly/DLxNM">Read here</a>]</p><p><strong>3. Hands-on Codes</strong></p><p>Here I am adding some codes that you can run on your local machine (though unfortunately only if you have a lot of GPUs :)) to get a hands-on experience of RLHF. I would like to note that TRL seems to a<br>nice library that has been used for RLHF, maybe that can be go to go library when it comes to RLHF implementation.</p><p>- 📚 2h: <strong>Detoxifying a Language Model using PPO</strong> [<a href="https://shorturl.at/o2X31">Read here</a>]<br>- 📚 2h: <strong>RLHF with DPO &amp; Hugging Face</strong> [<a href="https://shorturl.at/q1Brq">Read<br> here</a>]<br>- 📚 1h: <strong>TRL Library for Fast Implementation</strong>— Minimal and efficient<br> [<a href="https://shorturl.at/ezzvU">Read here</a>]</p><p><strong>4. Online Course</strong></p><p>If you are looking for a more structured learning experience, I<br>recommend taking an online course. Here is a course that covers<br>RLHF:</p><ul><li>📚 1h: <strong>Reinforcement Learning from Human Feedback</strong> by Nikita<br> Namjoshi [<a href="https://www.deeplearning.ai/short-courses/reinforcement-learning-from-human-feedback/">Course link</a>]</li></ul><p><strong>5. RLHF Book</strong></p><p>Finally, if you want to dive deep into RLHF, I recommend reading the book [<strong>A Little Bit of Reinforcement Learning from Human Feedback </strong>(<a href="https://rlhfbook.com/book.pdf">https://rlhfbook.com/book.pdf</a>) by Nathan Lambert. This book is in progress and you can read it online for free.</p><h3>Conclusion</h3><p>I hope this study guide helps you get started with Reinforcement<br>Learning from Human Feedback (RLHF). It seems it becoming more evident that Reinforcement learning is going to play an ever-increasing role in making LLMs better, especially with the release of <a href="https://www.deepseek.com/">DeepSeek</a>, which has a pure RL framework for training.</p><p>Hope you liked the blog and remember that the key to learning any topic is consistency and being curious!</p><p><strong>References:</strong></p><p>[1 ]: Ouyang, Long, et al. <a href="https://arxiv.org/abs/2203.02155">“Training language models to follow instructions with human feedback</a>.” <em>Advances in neural information processing systems</em> 35 (2022): 27730–27744.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bb0b8314e94" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/learn-reinforcement-learning-from-human-feedback-rlhf-your-9-hour-study-plan-2bb0b8314e94">Learn Reinforcement Learning from Human Feedback (RLHF): Your 9-Hour Study Plan</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Inventory Management with Reinforcement Learning: A Hands-on Python Guide]]></title>
            <link>https://medium.com/data-science/optimizing-inventory-management-with-reinforcement-learning-a-hands-on-python-guide-7833df3d25a6?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7833df3d25a6</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[inventory-management]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 01:20:00 GMT</pubDate>
            <atom:updated>2025-01-16T11:52:29.821Z</atom:updated>
            <content:encoded><![CDATA[<h4>A complete guide on how to apply the Q-Learning method in Python to optimize inventory management and reduce costs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*coNEBjFK73jwJApq" /><figcaption>Photo by <a href="https://unsplash.com/@petrebels?utm_source=medium&amp;utm_medium=referral">Petrebels</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Inventory Management — What Problem Are We Solving?</h3><p>Imagine you are managing a bike shop. Every day, you need to decide how many bikes to order from your supplier. If you order too many, you incur high holding costs (cost of storing bikes overnight); if you order too few, you might miss out on potential sales. Here, the challenge is to develop a (ordering) strategy that balances these trade-offs optimally. Inventory management is crucial in various industries, where the goal is to determine the optimal quantity of products to order periodically to maximize profitability.</p><p><strong>Why Reinforcement Learning for Inventory Management?</strong></p><p>Previously, we discussed approaching this problem using Dynamic Programming (DP) with the Markov Decision Process (MDP) <a href="https://medium.com/towards-artificial-intelligence/inventory-optimization-with-dynamic-programming-in-less-than-100-lines-of-python-code-ab1cc58ef34c">Here</a>. However, the DP approach requires a complete model of the environment (in this case, we need to know the probability distribution of demand), which may not always be available or practical.</p><blockquote>Here, the Reinforcement Learning (RL) approach is presented, which overcomes that challenge by following a “data-driven” approach.</blockquote><p>The goal is to build a “data-driven” agent that learns the best policy (how much to order) through interacting with the environment (uncertainty). The RL approach removes the need for prior knowledge about the model of the environment. This post explores the RL approach, specifically Q-learning, to find the optimal inventory policy.</p><h3>How to Frame the Inventory Management Problem?</h3><p>Before diving into the Q-learning method, it’s essential to understand the basics of the inventory management problem. At its core, inventory management is a sequential decision-making problem, where decisions made today affect the outcomes and choices available tomorrow. Let’s break down the key elements of this problem: the <em>state</em>, <em>uncertainty</em>, and <em>recurring decisions</em>.</p><p><strong>State</strong>: What’s the Current Situation?</p><p>In the context of a bike shop, the state represents the current situation regarding inventory. It’s defined by two key components:</p><p>α (Alpha): The number of bikes you currently have in the store. (referred to as On-Hand Inventory)</p><p>β (Beta): The number of bikes that you ordered yesterday and are expected to arrive tomorrow morning (<em>36 hours delivery lead time</em>). These bikes are still in transit. (referred to as On-Order Inventory)</p><p>Together, (α,β) form the state, which gives a snapshot of your inventory status at any given moment.</p><p><strong>Uncertainty</strong>: What Could Happen?</p><p>Uncertainty in this problem arises from the random demand for bikes each day. You don’t know exactly how many customers will walk in and request a bike, making it challenging to predict the exact demand.</p><p><strong>Decisions</strong>: How Many Items Should you Order Every Day?</p><p>As the bike shop owner, you face a recurring decision every day: How many bikes should you order from the supplier? . Your decision needs to account for both the current state of your inventory (α,β) and also the uncertainty in customer demand for the following day.</p><p>A typical 24-hour cycle for managing your bike shop’s inventory is as follows:</p><p>6 PM: Observe the current state St:(α,β) of your inventory. (<strong>State</strong>)</p><p>6 PM: Make the decision on how many new bikes to order. (<strong>Decision</strong>)</p><p>6 AM: Receive the bikes you ordered 36 hours ago.</p><p>8 AM: Open the store to customers.</p><p>8 AM — 6 PM: Experience customer demand throughout the day. (<strong>Uncertainty</strong>)</p><p>6 PM: Close the store and prepare for the next cycle.</p><p>A graphical representation of the inventory management process is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HSUODvSE29AeFhTWObcIw.png" /><figcaption>A typical 24-hour cycle for inventory management — image source: Author</figcaption></figure><h3>What is Reinforcement Learning?</h3><p>Reinforcement Learning (RL) is a data-driven method that focuses on learning how to make sequences of decisions (following a policy) to maximize a cumulative reward. It&#39;s similar to how humans and animals learn what action to take through trial and error. In the context of inventory management, RL can be used to learn the optimal ordering policy that minimizes the total cost of inventory management.</p><p>The key components of the RL approach are:</p><p><strong>Agent</strong>: The decision-maker who interacts with the environment.</p><p><strong>Environment</strong>: The external system with which the agent interacts. In this case, the environment is the random customer demand.</p><p><strong>State</strong>: The current situation or snapshot of the environment.</p><p><strong>Action</strong>: The decision or choice made by the agent.</p><p><strong>Reward</strong>: The feedback signal that tells the agent how well it’s doing.</p><p>The goal of the agent (decision-maker) is to learn the optimal policy, which is a mapping from states to actions that maximize the cumulative reward over time.</p><blockquote>In the context of inventory management, the policy tells the agent how many bikes to order each day based on the current inventory status and the uncertainty in customer demand.</blockquote><h3>Implementing Reinforcement Learning for Inventory Optimization Problem</h3><p><strong>Q-learning</strong> is a model-free reinforcement learning algorithm that learns the optimal action-selection policy for any given state. Unlike the DP approach, which requires a complete model of the environment, Q-learning learns directly from the interaction with the environment (here, uncertainty and the reward it gets) by updating a Q-table.</p><p><strong>The key components of Q-Learning</strong></p><p>In our case, the agent is the decision-maker (the bike shop owner), and the environment is the demand from customers. The state is represented by the current inventory levels (alpha, beta), and the action is how many bikes to order.<strong> The reward is the cost associated with both holding inventory and missing out on sales</strong>. Q-Table is a table that stores the expected future rewards for each state-action pair.</p><p><strong>Initialization of Q Table</strong></p><p>In this work, the Q-table is initialized as a dictionary named Q. States are represented by tuples (alpha, beta), where: alpha is the number of items in stock (on-hand inventory). beta is the number of items on order (on-order inventory).</p><p>Actions are <em>possible inventory order quantities </em>that can be taken in each state. For each state (alpha, beta), the possible actions depend on how much space is left in the inventory (remaining capacity = Inventory Capacity — (alpha + beta)). The restriction is that the number of items ordered cannot exceed the remaining capacity of the inventory.</p><p>The schematic design of the Q value is visualized below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*wKM7GyBD-QsZvs2JTQAEhw.png" /><figcaption>A schematic design of the Q dictionary is visualized — Image source: Author</figcaption></figure><p>The Q dictionary can be initialized as:</p><pre>def initialize_Q(self):<br>    # Initialize the Q-table as a dictionary<br>    Q = {}<br>    for alpha in range(self.user_capacity + 1):<br>        for beta in range(self.user_capacity + 1 - alpha):<br>        state = (alpha, beta)<br>        Q[state] = {}<br>        max_action = self.user_capacity - (alpha + beta)<br>        for action in range(max_action + 1):<br>            Q[state][action] = np.random.uniform(0, 1)  # Small random values<br>    return Q</pre><p>As the above code shows, Q-values (Q[state][action]) are initialized with small random values to encourage exploration.</p><h3>The Q-Learning Algorithm</h3><p>The Q-learning method updates a table of state-action pairs based on rewards from the environment (here, interacting with the environment comes). Here’s how the algorithm works in three steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*11Et_deLlmsX8pjCwImPGA.png" /><figcaption>Q-Learning Equation — Image Source: Author</figcaption></figure><p>Where s is the current state, a is the action taken, s’ is the next state, ( α ) is the learning rate. and ( γ ) is the discount factor.</p><p>We breakdown the equation, and rewrote it in three parts down here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*nFpaSa0QLAM5Yca63DrggA.png" /><figcaption>Q-Learning Equation — Image Source: Author</figcaption></figure><p>The translation of the above equations to Python code is as follows:</p><pre>def update_Q(self, state, action, reward, next_state):<br>        # Update the Q-table based on the state, action, reward, and next state<br>        best_next_action = max(self.Q[next_state], key=self.Q[next_state].get)<br><br>        # reward + gamma * Q[next_state][best_next_action]<br>        td_target = reward + self.gamma * self.Q[next_state][best_next_action]<br><br>        # td_target - Q[state][action]<br>        td_error = td_target - self.Q[state][action]<br><br>        # Q[state][action] = Q[state][action] + alpha * td_error<br>        self.Q[state][action] += self.alpha * td_error</pre><p>At the above function, the equivalent equation of each line has been shown as a comment on top of each line.</p><h3>Simulating Transitions and Rewards in Q-Learning for Inventory Optimization</h3><p>The current state is represented by a tuple (alpha, beta), where: alpha is the current on-hand inventory (items in stock), beta is the current on-order inventory (items ordered but not yet received), init_inv calculates the total initial inventory by summing alpha and beta.</p><p>Then, we need to simulate customer demand using Poisson distribution with lambda value “self.poisson_lambda”. Here, the demand shows the randomness of customer demand:</p><pre>alpha, beta = state<br>init_inv = alpha + beta<br>demand = np.random.poisson(self.poisson_lambda)</pre><p><strong>Note</strong>: Poisson distribution is used to model the demand, which is a common choice for modeling random events like customer arrivals. However, we can either train the model with historical demand data or live interaction with environment in real time. In its core, reinforcement learning is about learning from the data, and it does not require prior knowledge of a model.</p><p>Now, the “next alpha” which is in-hand inventory can be written as max(0,init_inv-demand). What that means is that if demand is more than the initial inventory, then the new alpha would be zero, if not, init_inv-demand.</p><p>The <strong>cost</strong> comes in two parts. <strong>Holding cost</strong>: is calculated by multiplying the number of bikes in the store by the per-unit holding cost. Then, we have another cost, which is <strong>stockout cost</strong>. It is a cost that we need to pay for the cases of missed demand. These two parts form the “reward” which we try to maximize using reinforcement learning method.( a better way to put is we want to minimize the cost, so we maximize the reward).</p><pre>new_alpha = max(0, init_inv - demand)<br>holding_cost = -new_alpha * self.holding_cost<br>stockout_cost = 0<br><br>if demand &gt; init_inv:<br>    <br>    stockout_cost = -(demand - init_inv) * self.stockout_cost<br>        <br>reward = holding_cost + stockout_cost<br>next_state = (new_alpha, action)</pre><h4>Exploration — Exploitation in Q-Learning</h4><p>Choosing action in the Q-learning method involves some degree of exploration to get an overview of the Q value for all the states in the Q table. To do that, at every action chosen, there is an epsilon chance that we take an exploration approach and “randomly” select an action, whereas, with a 1-ϵ chance, we take the best action possible from the Q table.</p><pre>def choose_action(self, state):<br><br>        # Epsilon-greedy action selection<br>    if np.random.rand() &lt; self.epsilon:<br>        <br>          return np.random.choice(self.user_capacity - (state[0] + state[1]) + 1)<br>    <br>    else:<br>        <br>        return max(self.Q[state], key=self.Q[state].get)</pre><h4>Training RL Agent</h4><p>The training of the RL agent is done by the “train” function, and it is follow as: First, we need to initialize the Q (empty dictionary structure). Then, experiences are collected in each batch (self.batch.append((state, action, reward, next_state))), and the Q table is updated at the end of each batch (self.update_Q(self.batch)). The number of episodes is limited to “max_actions_per_episode” in each batch. The number of episodes is the number of times the agent interacts with the environment to learn the optimal policy.</p><p>Each episode starts with a randomly assigned state, and while the number of actions is lower than max_actions_per_episode, the collecting data for that batch continues.</p><pre>def train(self):<br><br>        self.Q = self.initialize_Q()  # Reinitialize Q-table for each training run<br><br>        for episode in range(self.episodes):<br>            alpha_0 = random.randint(0, self.user_capacity)<br>            beta_0 = random.randint(0, self.user_capacity - alpha_0)<br>            state = (alpha_0, beta_0)<br>            #total_reward = 0<br>            self.batch = []  # Reset the batch at the start of each episode<br>            action_taken = 0<br>            while action_taken &lt; self.max_actions_per_episode:<br>                action = self.choose_action(state)<br>                next_state, reward = self.simulate_transition_and_reward(state, action)<br>                self.batch.append((state, action, reward, next_state))  # Collect experience<br>                state = next_state<br>                action_taken += 1<br>            <br>            self.update_Q(self.batch)  # Update Q-table using the batch</pre><h3>Example Case and Results</h3><p>This is example case is on how to pull together all above codes, and see how the Q-learning agent learns the optimal policy for inventory management. Here, <em>user_capicty</em> (capacity of storage) is 10, which is the total number of items that inventory can hold (capacity). Then, the <em>poisson_lambda</em> is the lambda term in the demand distribution, which has a value of 4. Holding costs is 8, which is the cost of holding an item in inventory overnight, and stockout cost, which is the cost of missed demand (assume that the item had a customer that day and the price of the item was, but you did not have the item in your inventory) is 10. <em>gamma</em> value lower than one is needed in the equation to discount the future reward (0.9), where <em>alpha</em> (learning rate ) is 0.1. The <em>epsilon</em> term is the term control exploration-exploitation dilemma. The episodes are 1000, and each batch consists of 1000 (max actions per episode).</p><pre># Example usage:<br>user_capacity = 10<br>poisson_lambda = 4<br>holding_cost = 8<br>stockout_cost = 10<br>gamma = 0.9<br>alpha = 0.1<br>epsilon = 0.1<br>episodes = 1000<br>max_actions_per_episode = 1000</pre><p>Having defined these initial parameters of the model, we can define the ql Python class, then use the class to train, and then use the module “get_optimal_policy()” to get the optimal policy.</p><pre># Define the Class<br>ql = QLearningInventory(user_capacity, poisson_lambda, holding_cost, stockout_cost, gamma, <br>                        alpha, epsilon, episodes, max_actions_per_episode)<br><br># Train Agent<br>ql.train()<br><br># Get the Optimal Policy<br>optimal_policy = ql.get_optimal_policy()</pre><p><strong>Results</strong></p><p>Now that we have the policy found from the Q-learning method, we can visualize the results and see what they look like. The x-axis is states, which is a tuple of (alpha, beta), and the y-axis is the “Number of Order” found from Q-learning at each state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnZ3qlYeDcL1WIq6Dcfbhw.png" /><figcaption><em>Number of order (y-axis) for each state (x-axis) found from Q-learning policy — Image Source: Author</em></figcaption></figure><p>A couple of learnings can be gained by looking at the plot. First, as we go toward the right, we see that the number of orders decreases. When we go right, the alpha value increases (in-hand inventory), meaning we need to “order” less, as inventory in place can fulfill the demand. Secondly, When alpha is constant, with increasing beta, we lower the order of new sites. It can be understood that this is due to the fact that when “we have more item “on order” we do not need increase the orders.</p><p><strong>Comparing the Q-Learning Policy to the BaseLine Policy</strong></p><p>Now that we used Q-learning to find the policy (how many items to order in a given state), we can compare it to the baseline policy (a simple policy). The baseline policy is just to “order up to policy,” which simply means you look at the on-hand inventory and the on-order inventory and order up to “meet the target level.” We can write simple code to write this policy in Python format here:</p><pre># Create a simple policy<br>def order_up_to_policy(state, user_capacity, target_level):<br>    alpha, beta = state<br>    max_possible_order = user_capacity - (alpha + beta)<br>    desired_order = max(0, target_level - (alpha + beta))<br>    return min(max_possible_order, desired_order)</pre><p>In the code, the <strong>target_level</strong> is the desired value we want to order for inventory. If target_level = user_capacity, then we are filling just to fulfill the inventory. First, we can compare the policies of these different methods. For each state, what will be the “number of orders” if we follow the Simple policy and the one from the Q-learning policy? In the figure below, we plotted the comparison of two policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guy3n-XuQpaDCmXqSodlrQ.png" /><figcaption>Comparing Ordering policy between Q-Learning and Simple Policy, for each state — Image Source : Author</figcaption></figure><p>The simple policy is just to order so that it fulfills the inventory, where the Q-learning policy order is often lower than the simple policy order.</p><blockquote><strong>This can be attributed to the fact that “poisson_lambda” here is 4, meaning the demand is much lower than the capacity of the inventory=10, therefore it is not optimal to order “high number of bicycle” as it has a high holding cost.</strong></blockquote><p>We can also compare the total cumulative rewards you can get when you apply both policies. To do that, we can use the <em>test_policy</em> function of “QLearningInventory” which was especially designed to evaluate policies:</p><pre>def test_policy(self, policy, episodes):<br>        &quot;&quot;&quot;<br>        Test a given policy on the environment and calculate the total reward.<br><br>        Args:<br>            policy (dict): A dictionary mapping states to actions.<br>            episodes (int): The number of episodes to simulate.<br><br>        Returns:<br>            float: The total reward accumulated over all episodes.<br>        &quot;&quot;&quot;<br>        total_reward = 0<br>        alpha_0 = random.randint(0, self.user_capacity)<br>        beta_0 = random.randint(0, self.user_capacity - alpha_0)<br>        state = (alpha_0, beta_0)  # Initialize the state<br>        <br>        for _ in range(episodes):<br><br>            action = policy.get(state, 0)<br>            next_state, reward = self.simulate_transition_and_reward(state, action)<br>            total_reward += reward<br>            state = next_state<br><br>        return total_reward</pre><p>The way the function works is it starts randomly with a new state (state = (alpha_0, beta_0); then for that state, you get action (number of order) for that state from policy, you act and see the reward, and next state, and the process continues as total number of episodes, while you collect the total reward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoE2GobFYCtE2PKmLhBR_Q.png" /><figcaption>Total costs of manging Inventory, following Q-Learnng policy and Simple policy — Image Source Author</figcaption></figure><p>The plot above compares the total cost of managing inventory when we follow the “Q-Learning” and “Simple Policy”. The aim is to mimimize the cost of running inventory. Since the ‘reward’ in our model represents this cost, we added total cost = -total reward.</p><blockquote>Running the inventory with the Q-Learning policy will lead to lower costs compared to the Simple policy.</blockquote><h3>Code in GitHub</h3><p>The full code for this blog can be found in the GitHub repository <a href="https://github.com/Peymankor/medium_blogs/blob/main/2024/08-Aug/RL-Inventory/main.py">here</a>.</p><h3>Summary and Main Takeaways</h3><p>In this post, we worked on how reinforcement learning (Q-Learning specifically) can be used to optimize inventory management. We were able to develop a Q-learning algorithm that learns the optimal ordering policy through interaction with the environment (uncertainty). Here, the environment was the “random” demand of the customers (buyers of bikes), and the state was the current inventory status (alpha, beta). The Q-learning algorithm was able to learn the optimal policy that minimizes the total cost of inventory management.</p><p><strong>Main Takeaways</strong></p><ol><li><strong>Q-Learning</strong>: A model-free reinforcement learning algorithm, Q-learning, can be used to find the optimal inventory policy without requiring a complete model of the environment.</li><li><strong>State Representation</strong>: The state in inventory management is represented by the current on-hand inventory and on-order inventory state = (α, β).</li><li><strong>Cost Reduction</strong>: We can see that the Q-learning policy leads to lower costs compared to the simple policy of ordering up to capacity.</li><li><strong>Flexibility</strong>: The Q-learning approach is quite flexible and can be applied to the case of we have past data of demand, or we can interact with the environment to learn the optimal policy.</li><li><strong>Data-Driven Decisions</strong>: As we showed, the reinforcement learning (RL) approach does not require any prior knowledge on the model of environment , as it is learning from the data.</li></ol><h3>References</h3><p>[1] A. Rao, T. Jelvis, Foundations of Reinforcement Learning with Applications in Finance (2022).</p><p>[2] S. Sutton, A. Barto, Reinforcement Learning: An Introduction (2018).</p><p>[3] W. B. Powell, Sequential Decision Analytics and Modeling: Modeling with Python (2022).</p><p>[4] R. B. Bratvold, Making Good Decisions (2010).</p><h3>Before you go! 🦸🏻‍♀️</h3><ol><li>If you found value in this article, please follow me on <a href="https://medium.com/@peymankor">Medium</a> and <a href="https://www.linkedin.com/in/peyman-kor/">Linkedin</a> to keep updated with my latest posts/writings.</li><li>You can reach out to me on my website: <a href="http://www.peymankor.com/">www.peymankor.com</a></li><li>Clap my article 50 times, that will really really help me out and boost this article to others.👏</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7833df3d25a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/optimizing-inventory-management-with-reinforcement-learning-a-hands-on-python-guide-7833df3d25a6">Optimizing Inventory Management with Reinforcement Learning: A Hands-on Python Guide</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Hero: A Step-by-Step Guide to Binomial Option Pricing in Less Than 30 Lines of Code!]]></title>
            <link>https://medium.datadriveninvestor.com/from-zero-to-hero-a-step-by-step-guide-to-binomial-option-pricing-in-less-than-30-lines-of-code-10ff2af268e2?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ff2af268e2</guid>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Mon, 27 May 2024 03:54:04 GMT</pubDate>
            <atom:updated>2024-05-28T16:48:31.839Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog guides you through mastering Binomial Option Pricing with Python. You will learn to price the American Option step-by-step, from theory to the coded example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*sqeOLHDcn11GbiSaRDdYYQ.png" /></figure><h3>Intro:</h3><p>In this blog post, I will explain the concept of the “Binomial Options Pricing Model” for option pricing.</p><p>The binomial model is a simple and widely used model for pricing options. The model is easy to understand and implement, making it a popular choice for pricing options.</p><p>More importantly, I will go through a simple example in Python to demonstrate how to implement the binomial model for pricing options through coding.</p><p>For exclusive insights on how to use AI /Reinforcement Learning for Option Pricing in Python, you can check out here:</p><p><a href="https://peymankor.gumroad.com/l/noyfhj">The Complete Option Pricing with Reinforcement Learning From A-Z in Python</a></p><h3><strong>Intro to American Options</strong></h3><p>American options are a type of financial derivative that gives the <strong>holder</strong> the right, but not the obligation, to buy or sell an underlying asset at a specified price on or before a certain date.</p><p>There are two common types of American options:</p><p><strong>Call Option</strong>: Gives the holder the right to buy the underlying asset at the strike price.</p><p><strong>Put Option</strong>: Gives the holder the right to sell the underlying asset at the strike price.</p><p>Let’s have an example to understand it better.</p><h4><strong>Example: American Put Option</strong></h4><p>Here is an example of how the <em>American Put Option</em> works:</p><p>The option expires in 3 days, the strike price is 100$, and the premium fee is 3$. Below are the prices of the underlying asset in the next three days (assumption):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*NzyAwBpOcmc7kLe0cWacxA.png" /><figcaption>Table of underlying asset future prices — Source: Author</figcaption></figure><p><strong>On day 1, </strong>the asset price is $92, and the strike price is $100. we can calculate the exercise value as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*bNrWHdS0TAt2A1gkMgu8TA.png" /></figure><p>Now, the option holder can sell the asset at 100$ (as she has the right to sell it at 100$) and buy back the asset at market price (say 92$). Now, she can make a profit of $3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*U0UrPSpBs8nZajAYSX1vEQ.png" /></figure><p>Now, the central question for Option Pricing is:</p><blockquote><strong>What is the fair value of the option? How to find the (Premium Value) of the Option?</strong></blockquote><h3><strong>Understanding the Binomial Lattice Model</strong></h3><p>The Binomial Lattice Model is a wide-spread model for pricing options. (Find the “premium” value of the option.) In this approach, we create a binomial tree of possible future asset prices with breaking down the time to expiration into discrete intervals.</p><p>At each time step, the price of the underlying asset can move up or down by a certain factor.</p><p>By the end of the model, a tree of possible asset prices is created. Then, the value of option is calculated at each node of the tree, starting from the end and working backwards to the present time.</p><h3><strong>Key Parameters of the Binomial Model:</strong></h3><ul><li>Initial Stock Price $S_0$ : Initial price of the underlying asset</li><li>Strike Price $K$: The price at which the option holder can buy or sell the asset</li><li>Expiry Time $T$ : Time to the expiration of the option</li><li>Risk-free Rate $r$: The rate of return on a risk-free investment.</li><li>Volatility $σ$: The standard deviation of the stock return (it is a of the stock price fluctuation)</li><li>Number of Time Steps $N$: The number of steps in the lattice model.</li></ul><h3><strong>Calculate the Up and Down Factor</strong></h3><p>As we mentioned, stock prices can move up or down at each time step. The up and down factors are constant in the whole tree structure. The up and down factors are calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*Y-UTHxi4rwOmCJZ2IChHRg.png" /></figure><p>We can rewrite the u (and d in the code is simply 1/u) as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*pAoBDBdPRqh-ea2g5OgsFg.png" /></figure><pre>import numpy as np<br><br>expiry_time_val = 1<br>num_time_steps_val = 50<br>volatility_val = 0.2<br><br># Time step<br>dt = expiry_time_val / num_time_steps_val<br><br># Up factor<br>u = np.exp(volatility_val * np.sqrt(dt))<br><br># down factor<br>d = 1 / u</pre><h3><strong>Calculating the Probability of Up and Down Movements</strong></h3><p>Now that we have found the <em>u</em> factor, we need the “probability” of the up factor. To understand the details of these equations, I refer to the classic no-arbitrage and risk-neutral probability concepts .¹</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*oYZ0bKsLOZerH9oGAcKw4Q.png" /></figure><p>Having defined the <em>q </em>value based on the <em>u</em>, <em>d,</em> and riks-free rate <em>r</em>, we can write <em>q</em> as :</p><pre>risk_free_rate_val = 0.06<br><br>q = (np.exp(risk_free_rate_val * dt) - d) / (u - d)</pre><h3><strong>Forming the Binomial Tree</strong></h3><p>Having found the <em>q</em> and <em>u</em> and <em>d=1/u, </em>we can fully define the binomial lattice model in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*ZhLHRkbWbiug6Q_6jCqUUg.png" /><figcaption>Visual Representation of Binomial Tree- Source: Author</figcaption></figure><p>Note that in the above lattice, <em>i </em>are time steps, while the <em>m</em> is the <strong>nodes</strong> inside that time step. The equation for the price at each node can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*-ZvD6I3k2TmckdKfDNc0Eg.png" /></figure><p>Where <em>i</em> is the time steps, <em>m &lt; i </em>is the nodes in that time step. For example, at time step<em> i=2</em>, the following are node prices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*JwxA1zS2ohxXOPpQu5UTkg.png" /></figure><h3><strong>Two-Step Procedure for Calculating Option Price:</strong></h3><p>In the Binomial Option Pricing Model (BOPM), we work from the end of the tree and work backward to the present.</p><p>So, I divide the codes into two steps:</p><ul><li><strong>Step 1: Calculate the option value at the end of the tree</strong></li><li><strong>Step 2: Calculate the option value at each node of the tree, starting from the end and working backward to the present time.</strong></li></ul><h4><strong>Step 1: Calculate the option value at the end of the tree</strong></h4><p>At the end of the tree, the option value is simply the max value of (exercise value of the option, 0). For a put option, the exercise value is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*6qzIZugr80vul-GVHMi40Q.png" /></figure><p>Where <em>K</em> is the strike price and $S_{node}$ is the asset price at the node (here, all nodes at the end of the tree). We can write code as:</p><pre>strike_price_val = 40 <br>initial_stock_price_val = 36<br>num_time_steps_val = 50<br><br>lattice_node_val = {}<br><br>for m in range(num_time_steps_val + 1):<br><br>        S_node = initial_stock_price_val * (u ** (2 * m - num_time_steps_val))<br><br>        lattice_node_val[(num_time_steps_val, m)] = max(strike_price_val - S_node, 0)<br><br><br>lattice_node_val</pre><h4><strong>Step 2: Calculate the option value at each tree node, starting from the end and working backward to the present time.</strong></h4><p>At each node of the tree, the node value is the max of the continuation value and exercise value. The continuation value is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*ITAe995YnG1y1icY0Gs_wA.png" /></figure><p>Where $OptionValue_{up}$ and $OptionValue_{down}$ are the option values at the next time step for the up and down movements, respectively.</p><pre>for k in range(num_time_steps_val - 1, -1, -1):<br>        for m in range(k + 1):<br><br>            cont_value = np.exp(-risk_free_rate_val * dt) * (q * lattice_node_val[(k + 1, m + 1)] + <br>                                                               (1 - q) * lattice_node_val[(k + 1, m)])<br>            <br>            S_node = initial_stock_price_val * (u ** (2 * m - k))<br>            <br>            exercise_value = max((strike_price_val - S_node), 0)<br>            <br>            lattice_node_val[(k, m)] = max(cont_value, exercise_value)</pre><p>The option price is given by the option&#39;s value at the lattice&#39;s root node:</p><pre>print(f&quot;The option price using Binomial Lattice Method is: {lattice_node_val[0, 0]:.2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhOFra5Yql-cyLGZqGr1gg.png" /></figure><h3>Putting Everything Together:</h3><p>We can put together all the above codes in one function that, given its input, gives the option value using the Binomial Lattice Method:</p><pre>def binomial_put_option_pricing(expiry_time : float,<br>                 num_time_steps: int,<br>                 volatility: float,<br>                 risk_free_rate: float,<br>                 strike_price: float,<br>                 initial_stock_price: float):<br><br>    dt = expiry_time / num_time_steps<br>    u = np.exp(volatility * np.sqrt(dt))<br>    d = 1 / u<br>    q = (np.exp(risk_free_rate * dt) - d) / (u - d)<br>    lattice_node = {}<br><br>    for m in range(num_time_steps + 1):<br><br>        S_node = initial_stock_price * (u ** (2 * m - num_time_steps))<br>        lattice_node[(num_time_steps, m)] = max(strike_price - S_node, 0)<br><br>    for k in range(num_time_steps - 1, -1, -1):<br>        for m in range(k + 1):<br><br>            cont_value = np.exp(-risk_free_rate * dt) * (q * lattice_node[(k + 1, m + 1)] + <br>                                                               (1 - q) * lattice_node[(k + 1, m)])<br>            <br>            S_node = initial_stock_price * (u ** (2 * m - k))<br>            exercise_value = max((strike_price - S_node), 0)<br>            lattice_node[(k, m)] = max(cont_value, exercise_value)<br><br>    return lattice_node[0, 0]</pre><h4><strong>Example: American Put Option</strong></h4><p>Here is an example of how to use the function:</p><pre>import numpy as np<br><br>expiry_time_val = 1.0<br>num_time_steps_val = 50<br>volatility_val = 0.2<br>risk_free_rate_val = 0.06<br>strike_price_val = 40.0<br>initial_stock_price_val = 36.0<br><br>option_value = binomial_put_option_pricing(expiry_time=expiry_time_val, <br>                            num_time_steps=num_time_steps_val, <br>                            volatility=volatility_val, <br>                            risk_free_rate=risk_free_rate_val, <br>                            strike_price=strike_price_val, <br>                            initial_stock_price=initial_stock_price_val)<br><br>print(f&quot;The option price using Binomial Lattice Method is: {option_value:.2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*y_sg17DmzX5OQ4fGKCsY-Q.png" /></figure><h3>Summary:</h3><ul><li>The blog post explains the concept of the Binomial options pricing model for fair pricing of options.</li><li>It provides a simple example in Python to demonstrate how to implement the binomial model for pricing options.</li><li>The option price is determined by the value of the option at the root node of the lattice.</li></ul><p>For exclusive insights on how to use AI /Reinforcement Learning for Option Pricing in Python, you can check out here:</p><p><a href="https://peymankor.gumroad.com/l/noyfhj">https://peymankor.gumroad.com/l/noyfhj</a></p><h3>Thanks for reading so far!</h3><p>I hope this article has provided an easy-to-understand tutorial on how to do a Binomial Option Pricing Model (BOPM) with Python.</p><p><em>If you think this article helped you to learn more, please give it a 👏 and follow!</em></p><h3>References</h3><p>[1]: Rao, A., &amp; Jelvis, T. (2022). <em>Foundations of reinforcement learning with applications in finance</em>. Chapman and Hall/CRC.</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Featured Article:</p><ul><li><a href="https://www.datadriveninvestor.com/2024/03/26/singapore-unveiling-a-tapestry-of-possibilities-and-global-connections/">Singapore: Unveiling a Tapestry of Possibilities and Global Connections | DataDrivenInvestor</a></li><li><a href="https://www.datadriveninvestor.com/2024/03/20/accelerating-success-through-the-singapore-fund-asset-management-platform/">Introducing Singapore&#39;s Fund Platform | DataDrivenInvestor</a></li></ul><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ff2af268e2" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/from-zero-to-hero-a-step-by-step-guide-to-binomial-option-pricing-in-less-than-30-lines-of-code-10ff2af268e2">From Zero to Hero: A Step-by-Step Guide to Binomial Option Pricing in Less Than 30 Lines of Code!</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forgot Solutions in Life. It’s All About Trade-offs (Here Is How to Master Them)]]></title>
            <link>https://medium.com/@peymankor/forgot-solutions-in-life-its-all-about-trade-offs-here-is-how-to-master-them-4cdbf3a8a395?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cdbf3a8a395</guid>
            <category><![CDATA[decision-making]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 17:49:45 GMT</pubDate>
            <atom:updated>2024-04-25T17:52:12.967Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Practical Guide on How to Manage Conflicting Objectives in Life’s Complex Decisions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ISOrjCbRXy_WA8K8" /><figcaption>Photo by <a href="https://unsplash.com/@saltsup?utm_source=medium&amp;utm_medium=referral">Piret Ilver</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p><strong>Life</strong> is full of though decisions. Imagine: you have have dream of buying a big, beatiful home but you do not spend all of your fortune on it. Or think about investing: you are tempted by high-return of high-growth stock market , but also you are woriied about risk involved. Sounds familiar,right? We all face such kind of trade-offs in our life.</p><p>In this blog , I want to help you how to manage such decisions. I am breaking down into a five-step process, from Step 1 to Step 5. Before you go, the graphical summary of the blog is here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6taDpIfYsO_tObzvu5wqg.png" /></figure><h4><strong>Decision-Making: A Daily Part of Life</strong></h4><p>Every day, whether we are aware of it or not, we are faced with decisions. We decide which house to buy, which car to buy, whom to spend our life with, and the list goes on.</p><h4>Luck and Decision in Life</h4><p>The quality of our lives (how much we enjoy them) largely boils down to two factors: <strong>Our Decisions</strong> and <strong>luck</strong>. Let’s talk about luck first. It is something we really can not control it. You can be lucky to have amazing weather during your summer vacation in Hawaii, but you may be unlucky to have bad weather when you go skiing in Austria. Luck (or bad luck) is out of our control.</p><h4>The Decision to Increase your “Luck Surface”</h4><p>You might think that you can “tilt” the odds in your favor (increase your “luck surface”). Sure, making certain decisions can broaden your opportunities for good luck ( posting your thoughts online, attending conferences, or going on blind dates).</p><blockquote>But again, that goes to choice/decision that you need to do to increase your “luck surface.”</blockquote><h4>What you can control in your life: Your Decisions</h4><p>What we can control/power is our decisions. Decisions we make in life in basic terms have three elements:</p><p>- <strong>Alternatives (What options do we have?)</strong></p><p><strong>- Uncertainty (What don’t we know for sure)</strong></p><p><strong>- Values (What we want to achieve?)</strong></p><p>The focus of this blog is on the “Values” — simply put, your “goals” in life. However, it is seldom that have only “one” goal in life.</p><blockquote>You want to achieve multiple goals in life. But, some of them are in conflict. When you gain one thing, you might have to give up another. That is called trade-off.</blockquote><h4>It is your Values that influence your decisions.</h4><p>Values (What you want to achieve) are overreaching, broad statements that are important to us. Our values are things that matter to us in the context of decision-making.</p><p>For instance, a public corporation’s value might be increasing shareholder wealth. In contrast, a national company might prioritize boosting the well-being of the country’s citizens.</p><h4>Understanding Values vs. Objectives</h4><p>But what’s the difference between values and objectives?</p><p>Objectives, also known as criteria, are usually verbs that describe the preferred direction of movement (maximize or minimize) of quantities that reflect high-level values.</p><p>An example of Values Vs. Objective and how to do tradeoff- is explained through an example of deciding on a job offer in the example below.</p><h3>Hands-on Example: Navigating Trade-offs in the Job Search Journey</h3><p>Imagine you are searching for a new job. Surely, you need to know beforehand, that what are your values?</p><blockquote>In another word, what are the high level “desires” you have that you want to accomplish through finding job?</blockquote><h4>Values in the Job Search Journey</h4><p>For deciding on what job to accept , you might prioritize values such as:</p><p><strong>- Be Financially Well<br>- Have a Good Work-Life Balance<br>- Enjoy the Work</strong></p><p>These are high-level statements (“Values”). In next steps, what you need is “Objectives”.</p><h4><strong>Objectives for Each Value:</strong></h4><p>Objectives (sometimes called criteria) are usually verbs that describe the preferred direction of the movements (maximize or minimize) of quantity that reflect the values.</p><p>In other words, for the value of “Be Financially Well,” the criteria that can define it is:</p><ul><li><strong>Monthly Salary</strong></li></ul><p>For the Value of “Healthy Work-Life Balance”, the following can be criteria:</p><ul><li><strong>Number of Vacations</strong></li><li><strong>Work from Home Option</strong></li><li><strong>Benefits</strong></li></ul><p>For the value of “Enjoy the Work,” the following can be the criteria</p><ul><li><strong>Professional Development</strong></li><li><strong>Supportive Manager</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*UqcOD974qF7-JAqaRSoWVg.png" /><figcaption>Values are high-level statements, whereas objectives are criteria that describe that value — Image Source: Author.</figcaption></figure><p>These “Objectives” will guide you in evaluating job offers based on how well the alternatives/option align with the objectives.</p><h3>Mastering Life’s Trade-offs: A Five-Step Process</h3><h3>Step 1) List out all objectives:</h3><p>The first step in deciding when there are multiple objectives is to list the objectives. For the example of the job-seeker, this is a list of objectives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*HT2jGYWcfJr0HxpaTRTmCg.png" /></figure><h4>Decision Matrix</h4><p>In this blog, I work on a case study from the book <strong>“Smart Choices: A Practical Guide to Making Better Decisions,”[1]</strong> where the book discusses Vincent Sahid’s Job decision.</p><p>In the book’s example, the job-seeker evaluates five potential job opportunities, labeled A, B, C, D, and E.</p><p>In the decision matrix below, we put a list of objectives on the left side of the matrix, where the column names are a list of jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKaO6d43p1Y5UF6wFXAV8g.png" /><figcaption>Decision Matrix for Job Seeker — Image Source: Author</figcaption></figure><p><strong>Evaluating Objectives:</strong></p><p>For each objective (rows), the decision maker (here, job-seeker) needs to evaluate each objective (row) versus all alternatives (columns). Some value of the rows can be “data” (like<strong> Number of Vacation</strong>) for each job,. However, some others, like “<strong>Supportive Manager,</strong>” can be a more subjective evaluation of the job seeker about each job.</p><h3>Step 2) Converting Description to Scales:</h3><h4>Converting Description to Scales:</h4><p>The decision matrix shows that some objectives have a “<strong>Descriptive</strong>” unit. They need to be converted to a “Scale.”</p><p>When converting <strong>“Description” to “Scale,”</strong> we can assign a zero value to the “status quo” (which can be the job-seeker&#39;s previous job situation) and then create a scale based on that reference point.</p><p>Three objectives in the previous table have a “Descriptive“ unit. Here, we are converting <strong>“Description to Scale”</strong> for the three objectives:</p><p><strong>Work From Home Option</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2Zd8E4Norah7wtZXIsi7Q.png" /></figure><p><strong>Benefits:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxBoh5NAAuKw77F833WYxQ.png" /></figure><p><strong>Supportive Manager</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaJYV2DU5Cj6LS34ZQFyug.png" /></figure><h4>The Decision Matrix Based on Scales:</h4><p>In the below decision matrix, all descriptive cells were replaced with scales for the three objectives, as in the previous three tables of conversion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9oM_OQK38Cw_ayX-n8v6A.png" /><figcaption>Decision Matrix for Job Seeker, all in scale units— Image Source: Author</figcaption></figure><h3>Step 3) Find the Swing Rank of Each Objective and Assign Weights</h3><p>Now that we have all table values in scale values, it is time to assign “Weight” to each objective.</p><blockquote>“Weight” is simply our preference between objectives. For instance, one person might prioritize “Monthly Salary” more than “Number of Vacation”. Such Preferences are personal, as people’s preferences are subjective.</blockquote><p>However, just assigning weight to each objective causes problems. The objectives should be ranked based on their importance in <strong>“distinguishing between alternatives”</strong>, not absolute measures.</p><p>Here, the “Swing Rank” comes into the picture.</p><h4>Swing Rank</h4><p>To find the swing rank of each objective, each objective is first considered based on two hypothetical alternatives: the worst possible payoff and the Best Possible Payoff.</p><p>Then, the highest rank is given to the objective representing the greatest percentage gain over its worst case.</p><p>Example:</p><p><strong>Monthly Salary :</strong></p><p>Best Alternative: 3400</p><p>Worst Alternative: 3000</p><p>Percentage gain: (3400–3000)/3000 = 13.3%</p><p><strong>Benefits</strong>:</p><p>Best Alternative: 2</p><p>Worst Alternative: -1</p><p>Percentage gain: (2-(–1))/1 = 300%</p><blockquote>The objective with the best score, representing the greatest percentage gain over its worst case, gets the highest rank (1). This ranking continues for the rest of the objectives.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVAXj5qgEfEpid0DqVfVDg.png" /><figcaption>Decision Matrix for Job Seeker, with Swing Rank — Image Source: Author</figcaption></figure><h4>Assigning Weights</h4><p>Having done the swing ranking, the decision maker assigns a weight of 100 to the number one ranked objective (based on swing rank).</p><p>Then, for the second objective, they ask themselves: <strong>relative to the first one, how desirable the increment from worst score to best score is?</strong> And they might decide 90. Then, repeat for the remaining objectives in order of their rank. (It is OK for two or more objectives to have the same rank)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehcM01NewcYbhQ7iW2JB0A.png" /><figcaption>Decision Matrix for Job Seeker, with Swing Rank and Weight— Image Source: Author</figcaption></figure><h3>Step 4) Converting Scores to Unified Values (0 to 100)</h3><p>We are not finished yet.</p><blockquote>We need to convert the scales to a common scale (like 0 to 100) so that the performance of each objective on multiple objectives can be combined.</blockquote><p>A linear value function can be used where the x-axis is the minimum and maximum value of the objective, and that can be converted to the y-axis, which takes a value between 0 and 100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5o_N_xstFsChPWHCvyH-pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TfHTWpXR2x8zuOsfaopAg.png" /><figcaption>Final Decision Matrix for Job Seeker— Image Source: Author</figcaption></figure><h4><strong>Weighted Overal Values of Each Alternative:</strong></h4><p>Now that the decision matrix is complete, with normalized weights and values scaled from 0 to 100, we can proceed to calculate the weighted sum for each job option.</p><p>For example, consider the calculations<strong> for Job A:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*gjT-SvGWzZa9X04e3meKCQ.png" /></figure><p>We can do the same to all alternatives to get the overall value of each job:</p><ul><li>Job A = <strong>66.59</strong></li><li>Job B = <strong>60.22</strong></li><li>Job C = <strong>36. 04</strong></li><li>Job D = <strong>55.44</strong></li><li>Job E = <strong>36.97</strong></li></ul><p>Each job is ranked according to their overall value. We employed a methodology that yielded a good or high-quality decision.</p><blockquote>The first ranked alternative(A, in this case) is the one logically consistent with maximizing the value of the decision.</blockquote><h3>Step 5) Assessing the Tradeoff between conflicting Objectives.</h3><p>In this part, we would like to do a tradeoff between two sets of objectives:</p><p><strong>On x-axis:</strong></p><p>We are considering the salary of each job alternative.</p><p><strong>On Y-axis:</strong></p><p>We are considering weighted benifits of all objectives except salary. Simply, we multiply the weight of each objective in each column, except the salary row.</p><p>Then, we can plot the data and locate the each job at it’s corropnding x and y axis place. As we know, job B has the highest monthly salary. But Job A has the highest benefits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_XSlG0mdcIOLECnlOHh9A.png" /><figcaption>Assessing tradeoffs between conflicting objectives — Image source:Author</figcaption></figure><h4><strong>Considering Trade-offs:</strong></h4><p>One way to consider trade-offs is by examining the shifts in x and y values when comparing two job options, such as moving from <strong>Job A to Job B</strong>.</p><ul><li>For instance, would you accept a $400 increase in monthly salary if it meant sacrificing 10 units of weighted benefit? (This case involves choosing a job that ranks third in terms of benefits other than salary.)</li><li>Alternatively, think about whether you’d be willing to give up $400 in salary each month to enjoy additional job benefits that are particularly valuable to you?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*oBvJoQkBff3OvRzQ1BVnrw.png" /><figcaption>Assessing tradeoffs between conflicting objectives — Image source:Author</figcaption></figure><h3>Takeaways:</h3><ul><li><strong>Know Your Values</strong>: Your personal values and objectives guide your choices, and you need to think about them for every significant decision you make in your life.</li><li><strong>Structured Evaluation: </strong>The five-step process in this blog provides a structured way of evaluating options and improving decision clarity.</li><li><strong>Differentiating Objective</strong>: When dealing with multiple objectives, consider not only their importance <strong>but also their ability to distinguish between alternatives.</strong></li><li><strong>Trade-off Thinking:</strong> Thinking in “Trade-off” will help you be more clear about your important decisions.</li></ul><p>Would like to end this blog with a quote from<strong> Thomas Sowell</strong>,</p><blockquote>There are no solutions but only trade-offs</blockquote><p>[1] Hammond, J. S., Keeney, R. L., &amp; Raiffa, H. (2002). Smart Choices: A Practical Guide to Making Better Decisions. Paperback edition.</p><p>[2]Bratvold, R. B., &amp; Begg, S. H. (Publication Year). Making Good Decisions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cdbf3a8a395" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Negative Thinking: Supercharge your Decision-Making Skill]]></title>
            <link>https://medium.com/@peymankor/the-power-of-negative-thinking-supercharge-your-decision-making-skill-c81782177f97?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c81782177f97</guid>
            <category><![CDATA[decision-making]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 14:16:44 GMT</pubDate>
            <atom:updated>2024-02-12T14:16:44.796Z</atom:updated>
            <content:encoded><![CDATA[<p>Maya Angelou, a well-known poet and civil rights activist, once wrote:</p><blockquote>“Hoping for the best, prepared for the worst, and unsurprised by anything in between”</blockquote><p>“Prepared for the worst” is a useful mindset to have in decision—making.</p><p>I really liked Angelou’s text and I am going to relate it something <a href="https://medium.com/u/d3a7cb4ec992">Annie Duke</a> wrote in chapter 8 of her book¹, titled “<em>The Power of Negative Thinking</em>”</p><p>You may assume thinking negatively is a bad idea. We should always think positively.</p><p>As the best-selling book “The Power of Positive Thinking”² says, we absorb what we think. If we think positively, we absorb positive results.</p><p>Well, there is a caveat here. It is important to distinguish the following:</p><blockquote>“ You need to think positively about the destination (goal) but think negatively about the route.”</blockquote><p>Thinking negatively here means: that for every goal/ decision you want to make, imagin<em>e “all the ways that you can fail” </em>to achieve that goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-d9xkNHCQWsj5Rnp" /><figcaption>Photo by <a href="https://unsplash.com/@kamilszumotalski?utm_source=medium&amp;utm_medium=referral">Kamil Szumotalski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Why Only “Positive Thinking” is Not Enough</strong></p><p>Let me give an example.</p><p>Your goal is to lose 10 kg weight in 2024. That is a positive goal, and you should definitely have such a positive goal and thinking.</p><p>But, now imagine all the ways that “<strong>You can fail to achieve this goal”:</strong></p><ul><li>You start eating healthier food, but then after a while, start snacking after dinner</li><li>You started a gym membership but, after a while, stopped it due to being busy with work</li></ul><blockquote>Surprisingly, research shows that thinking about “What Can Go Wrong in Our Plans” actually helps us to realize our goals easier.</blockquote><p>So “<strong>Only Positively Thinking</strong>” about our goal of “losing 10kg” is not enough.</p><p>It is not surprising that within a week, <em>23% of every New Year resolution is abandoned</em>, <em>and 90% are never achieved</em>.</p><p><strong>What is Negative Thinking</strong></p><p>The <strong>“Negative Thinking” </strong>is a powerful technique that I personally found can be very helpful in life.</p><p>It is a mental contrast:</p><blockquote>“You’d think positively about what your future is, but you think back all the way that you can not reach that future and see what all the obstacles are now”</blockquote><p>Now, you can ask what the roots of this failure are. It is about two ways that</p><ul><li><strong>Our Choices</strong></li><li><strong>Bad luck</strong></li></ul><p>Now, having figured out all the obstacles in the path, it is three essential benefits for achieving your goal:</p><h4><strong>How “Negative Thinking” will Help you Achieve your Goals Easier:</strong></h4><h4>1) Pre-Commitment Barrier</h4><p>Think about the reasons you fail to achieve your goal. Then, make a <strong>“pre-commitment”</strong> barrier that will prevent you from having that bad outcome.</p><p>For example, imagine you get a new job, and one thing you think will be an obstacle to doing your job is your relationship with your boss.</p><p>What you can to imagine in this possible scenario is to do all the precommitments you make to avoid it:</p><ul><li><strong>Have clear communication with your boss from the beginning</strong></li><li><strong>Setting expectations in the beginning</strong></li></ul><p>So, the pre-commitment barrier works in two ways.</p><blockquote>First, you raise the barriers to behavior/decisions that interface with your goal and encourage behavior that supports your success, all planned in advance.</blockquote><h3><strong>2) Avoiding Surprise</strong></h3><p>Our brain is not immune from a hot emotional state when dealing with bad outcomes.</p><p>When a bad outcome happens, it is much more likely that it will affect the quality of your decision-making.</p><p><strong>What-the-hell effect:</strong></p><p>Our decision-making can be compromised when we face a bad situation.</p><p>Imagine you decided to eat healthily. You are following your decision until one day, in the breakroom at your job, you see a couple of donuts. You just pick a couple of them. Then, following that day, you load up yourself with junk food, thinking you will start again the next day. next week…</p><p>This is the classical “<strong>What-the-hell-effect</strong>,” where one worse situation compromises your decision quality and affects all of your decisions.</p><blockquote>Thinking negatively in advance and recognizing all the ways we fail in advance help us to be “<strong>better prepared</strong>” to react rationally and avoid situations like “What the hell effect?”</blockquote><h3>Thinking Negatively about the Obstacles due to our Bad Luck:</h3><p>The outcome of your decision is not only influenced by your choices. It is influenced by luck, also.</p><blockquote>You can think in advance about all the obstacles to the decision that can happen due to bad luck.</blockquote><p>Let’s say you have always dreamed of having an outdoor wedding. And finally, you reserved the beautiful garden for your wedding.</p><p>Well, one problem in achieving your desired result can be the wedding day being rainy. It is just possible due to bad luck, out of our control.</p><p>Now, how does the <strong>Power of Negative Thinking</strong> help here? Well, knowing what can go wrong, you can start “Hedging” about your decisions in your life.</p><p><strong>“Hedging”</strong></p><blockquote>Hedging is simply making/generating an option that you hope you will never use.</blockquote><p>You only use it to mitigate the impact of big downsides in your decisions.</p><p>In the case of weddings in the garden, rain is a big downside. What option you make that you hope that you never use it but it mitigate the impact of rain?</p><p>Maybe renting and setting up a tent, in this case, maybe good hedging.</p><h3><strong>Main Take Aways:</strong></h3><ol><li>Positive Thinking is good for thinking about a “<em>Destination</em>”, but Negative Thinking is a much better approach for planning the “<em>Route</em>” to get there.</li><li>Research shows that “Negative” thinking about <em>all the obstacles in your way to achieving your goals</em> makes you find 30% more obstacles.</li><li>Finding more obstacles in the route to the destination “<em>in advance</em>” is a little of mental pain. <em>But, mental pain leads to real-world gains.</em></li><li>How thinking negatively about the route <em>actually</em> helps you achieve your goals:</li></ol><p>A) <em>It will force you to think about obstacles and figure out what steps you can take to avoid them</em></p><p>B) <em>Avoid surprises when bad outcomes happen, avoiding being in a “hot” emotional state.</em></p><p>6. Thinking about obstacles on the route to your goal helps you address potential bad luck by hedging: paying for something mitigates<em> the impact of unwanted outcomes.</em></p><p>[1]: <a href="https://www.amazon.com/How-Decide-Simple-Making-Choices-ebook/dp/B07TRJB3S3">How to Decide: Simple Tools for Making Better Choices</a>, 2020, Annie Duke</p><p>[2]: <a href="https://www.amazon.com/Power-Positive-Thinking-Norman-Vincent/dp/0743234804">The Power of Positive Thinking, 2003</a>, <a href="https://www.amazon.com/Dr-Norman-Vincent-Peale/e/B0BW6GYKVJ/ref=dp_byline_cont_book_1">Norman Vincent Peale</a>,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c81782177f97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Why There Is No Such Thing as ‘Correct Probability’ in Data Science]]></title>
            <link>https://pub.towardsai.net/understanding-why-there-is-no-such-thing-as-correct-probability-in-data-science-950c81629bcf?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/950c81629bcf</guid>
            <category><![CDATA[decision-intelligence]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[decision-making]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 12:01:38 GMT</pubDate>
            <atom:updated>2024-01-22T12:01:38.799Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Probability Should be Conditioned on your Current State of Information</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_pJvTM9PPh8KdwYD" /><figcaption>Photo by <a href="https://unsplash.com/@edge2edgemedia?utm_source=medium&amp;utm_medium=referral">Edge2Edge Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p>In the field of data science, individuals frequently use the term “<strong>Probability</strong>”. However, a fundamental concept needs to be emphasized:</p><blockquote>There is no such thing as a Correct Probability in Data Science.</blockquote><p>Let’s go a little deeper. We heavily rely on building machine learning models that give the probability of future events.</p><p>For example, what is the probability of the next person defaulting on a bank loan?, or what is the probability of a particular transaction being fraudulent?</p><h3>Uncertainty Vs. Variability:</h3><p>One common confusion I see is to recognize the difference between two terms, <strong>uncertainty and variability.</strong></p><blockquote><strong>Confusion comes from the point both Uncertainty ad Variability can be expressed in terms of probability, but they are different concepts.</strong></blockquote><h4>Variability</h4><p><strong>Variability is a state of things: </strong>It is quantified by the frequency of observed actual value.</p><p>For example, you can quantify the variability of the height of 100 students at the high school by plotting the probability mass function of the 100 data points.</p><h4>Uncertainty</h4><p><strong>Uncertainty is a state of mind: </strong>It is quantified by the probability of a future event being true or not.</p><p>In the previous example, when we want to assign a probability to the height of the next person (101) who hasn’t been measured yet, here we are in the realm of uncertainty.</p><h3>Uncertainty Comes from Person</h3><p>In probability classes, you might heard the term <strong>“fair coin.” </strong>Well, the<strong> </strong>reality is that the factory producing the coin may not necessarily be concerned with ensuring the coin is perfectly fair.</p><p>It is <strong>our assumption, our belief</strong>, that the probability of coming head or tail is equal.</p><p>Probability is nothing more than our degree of belief, and it is much more useful to think about it as a <strong>measure that is conditioned on the current state of information we have.</strong></p><p>Imagine two analysts sharing their weather predictions for tomorrow. One person suggests that there is a 70% of rain tomorrow, while another predicts a 50% chance.</p><p>Now, suppose tomorrow it rains. Who was correct? They both were. If it does not rain, they are still both equally correct.</p><p>There’s no such thing as an<strong> “actual probability “ </strong>of rain; each person presented a belief about the chance of rain, <strong>conditioned on the state of information they had.</strong></p><h3>Bayesian Example: What is the Probability of Rain Tomorrow?</h3><p>Imagine that I want to forecast the probability of rain in my city tomorrow.</p><p>I can simply look at the previous year and see how many days of January were rainy. Say it was 20 days. Now, with this information, I can assign the probability of rain for tomorrow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*F0655Z4o9vmF-NfDW3-Zhg.png" /><figcaption>Image Source: Author</figcaption></figure><p>Now you just check the weather forecast, and it predicts<em> heavy clouds and high humidity</em>, which historically are <strong>associated with a 70% chance of rain.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*vCmCaJDrd_y2zpZqmXBztg.png" /><figcaption>Image Source: Author</figcaption></figure><p><strong>Now, this is a new information</strong>. As we said,<em> probability is just the state of information, and it changes when the information we have changes.</em></p><p>We can do simple Bayesian flipping to update our belief:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*w81tpER1dr6E9KyfN6lWtw.png" /><figcaption>Image Source: Author</figcaption></figure><p>Now the probability of Rain (with weather forecast info) is around <strong>0.82</strong>, which is different from what it was in the beginning when it was 2/3 (<strong>0.66</strong>).</p><blockquote>The more information we receive, the probability we assign to the uncertain event changes, making probability a measure of the state of information.</blockquote><p><strong>Here is a simple Python code to reproduce the example:</strong></p><pre>prior_prob_rain = 20/30<br><br>print(f&quot;Prior Probaility of Rain: {prior_prob_rain}&quot;)<br><br>prob_heavycloud_rain = 0.7<br>prob_heavycloud_norain = 0.3<br><br># Calculate the total probability of heavy cloud<br>prob_heavycloud = prior_prob_rain * prob_heavycloud_rain + (1 - prior_prob_rain) * prob_heavycloud_norain<br><br># Calculate the updated probability of rain<br>updated_prob_rain = prior_prob_rain * prob_heavycloud_rain / prob_heavycloud<br><br># Print the results<br>#print(f&quot;Total Probability of Heavy Cloud: {prob_heavycloud}&quot;)<br>print(f&quot;Updated Probability of Rain: {updated_prob_rain}&quot;)</pre><h3>Main Message:</h3><p>The main message I wish to convey is about assigning probabilities to uncertain events.</p><blockquote>Two data scientists can, legitimately, assign different probabilities to an uncertain event if they have different information or process the same information differently.</blockquote><p>Probability is <em>subjective</em> and <em>personal</em>. There is not “the” probability but rather “a probability”, and probability is <strong>conditioned on the current state of information we have.</strong></p><h3>References:</h3><ul><li>[1] <a href="https://www.amazon.com/Foundations-Decision-Analysis-Ronald-Howard/dp/0132336243">Foundations of Decision Analysis</a>, Ronald Howard (Author), Ali Abbas (Author)</li><li>[2] I appreciate the insightful dialog I had with Professor Reidar Brumer Bratvold and Professor Steve Begg. <a href="https://www.amazon.com/Making-Good-Decisions-Reidar-Bratvold/dp/1555632580">Their book on making good decisions</a> will be a valuable resource to explore.</li></ul><p><em>If you think this article helped you to learn more about this topic, please give it a 👏 and follow!</em></p><h3>Resources:</h3><h4><a href="https://linktr.ee/peymankor"><strong>Connect with Me</strong></a>| <a href="https://topmate.io/peyman_kor/692694"><strong>Book a Free Call with Me</strong></a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=950c81629bcf" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/understanding-why-there-is-no-such-thing-as-correct-probability-in-data-science-950c81629bcf">Understanding Why There Is No Such Thing as ‘Correct Probability’ in Data Science</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging the Gap: Integrating Data Science and Decision Science through Six Essential Questions]]></title>
            <link>https://pub.towardsai.net/bridging-the-gap-integrating-data-science-and-decision-science-through-six-essential-questions-1747eff7487d?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1747eff7487d</guid>
            <category><![CDATA[decision-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[decision-making]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 14:06:00 GMT</pubDate>
            <atom:updated>2024-01-28T22:26:47.665Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Science is the discipline of making data useful — But How?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*F2UPh3IOwQ3vOkSz9ve6Xg.jpeg" /><figcaption>Image Source: Stablecog</figcaption></figure><h3>Intro</h3><p>It has been now more than one decade since <em>Thomas H. Davenport</em> and <em>DJ Patilthree</em> wrote their famous <a href="https://hbr.org/2012/10/data-scientist-the-sexiest-job-of-the-21st-century">Harvard Business Review article</a>:</p><blockquote>“<em>Data Scientist: The Sexiest Job of the 21st Century</em>”</blockquote><p>The article made many discussions, and now, after a decade, we have thousands of job profiles titled “Data Scientist.”</p><p>Many organizations have embraced the idea of having an analytic team in their structure.</p><p>Yet, it is a little bit surprising to see that according to <a href="https://www.gartner.com/en/newsroom/press-releases/2015-09-15-gartner-says-business-intelligence-and-analytics-leaders-must-focus-on-mindsets-and-culture-to-kick-start-advanced-analytics"><strong>Gartner report</strong></a> estimated that:</p><blockquote>“ 60 percent of <a href="http://www.gartner.com/it-glossary/big-data/">big data</a> projects will fail to go beyond piloting and experimentation, and will be abandoned.”</blockquote><p>In this blog, I reflect on how the field of Data Science/analytics can meet expectations and fulfill the anticipated value.</p><h3>Main Hurdle for Analytics in the Next Decade?</h3><p>I believe the main challenge facing the analytics field in the upcoming decade will involve <em>reducing the gap between “Time Spent Analyzing Data” and the actual “Value Creation” with data within organizations.</em></p><h3>Decision Intelligence</h3><p>Then, how can data be used for “value creation”? Well, the field of “Decision Analysis,” or a more refined one proposed by Cassie Kozyrkov&#39;s “Decision Intelligence” [1], has some answers on how to “Create Value.”</p><p>When we go to the literature on Descion Anlaysis [2] , <strong>we see that value can be created through high-quality decisions</strong>. Well, you may say that “chance” plays a role too.</p><blockquote>Sure, but the “High Quality” decision is the only way you can “purposefully” create value.</blockquote><h3>Role of Data Scientist: Making Data Useful for Decision-Making</h3><p>Thus, my suggestion is that the role of data scientist/analyst should be centered around framing the decision context within organizations.</p><p>Then, that enables business leaders/managers to make informed, “high-quality” decisions.</p><p>It is important to note that often, data scientists/analysts do not make final decisions. <strong>But, by using their analytic capability, they can function as context providers to make high-quality decisions.</strong></p><h3>Then, What is a “High-Quality” Decision?</h3><p>To answer the question of what constitutes a “High-Quality” decision, we first understand the main six elements of any “decision.”</p><ol><li><strong>The decision-maker;</strong></li><li><strong>A Frame;</strong></li><li><strong>Alternatives from which to choose;</strong></li><li><strong>Preferences;</strong></li><li><strong>Information; and</strong></li><li><strong>The logic by which the decision is made</strong></li></ol><p>The six elements of decision make a mental framework for “high-quality” decisions with six questions, <strong>and the quality of the decision depends on the quality of your answer to these six questions.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*JJ5rXgW3DQPUO5sSseawKQ.png" /><figcaption>Elements of A High-Quality decisions — Source:Author</figcaption></figure><p>I will explore these six questions. This approach will help analytic professionals <strong>make decisions within organizations that optimize for value creation.</strong></p><h3>Six Questions for Achieving High-Quality Decisions</h3><h4>1. Decision Maker: Who is the Decision Maker?</h4><p>The first thing that is crucial for data scientists to know is <strong>who the decision maker is</strong>. Often, data scientists themselves are not the decision-makers. Instead, they provide decision context to business managers and leaders.</p><p>In many cases, the decision maker is not one person but rather multiple. In many decisions, you may have a partner who needs to make decisions together, or you have a customer who is a stakeholder.</p><blockquote>Every decision needs a decision maker—the person who makes the decision and also commits to act.</blockquote><h4>2. Right Frame: What am I Deciding?</h4><p><strong>The way you <em>view</em> a decision is “Frame.” </strong>Depending on how you frame the decision, you may address different decision contexts, hence making different choices.</p><p><strong>Example:</strong></p><p>Imagine that you are part of the data science team at a retail company. Your company is considering enhancing its customer experience through personalized recommendations. Two frames for this decision can be:</p><p><strong>Frame A</strong>: The decision is whether to build an in-house recommendation system or buy a machine learning platform from external resources.</p><p><strong>Frame B</strong>: The decision has already been made to buy a recommendation system from external resources (service provider); now, the choice is whether to use the service of provider X or Y.</p><blockquote>As you can see, each framing provides a different view of the decision problem to be addressed.</blockquote><h4><strong>3. Right Alternatives: What Are My Choices?</strong></h4><p>When you build your frame, that frame will lead to the creation of alternatives appropriate to the frame.</p><p><strong>Making any high-quality decision involves considering substantially different alternatives.</strong></p><p>Sometimes, you have only one alternative to choose from.<em> In that case, it means that you do not have a choice to make, and you do not have a decision to make.</em></p><p>Also, you may face some cases where the decision involves a small, limited set of alternatives. In this case, skilled scientists and analysts can be very beneficial. The data science team can provide a new “creative” alternative to the leaders, one that was not initially considered.</p><blockquote>Within any organization, teams that come up with new “alternatives” are valuable assets. This is where the data science team can truly shine.</blockquote><h4>4. Right Values: What Consequences Do I Care?</h4><p>Every decision-maker will have “preferences” for the future come from various alternatives.<strong> The preference is “What do you want to achieve?”</strong>.</p><p><strong>If you are indifferent to the possible outcomes of the decision, then there would be no need to make a decision.</strong></p><p>In the words of Lewis Carroll:</p><blockquote>“If you don’t know where you are going, any road will get you there”.</blockquote><p>If you don’t discuss your values and what you want to achieve, the decision-making process is just wasteful.</p><h4>5. Right Information: What do I Need to Know?</h4><p>Information serves as a link between what we can do and what we want. Simply put, our alternatives lead to outcomes.<em> But there is uncertainty in the outcome of each option we make in decisions.</em></p><p>Often, we need to make decisions with incomplete information, meaning making decisions in the face of uncertainty.</p><blockquote>However, we are always tempted to get more information, yet information costs resources. A high-quality decision ensures gathering (buying) information is neither overdone nor underdone.</blockquote><h4>6. Right Reasoning: Am I Thinking Straight About This?</h4><p>Finally, we need to derive some process to make a decision. The final decision is based on what we know, what the choices are, and what we know.</p><h3>A Key Lesson:</h3><p>A data-driven organization would embrace the value of good data-driven decision-making.</p><p>Yet, data-driven decisions <strong>are not only about data</strong>. Organizations also need awareness about the science and practice of decision-making to maximize value creation.</p><p><strong>A starting point</strong> to understand the decision-making practice can be: <strong>What is a high-quality decision? And what are the elements of high-quality decision?</strong></p><blockquote>This blog offers an overview of the essential questions that must be addressed to facilitate the high-quality decision making.</blockquote><h3>Takeaway Messages:</h3><ul><li>Cassie Kozyrkov, in her LinkedIn “Decision Intelligence” course[3], defines“Data Science is the Discipline of Making Data Useful.” But How?</li><li>The primary focus of the data team should be on how to facilitate making “high-quality” decisions, irrespective of the potential outcome.</li><li>Achieving a high-quality decision requires ensuring that the six questions raised earlier have been answered correctly.</li><li>These six questions form a decision-making chain. It is a chain of six questions as links. <strong>The notion here is that the “Chain” is only as strong as its weakest link.</strong></li><li>The <strong>quality of a decision is as strong as its weakest answer </strong>to each question (each link).</li></ul><h3><strong>References</strong>:</h3><ul><li>[1]:<a href="https://towardsdatascience.com/introduction-to-decision-intelligence-5d147ddab767"> Introduction to Decision Intelligence</a>, Cassie Kozyrkov, 2019</li><li>[2]: <a href="https://www.amazon.com/Foundations-Decision-Analysis-Ronald-Howard/dp/0132336243">Foundations of Decision Analysis</a>, Ronald Howard (Author), Ali Abbas (Author)</li><li>[3]: Decision Intelligence Linkedin Course, Cassie Kozyrkov, 2023</li></ul><h3>Connect with Me:</h3><p><a href="https://linktr.ee/peymankor"><strong>https://linktr.ee/peymankor</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1747eff7487d" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/bridging-the-gap-integrating-data-science-and-decision-science-through-six-essential-questions-1747eff7487d">Bridging the Gap: Integrating Data Science and Decision Science through Six Essential Questions</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insights from Invaluable: How to Find Your Unique Values to a Purposeful and Aligned Life?]]></title>
            <link>https://medium.com/geekculture/insights-from-invaluable-how-to-find-your-unique-values-to-a-purposeful-and-aligned-life-e7796d209440?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7796d209440</guid>
            <category><![CDATA[decision-making]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 19:50:49 GMT</pubDate>
            <atom:updated>2023-12-29T11:31:59.096Z</atom:updated>
            <content:encoded><![CDATA[<p>A summary of my thoughts on “Invaluable” book by Somik Raha, on how both individuals and organizations can discover their core values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_uq18PTsV10Vpbsm1VDTQ@2x.jpeg" /><figcaption><a href="https://www.amazon.com/Invaluable-Achieving-Clarity-Somik-Raha/dp/B0C9SLCPWT">Invaluable Book </a>— Image Source: Author</figcaption></figure><h4>Intro :</h4><p>I have been studying the field of “Decision Analysis” now for almost 5 years. The “Decision Analysis” is all about how to make good decisions in life. Whether it is good or bad, our decisions are the only way by which we can control our lives.</p><p>In simple terms, making a good decision is based on three elements: 1) <em>What are the options in hand</em>, 2) <em>what are the uncertainties</em>, and 3<em>) What we want to achieve</em>.</p><p>Let me give one example. Picture this: You are thinking about your 2024 summer vacation and trying to decide where to go. How would you make that choice?</p><p>Let’s explore three elements that we discussed for this decision:</p><ol><li><em>What are the options</em>: Spain, Japan, Italy (for example)</li><li><em>What are uncertainties:</em> Weather ( how the weather will be during your vacation)</li><li><em>What you want to achieve</em>: Maximize exposure to good weather and enjoy the sun (for example)</li></ol><p>Given this frame and the three elements of the decision, a rational decision can be made.</p><p>During my work on making good decisions, I found that many individuals and organizations really struggle with the last part, which is:</p><blockquote>What (Truely) you want to achieve?</blockquote><p>That essentially boils down to identifying your “Values”. Because fundamentally, you want to achieve something that truly matters to you.</p><p>When I first heard about the. <a href="https://www.amazon.com/Invaluable-Achieving-Clarity-Somik-Raha/dp/B0C9SLCPWT#customerReviews">“Invaluable” book</a>, I felt that Somik Raha really touched the main bottleneck. I do believe he did an excellent job of addressing how to find values.</p><p>Somik also comes from a Decision Analysis background, and I am happy that a fellow from the society (Decision Analysis) has addressed this topic so well.</p><h4>Why We Need to “Clarify” Our Values in Life?</h4><p>As the the subtitle of the book indicates, “Achieving Clarity on Value” is in fact highly related to the question of “What to Do in Our Life?”.</p><p>Because let&#39;s be honest, being human is a complex thing. You wake up every morning, and there are 100s of directions that you can go. Which direction in life to go, is a recurring question in the minds of individuals and even organizations.</p><p>As Somik points out, the direction you need to go in life is the direction that is truly aligned with your values.</p><blockquote>You need to locate to focus of your life and energy on your values</blockquote><p>However, “Values” are not something that in place, and can be easily recognized and to be known.</p><p>It is a “Process” you need to go to understand your true value, which is that your value, can be very different from any other individual.</p><p>A wonderful book by Somik Raha, and here’s a brief summary and my take on it in a shorter version. I hope you catch the essence of it.</p><h4>Need to Bring Human Value to Technology:</h4><p>Technology has evolved with tremendous peace in previous decades. Just look at Artificial intelligence (AI) and all the discussion about the ChatGPT and large language models.</p><p>Technology almost outpaced the evolution of the human spirit. A lot of discussion on how to make AI even more efficient, but technology like AI is just a tool.</p><blockquote>What we are missing is a human touch, on how to bring human values to the center of discussion in the realm of technology.</blockquote><p>But then you may say in business or technology, there is no rule for spirituality or philosophical discussion. For businessman, who cares about spirituality and human values?</p><blockquote>Well in fact, as Somik (Author) explains, it is an intersection of business and philosophy, where business and work become <strong>meaningful</strong> and <strong>alive</strong>.</blockquote><h4>What is the Purpose of Business?</h4><p>Let&#39;s go back to business and the purpose of business:</p><blockquote>The purpose of business is to be a canvas for our unique service.</blockquote><p>Two words are critical here:</p><p>First is <em>service</em>, which is the act of serving others, and in more depth<strong>,</strong> serving in a way that makes other people&#39;s lives better.</p><p>Another is <em>Unique</em>, which means that there is a unique condition in us that goes beyond us and only “You” can do that service.</p><h4>What is Wrong with Profit as Business Value?</h4><p>But it might seem odd because, in the business domain, profit is king. How do we maximize profit? CEOs worldwide often ask themselves, ‘How can we make the most profit?’”</p><blockquote>It turns out that optimizing for profit metric suffers from a fundamental issue, the profit metric does not create profit, only how to measure it.</blockquote><p>Ok, now we see that Profit is not a practical metric because it does not create profit.</p><h4>What Could be a More Meaningful Substitute for Business Value other than just Profit?</h4><p>So, how do you discover values that serve business as a guide for decision-making, how can you be sure that these are the <strong>right values?</strong></p><blockquote>What we should value is: That protect and preserves life</blockquote><p>Honestly, I am somehow shocked to hear this from Somik. Life??</p><p>It is really about how to bring philosophy and spirituality into business, which is what makes business alive and meaningful.</p><h3>What to Do With Your Life?</h3><p>I would say the same philosophy applies to individuals, too. What is the deep intrinsic value of life?<em> The one that protects and preserves life</em>.</p><p>Let me elaborate on it more. The deep intrinsic purpose of life is how to improve the well-being of yourself and others. When you’re involved in activities that contribute to the well-being of others, you’re tapping into life’s intrinsic purpose, which is Giving Life!</p><p>Let me give some examples.</p><p>Have you ever asked why you brush your teeth twice a day? Brushing your teeth twice a day is an input metric that drives action (you are taking action). But Why? Why do we brush our teeth? We brush our teeth because it leads to dental health. But why does dental health matter? It matters because it leads to our well-being. Your well-being matters because it leads to life, and life matters, because life is the deep, intrinsic value of life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOjC51BOpfM4dsknT8ZsoQ.png" /><figcaption>Both systemic and extrinsic value ends in Intrinsic value of life — Image Source: Author</figcaption></figure><p>Another example is imagine a fitness trainer. The fitness trainer will assign the rules, like eating X grams of protein every day, X number of steps to walk per day, or …. These are just rules that drive action (Systemic Value). What does this rule lead to? It leads to the health of the person. What does health mean? it means preserving and protecting the life of the person (well-being of the person), which is a deep, intrinsic value.</p><h4>But you are a UNIQUE individual</h4><p>So, I wrote that the well-being of yourself and others is the deep intrinsic value of life.</p><blockquote>But, deep satisfaction for the individual comes from their uniqueness.</blockquote><p>It means that they are conditioned so uniquely that ONLY you can discover your core values that are aligned with life&#39;s purpose.</p><p>Nobody can be You! Your genetics, background, and life experience all make you a unique person.</p><p>So, being unique, you need to find your “Unique” value that makes “space” for you to deliver life value.</p><p>Your values in your life that must be targeted consist of three parts:</p><ul><li>Your<strong> Heart </strong>Value</li><li>Your<strong> Habit </strong>Value</li><li>Your<strong> Head </strong>Value</li></ul><p>You need to find your Heart, Habit, and Head Value.</p><blockquote>You may need to put focus on your work life on the path that is blend of your Heart, Habit and Head Value.</blockquote><p>So far easy, at least to say it. But, how to find them? how to find my heart value, head, and habit value? well…I agree it is a process…it is a bloody process… Sometimes it can take decades.</p><blockquote>But once you arrive at your deep value, then every moment of life becomes such joy that you want to go to sleep, looking forward to start tomorrow and living a life in alignment.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tufr-_INJbNsg7qMSsxA4g.png" /><figcaption>Three parts of the “core value “— Image Source: Author</figcaption></figure><h4>How to Find Your Heart Value:</h4><p>To find your heart value, you really need to listen to your emotions and feelings. Your heart value should be something you and others can be inspired.</p><p>Two useful questions to find your heart value can be : (use your feelings and emotions to answer these two questions)</p><p>-<strong> Reflect on times you got a thrill of joy through your work. What was the thrill about?</strong></p><p>- <strong>Reflect on the times you have felt “proud about your work”. What made you proud?</strong></p><blockquote>Your heart value is very important. It is something that when you work toward it, you feel a sense of “creative joy”.</blockquote><h4>How to Find Your Habit Value:</h4><p>Habit value is an interesting thing because when it gets discovered, it will be your <em>superpower. </em>It is deep inside habit when you show up, that habit shows up too.</p><p>Two useful questions to find your habit value can be:</p><p>- <strong>What is a habit pattern people have noticed you since you were a child?</strong></p><p>- <strong>What is something you have not been able to stop, even when people have asked you?</strong></p><blockquote>Your habit value is not <em>decision</em>, it is a repeated pattern in you. It is not a thoughtful habit you have, it is a pattern that just comes out of you naturally.</blockquote><h4>How to Find Your Head Value</h4><p>Your head value is the place you are going to create through your hard work and time.</p><p>Two useful questions to find your head value can be:</p><ul><li><strong>In what profession or area, are you an expert?</strong></li><li><strong>What is something (subject/topic) you are drawn to it?</strong></li></ul><p>Here what I mean by drawn is not what your background is. For example, you may have an education in computer science, but you are drawn into understanding human and computer interaction.</p><blockquote>The word drawn here means what is topic/area the more you read, the more you become interested.</blockquote><h4><strong>Blend Your Heart + Habit + Head Value. You arrive at your True Value!</strong></h4><p>Your true value in your life is a blend of your Heart, Head, and Habit value. In simpler and easier terms your value in life is a combination of your motivation (heart value) + skill (habit value) + knowledge (head value)</p><p>Note that only you know when you arrived at your values, and it’s your values and can be very different from another person&#39;s values. This is important to note because people make different life choices simply because values are different.</p><h3><strong>Story of Mary:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aUc7QNkxrqZI36m9MSPK-g.png" /><figcaption>Mary’s Value Mapping — Image Source: Author</figcaption></figure><p>An interesting story in the book is about Mary, a lady who had a career in Mergers and Acquisitions in a corporate structure. While successful in her corporate ladder, she was considering doing something else that would be aligned more with her values.</p><p>The same process (value-mapping) that I explained on finding heart, head, and habit values was done. After talking the author (Somik) with the Mary, the following found the values of Mary:</p><p><strong>Mary’s Heart Value is:</strong></p><ul><li>Mary’s creative joy was around helping people on their healing journey. So her Heart Value was noted as: <strong>“Helping people on their healing journeys.”</strong></li></ul><p><strong>Mary’s Habit Value:</strong></p><p>At the same time, Mary found it in herself easy to get detached from other people. So her Habit Value was noted as:<strong> “Avoiding attachment.”</strong></p><p>Given these two values, it was suggested that maybe a therapist line career is something Mary can consider as her career. She decided on that. After some years of conversation, Mary’s life was in a very different direction. Mary’s work was a space for “creative joy”. Later, Mary refined her career further and went to “Love Coach”. <br>This is an example of how following heart and habit values puts you in the direction that you can further refine and find your head value. Mary was able to create a “Love Coach” distinction for her head value.</p><h3>Summary</h3><ul><li>Being human is complex. Each morning, you wake up with countless directions to choose from, thinking about a recurring question: “<em>Which direction should I take in life</em>?”</li><li>The direction you need to go is the one aligned with your values. Then, what is your true value in your life? - In the big picture, the deep, intrinsic, moral value in life is how to bring well-being to yourself and, more importantly, other humans.</li><li>In simpler terms, the intrinsic value of life is life! Life of you and others.</li><li>Human individuals need to find a blend of their heart, head, and habit values.</li><li>Your heart value is what brings you “creative joy” out of doing, your habit value is what is something that “shows in you naturally,” and your head value is the “source of your knowledge”.</li><li>You need to mix your heart value (motivation), habit value (skills), and head value (knowledge) to find the center of your emotional energy in your life.</li><li>In the end, all I wrote was easy to say but hard to do :) . Finding your true value in life is a process, sometimes a bloody process. It can take decades…Though like every thing else in life, the path becomes more clear when you START!</li></ul><h3>Link to Buy Invaluable Book:</h3><p><a href="https://www.amazon.com/Invaluable-Achieving-Clarity-Somik-Raha/dp/B0C9SLCPWT">https://www.amazon.com/Invaluable-Achieving-Clarity-Somik-Raha/dp/B0C9SLCPWT</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7796d209440" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/insights-from-invaluable-how-to-find-your-unique-values-to-a-purposeful-and-aligned-life-e7796d209440">Insights from Invaluable: How to Find Your Unique Values to a Purposeful and Aligned Life?</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inventory Optimization with Dynamic Programming in Less than 100 Lines of Python Code]]></title>
            <link>https://pub.towardsai.net/inventory-optimization-with-dynamic-programming-in-less-than-100-lines-of-python-code-ab1cc58ef34c?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab1cc58ef34c</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[inventory-management]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 20:16:21 GMT</pubDate>
            <atom:updated>2023-12-24T14:44:33.650Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>How to master inventory decisions using dynamic programming for maximum profitability</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ek7_rs6jaXR0if0RsCyJfw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@christinhumephoto?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Christin Hume</a> on <a href="https://unsplash.com/photos/pile-of-assorted-color-bikes-on-concrete-pavemenet-zbUH21c9ARk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Intro</h3><p>Inventory optimization is a broad problem that arises across many domains. The central question is all about figuring out:</p><blockquote>“How many products to order for your store periodically, in order maximize the profitability?”</blockquote><p>I think you are a bike shop manager. Every day, you need to contact your supplier to order a number of bikes for your store. If you order too many bikes daily, you will spend<strong> too much money on maintaining and keeping the bikes in the store</strong>. On the other hand, <strong>if you order fewer, you might not have enough bikes to meet customer demands</strong>. You need to have an “ordering strategy” that balances two factors.</p><p>We will break down this problem and find the optimal “ordering strategy”. The “optimal ordering strategy” is based on three pillars:</p><ul><li><strong>Markov Process</strong>,</li><li><strong>Markov</strong> <strong>Rewards Process</strong></li><li>and <strong>Markov Decision Processes</strong>.</li></ul><p><a href="https://pub.towardsai.net/inventory-optimization-with-data-science-hands-on-tutorial-with-python-f49633fdd19a">Here</a> and <a href="https://pub.towardsai.net/inventory-optimization-with-data-science-hands-on-tutorial-with-python-1360ef044f18">here</a>, I covered how to frame the “inventory optimization” problem, the Markov Process, and the Markov Reward Process.</p><h3>Framing the Inventory Optimization Problem</h3><p>Inventory Optimization is a Sequential Decision-Making Problem. We can frame this problem by defining what the states are, uncertainties, and what the **<strong>recurring decisions</strong>** are.</p><ol><li><strong>State:</strong></li></ol><p>The state (<strong>the internal representation of the process</strong>) can be described by two components:</p><ul><li><strong>α</strong> : is the number of bikes you already have in store</li><li><strong>β</strong> : is the number of bikes that you ordered the previous day and will arrive tomorrow morning (these bikes are on a truck)</li></ul><p><strong>2. Uncertainty:</strong></p><p>In this example, uncertainty is random demand demand modeled following Poisson distributions (with Poisson parameter λ∈R&gt;). A demand of i bikes for each i=0,1,2⋯ occurs with probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GSHKvaW4GDeB3wIB.png" /></figure><p><strong>3. Decisions:</strong></p><p>In this example, the bike shop owner must decide every day at 6PM, on how many bikes to order from the supplier.</p><h4><strong>Sequence of 24-hr cycle</strong></h4><p>The sequence of events in a 24-hour cycle for this bike shop is as follows:</p><ol><li><strong>At 6 PM</strong>: you observe the state S_t:(α,β)</li><li><strong>At 6 PM</strong>: you order the new bikes</li><li><strong>At 6 Am</strong>: You receive bikes that you ordered 36hr ago</li><li><strong>At 8 AM</strong>: You open the store</li><li><strong>From 8 Am to 6 PM</strong> you experience demand i during the day (modelled using Poisson distribution) more below.</li><li><strong>At 6 PM</strong> you close the store</li></ol><p>The diagram below visualizes this sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1t71XhYIYZTXcDpCQ9XU-A.png" /></figure><p>In this blog, we are going to summarize everything and connect the Markov Process and Markov Reward Process with the Markov Decision Process to arrive at the optimal “ordering strategy”, all with codes in Python.</p><h3><strong>Markov Decision Process:</strong></h3><p>Markov Decision Process (MDP) is a mathematical model whose key components are states, actions, transition probabilities, and rewards.</p><p>In the Markov Reward Process, <em>the decisions were fixed</em>, and we were not considering all possible actions for each state. In Markov Decision Process (MDP), we need to build a data structure that for each state, we need to consider all possible actions, and following the $(S_t,A_t)$, we need to know what will be $(S_{t+1}, R_{t+1})$.</p><p><strong>Example of Markov Decision Process Data Structure</strong></p><p>Here, I am giving you an example of an MDP dictionary, where you can see for each state, all possible actions need to be considered:</p><pre><br>MarkovDecProcessDict = {&quot;Current State A&quot;:{&quot;Action 1&quot;:{(&quot;NextS1fromAact1&quot;, &quot;Reward1&quot;): &quot;PNextS1fromAact1&quot;<br>                                           ,(&quot;NextS2fromAact1&quot;, &quot;Reward2&quot;): &quot;PNextS2fromAact1&quot;},<br>                                           &quot;Action 2&quot;:{(&quot;NextS1fromAact2&quot;, &quot;Reward2&quot;): &quot;PNextS1fromAact2&quot;<br>                                           ,(&quot;NextS2fromAact2&quot;, &quot;Reward2&quot;): &quot;PNextS2fromAact2&quot;}},<br>                    <br>                     &quot;Current State B&quot;:{&quot;Action 1&quot;:{(&quot;NextS1fromBact1&quot;, &quot;Reward1&quot;): &quot;PNextS1fromBact1&quot;<br>                                           ,(&quot;NextS2fromBact1&quot;, &quot;Reward2&quot;): &quot;PNextS2fromBact1&quot;},<br>                                           &quot;Action 2&quot;:{(&quot;NextS1fromBact2&quot;, &quot;Reward2&quot;): &quot;PNextS1fromBact2&quot;<br>                                           ,(&quot;NextS2fromBact2&quot;, &quot;Reward2&quot;): &quot;PNextS2fromBact2&quot;}}<br>}<br><br>for current_state, actions in MarkovDecProcessDict.items():<br>    print(f&quot;Current State: {current_state}&quot;)<br>    <br>    for action, transitions in actions.items():<br>        print(f&quot;  Action: {action}&quot;)<br>        <br>        for (next_state, reward), probability in transitions.items():<br>            print(f&quot;  ({next_state},{reward}): {probability}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*KZ0m0Kw7K6qiZCSI6t1T_w.png" /><figcaption>Output of the Python code — source: Author</figcaption></figure><h3><strong>Markov Decision Process for Inventory Optimization</strong></h3><p>Here, we are building the dictionary, where for each state, we are considering all possible actions, and for each action, we are considering all possible states and rewards. This dictionary name is <strong>**MDP_dict**,</strong> and I wrote the code of it below:</p><pre>from typing import Dict, Tuple<br><br># poisson is used to find pdf of Poisson distribution <br>from scipy.stats import poisson<br><br>MDP_dict: Dict[tuple, Dict[tuple, tuple]] = {}<br><br>user_capacity = 2<br>user_poisson_lambda = 1<br>holding_cost = 1<br>missedcostumer_cost = 10<br><br><br><br>for alpha in range(user_capacity+1):                            <br>                                                               <br>    for beta in range(user_capacity + 1 - alpha):<br>        <br>        # This is St, the current state<br>        state = (alpha, beta)                                   <br><br>        # This is initial inventory, total bike you have at 8AM <br>        init_inv = alpha + beta                         <br>        <br>        base_reward = -alpha* holding_cost<br>        <br>        action = {}<br>        # Consider all possible actions<br>        for order in range(user_capacity-init_inv +1):<br>            <br>            #action = {}<br>            dict1 = {}<br>            for i in range(init_inv +1):<br><br>            # if initial demand can meet the deman<br>                if i &lt;= (init_inv-1):<br>                <br>                # probality of specifc demand can happen<br>                    transition_prob = poisson.pmf(i,user_poisson_lambda)<br><br>                    dict1[((init_inv - i, order), base_reward)] = transition_prob<br><br>                         <br>            # if initial demand can not meet the demand<br>                else:<br>                <br>                    transition_prob = 1- poisson.cdf(init_inv -1, user_poisson_lambda)<br>                <br>                # probability of not meeting the demands<br>                    transition_prob2 = 1- poisson.cdf(init_inv, user_poisson_lambda)<br>                <br>                # total reward<br>                <br>                    reward = base_reward - missedcostumer_cost*((user_poisson_lambda*transition_prob) - \<br>                                                  init_inv*transition_prob2)                <br><br>                    dict1[((init_inv - i, order),reward)] = transition_prob<br><br>                    #if state in MDP_dict:<br><br>            action[order] = dict1<br><br>        MDP_dict[state]= action<br><br>MDP_dict<br># Constants</pre><p>“MDP_dict” is a Python dictionary where each key represents the “current state,” and the value is “all possible actions at that state,” corresponding to the next state, immediate reward, and probability of the next state. Here is the explanation in the schematic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*aRoYkulqUUw4zHFihEL6-A.png" /><figcaption>Schematic of the MDP_dict — Source: Author</figcaption></figure><h3><strong>Dynamic Programming</strong></h3><p>Richard Bellman (1950s) first coined the term called <strong>Dynamic Programming (DP)</strong>. Dynamic Programming is a method for solving complex problems by breaking them down into simpler subproblems.</p><p>DP generally refers to general theories of the Markov Decision Process and <strong>algorithms</strong> to find an optimal policy in MDP, relying heavily on the Bellman Equation.</p><p>In the context of this article, we use the term Dynamic Programming with the goal of finding the optimal policy for the Inventory Optimization problem.</p><p>There are generally two import DP algorithms:</p><p>- <strong>Value Function Iteration Algorithm</strong> (<strong>Bellman 1957</strong>)</p><p><strong>- Policy Iteration Algorithm (Howard 1960)</strong></p><p>In this article, we are going to focus on the Policy Iteration Algorithm, and we are going to implement it in Python.</p><h3>Policy Iteration Algorithm for Inventory Optimization:</h3><p>The <strong>Policy Iteration Algorithm</strong> is a method for finding the optimal policy for a given MDP. The algorithm is based on the following idea:</p><p><strong>- 1)</strong> Start with an initial policy $π_0$.</p><p><strong>- 2)</strong> Evaluate the policy $π_0$ by computing the state-value function $V^{π_0}$.</p><p><strong>- 3) </strong>Improve the policy by acting greedily with respect to $V^{\pi_0}$ to get a new policy $\pi_1$.</p><p>The algorithm iterates on the above steps until the policy converges (policy stops to change). We are going to go through all three stages in the following sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*ljUBo45OKI92NHOlqVf8xw.png" /><figcaption>A simple diagram to explain the <strong>Policy Iteration Algorithm </strong>— Source: Author</figcaption></figure><h4><strong>1) Start with the Initial Policy</strong></h4><p>The policy iteration algorithm needs an initial policy (ordering strategy), which can be any arbitrary policy. In this article, we are going to use the policy that we found in the second article, which is the following:</p><p>Initial policy:</p><p><strong>π_0=C-(α + β)</strong></p><p>The initial policy is that at each stage of the inventory, we order the amount of $C-(α + β)$, which is the difference between the capacity of the inventory and the sum of initial items in the inventory ($α$) and the ones will come tomorrow morning ($β$) .</p><p>Here is the code for the initial policy:</p><pre>user_capacity_val = 2<br><br>def policy_0_gen(user_capacity: int):<br>        <br>        # Generate an initial policy<br><br>        return {(alpha, beta): user_capacity - (alpha + beta) <br>                for alpha in range(user_capacity + 1) <br>                for beta in range(user_capacity + 1 - alpha)}<br><br>policy_0 = policy_0_gen(user_capacity_val)<br>policy_0</pre><h4><strong>2) Evaluate the policy π_0 by computing the state-value V^{π_0}.</strong></h4><p>Note that any Markov Decision Process with a fixed policy leads to an **<strong>implied**</strong> Markov Reward Process. So, like the previous article, if we have the Markov Reward Process, we can find each state&#39;s value function.</p><p>In other words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*1GyTEo42GrrUr-ASWArIhQ.png" /><figcaption>Reference: Author</figcaption></figure><p>The below function will get a <strong>**fixed policy** </strong>(as input), and then it will return an implied Markov Reward Process:</p><pre>def MRP_using_fixedPolicy(full_MDP, policy):<br>        # Calculate the Markov Reward Process using a fixed policy<br>        MRP_policy = {}<br>        for state in full_MDP.keys():<br>            action = policy[state]<br>            MRP_policy[state] = full_MDP[state][action]<br>        return MRP_policy</pre><p>As an example, we can give the initial policy to the below function, and it will return the implied Markov Reward Process:</p><pre>MRP_p0=MRP_using_fixedPolicy(MDP_dict, policy_0)<br>MRP_p0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*BU_p2VgSFoKMqO-OEJhECg.png" /><figcaption>Output of the Python code — Source: Author</figcaption></figure><p>Having the Markov Reward Process, it is <em>pretty easy to find Immediate Rewards for each state</em> and also the state value function for each state:</p><pre>def calculate_expected_immediate_rewards(MRP_policy):<br>        # Calculate the expected immediate rewards from the MRP policy<br>        E_immediate_R = {}<br>        for from_state, value in MRP_policy.items():<br>            expected_reward = sum(reward[1] * prob for (reward, prob) in value.items())<br>            E_immediate_R[from_state] = expected_reward<br>        return E_immediate_R<br>R_ime_p0 = calculate_expected_immediate_rewards(MRP_p0)<br>R_ime_p0<br></pre><pre>import numpy as np<br>import pandas as pd<br>def create_transition_probability_matrix(MRP_policy):<br>        # Create the transition probability matrix<br>        states = list(MRP_policy.keys())<br>        num_states = len(states)<br>        trans_prob = np.zeros((num_states, num_states))<br>        df_trans_prob = pd.DataFrame(trans_prob, columns=states, index=states)<br>        for i, from_state in enumerate(states):<br>            for j, to_state in enumerate(states):<br>                for (new_state, reward) in MRP_policy.get(from_state, {}):<br>                    if new_state == to_state:<br>                        probability = MRP_policy[from_state].get((new_state, reward), 0.0)<br>                        df_trans_prob.iloc[i, j] = probability<br>                        <br>        return df_trans_prob<br><br>def calculate_state_value_function(trans_prob_mat, expected_immediate_rew, gamma=0.9):<br>        # Calculate the state value function<br>        states = list(expected_immediate_rew.keys())<br>        R_exp = np.array(list(expected_immediate_rew.values()))<br>        val_func_vec = np.linalg.solve(np.eye(len(R_exp)) - gamma * trans_prob_mat, R_exp)<br>        MarkRevData = pd.DataFrame({&#39;Expected Immediate Reward&#39;: R_exp, &#39;Value Function&#39;: val_func_vec}, <br>                                   index=states)<br>        return MarkRevData<br><br>trans_prob_p0 = create_transition_probability_matrix(MRP_p0)<br><br>state_val_p0 = calculate_state_value_function(trans_prob_mat=trans_prob_p0,<br>                               expected_immediate_rew=R_ime_p0)<br>state_val_p0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*97cqhrnoGi5YkNhtICxUxg.png" /><figcaption>Output of the Python code — Source: Author</figcaption></figure><h4><strong>3) Improve the policy by acting greedily with respect to $V^{π_0}$ to get a new policy $π_1$.</strong></h4><p>The last part of the <strong>Policy Iteration Algorithm</strong> is to improve the policy by acting greedily with respect to $V^{\pi_0}$ to get a new policy $\pi_1$.</p><p>The greedy equation is based on the Bellman Equation, and in fact, it is about finding the action with the highest <strong>**State-Value**</strong> function for each state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcDXUCAzfCf_0pWZ2qsdvw.png" /><figcaption>Bellman Optimality Equation— Source: Author</figcaption></figure><p>Here is the code for the greedy operation:</p><pre>def greedy_operation(MDP_full, state_val_policy, old_policy, gamma=0.9):<br>        # Perform the greedy operation to improve the policy<br>        new_policy = {}<br>        for state in old_policy.keys():<br>            max_q_value, best_action  = float(&#39;-inf&#39;), None<br>            state_val_dict = state_val_policy.to_dict(orient=&quot;index&quot;)<br>            for action in MDP_full[state].keys():<br>                q_value = 0<br>                for (next_state, immediate_reward), probability in MDP_full[state][action].items():<br>                    q_value = q_value +  probability * (immediate_reward + gamma *<br>                        (state_val_dict[next_state][&quot;Value Function&quot;]))<br>                if q_value &gt; max_q_value:<br>                    max_q_value, best_action = q_value, action<br>            new_policy[state] = best_action<br>        return new_policy<br><br>new_policy = greedy_operation(MDP_full=MDP_dict, <br>                              state_val_policy=state_val_p0, <br>                              old_policy=policy_0)</pre><p>The new policy after the first iteration of the policy iteration algorithm is the following:</p><pre>new_policy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*LwatFIH4egIyvUu2wg_V1g.png" /></figure><p>In the Policy Iteration algorithm, we keep iteration on the above three steps until the policy converges. In other words, we keep iterating on the above three steps until the policy stops to change. Here is the code for the Policy Iteration Algorithm:</p><pre>def policy_iteration():<br>        # Perform policy iteration to find the optimal policy<br>        policy = policy_0_gen(user_capacity_val)<br>        while True:<br>            MRP_policy_p0 = MRP_using_fixedPolicy(MDP_dict, policy)<br>            expected_immediate_rew = calculate_expected_immediate_rewards(MRP_policy_p0)<br>            trans_prob_mat_val = create_transition_probability_matrix(MRP_policy_p0)<br>            value_function = calculate_state_value_function(trans_prob_mat=trans_prob_mat_val,<br>                                                            expected_immediate_rew=expected_immediate_rew,<br>                                                            gamma=0.9)<br>            new_policy = greedy_operation(MDP_full=MDP_dict, <br>                                          state_val_policy=value_function, <br>                                          old_policy=policy)<br>            if new_policy == policy:<br>                break<br>            policy = new_policy<br>        <br>        opt_policy = new_policy<br>        opt_value_func = value_function<br>        <br>        return opt_policy, opt_value_func</pre><h3><strong>What is the Optimal Order?</strong></h3><p>Now, we can look at the outcome of policy iteration and see what the optimal order is for each state. Here is the code for it:</p><pre>for state, order_quantity in opt_policy.items():<br>    print(f&quot;For state {state}, the optimal order quantity is: {order_quantity}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Cfib8Q6ufnz5wBeUqihovw.png" /><figcaption>The optimal final policy — Source: Author</figcaption></figure><h3><strong>Putting Everything Together:</strong></h3><p>I am putting all the codes together in one Python class with its methods.</p><pre>import numpy as np<br>from scipy.stats import poisson<br>import pandas as pd<br><br>class MarkovDecisionProcess:<br>    def __init__(self, user_capacity, poisson_lambda, holding_cost, stockout_cost, gamma):<br>        # Initialize the MDP with given parameters<br>        self.user_capacity = user_capacity<br>        self.poisson_lambda = poisson_lambda<br>        self.holding_cost, self.stockout_cost = holding_cost, stockout_cost<br>        self.gamma = gamma<br>        self.full_MDP = self.create_full_MDP()  # Create the full MDP<br><br>    def create_full_MDP(self):<br>        # Create the full MDP dictionary<br>        MDP_dict = {}<br>        for alpha in range(self.user_capacity + 1):<br>            for beta in range(self.user_capacity + 1 - alpha):<br>                state, init_inv = (alpha, beta), alpha + beta <br>                action = {}<br>                for order in range(self.user_capacity - init_inv + 1):<br>                    dict1 = {}<br>                    for i in range(init_inv + 1):<br>                        if i &lt;= (init_inv - 1):<br>                            transition_prob = poisson.pmf(i, self.poisson_lambda)<br>                            dict1[((init_inv - i, order), -alpha * self.holding_cost)] = transition_prob<br>                        else:<br>                            transition_prob = 1 - poisson.cdf(init_inv - 1, self.poisson_lambda)<br>                            transition_prob2 = 1 - poisson.cdf(init_inv, self.poisson_lambda)<br>                            reward = -alpha * self.holding_cost - self.stockout_cost * (<br>                                (self.poisson_lambda * transition_prob) - init_inv * transition_prob2)<br>                            dict1[((0, order), reward)] = transition_prob<br>                    action[order] = dict1<br>                MDP_dict[state] = action<br>        return MDP_dict<br><br>    def policy_0_gen(self):<br>        # Generate an initial policy<br>        return {(alpha, beta): self.user_capacity - (alpha + beta) <br>                for alpha in range(self.user_capacity + 1) <br>                for beta in range(self.user_capacity + 1 - alpha)}<br><br>    def MRP_using_fixedPolicy(self, policy):<br>        # Create the MRP using a fixed policy<br>        return {state: self.full_MDP[state][action] <br>                for state, action in policy.items()}<br>    <br>    def calculate_state_value_function(self, MRP_policy):<br>        # Calculate the expected immediate rewards from the MRP policy<br>        E_immediate_R = {}<br>        for from_state, value in MRP_policy.items():<br>            expected_reward = sum(reward[1] * prob for (reward, prob) in value.items())<br>            E_immediate_R[from_state] = expected_reward<br><br>        # Create the transition probability matrix<br>        states = list(MRP_policy.keys())<br>        trans_prob = np.zeros((len(states), len(states)))<br>        df_trans_prob = pd.DataFrame(trans_prob, columns=states, index=states)<br>        for i, from_state in enumerate(states):<br>            for j, to_state in enumerate(states):<br>                for (new_state, reward) in MRP_policy.get(from_state, {}):<br>                    if new_state == to_state:<br>                        probability = MRP_policy[from_state].get((new_state, reward), 0.0)<br>                        df_trans_prob.iloc[i, j] = probability<br><br>        # Calculate the state value function<br>        R_exp = np.array(list(E_immediate_R.values()))<br>        val_func_vec = np.linalg.solve(np.eye(len(R_exp)) - self.gamma * df_trans_prob, R_exp)<br>        MarkRevData = pd.DataFrame({&#39;Expected Immediate Reward&#39;: R_exp, &#39;Value Function&#39;: val_func_vec}, index=states)<br>        return MarkRevData<br><br>    def greedy_operation(self, MDP_full, state_val_policy, old_policy):<br>        # Perform the greedy operation to improve the policy<br>        new_policy = {}<br>        for state in old_policy.keys():<br>            max_q_value, best_action  = float(&#39;-inf&#39;), None<br>            state_val_dict = state_val_policy.to_dict(orient=&quot;index&quot;)<br>            for action in MDP_full[state].keys():<br>                q_value = 0<br>                for (next_state, immediate_reward), probability in MDP_full[state][action].items():<br>                    q_value = q_value +  probability * (immediate_reward + self.gamma *<br>                        (state_val_dict[next_state][&quot;Value Function&quot;]))<br>                if q_value &gt; max_q_value:<br>                    max_q_value, best_action = q_value, action<br>            new_policy[state] = best_action<br>        return new_policy<br><br>    def policy_iteration(self):<br>        # Perform policy iteration to find the optimal policy<br>        policy = self.policy_0_gen()<br>        while True:<br>            MRP_policy_p0 = self.MRP_using_fixedPolicy(policy)<br>            value_function = self.calculate_state_value_function(MRP_policy_p0)<br>            new_policy = self.greedy_operation(self.full_MDP, value_function, policy)<br>            if new_policy == policy:<br>                break<br>            policy = new_policy<br>        opt_policy, opt_value_func = new_policy, value_function<br>        return opt_policy, opt_value_func</pre><h4>Example of using the Markov Decision Process class</h4><pre># Example usage:<br>user_capacity = 2<br>poisson_lambda = 1.0<br>holding_cost = 1<br>stockout_cost = 10<br>gamma = 0.9<br><br>MDP_Example = MarkovDecisionProcess(user_capacity, poisson_lambda, holding_cost, stockout_cost, gamma)<br><br>opt_policy, opt_val = MDP_Example.policy_iteration()<br><br># Print the optimal policy<br>print(&quot;Optimal Policy:&quot;)<br>for state, order_quantity in opt_policy.items():<br>    print(f&quot;For state {state}, the optimal order quantity is: {order_quantity}&quot;)<br><br># Print the optimal value function<br>print(&quot;\nOptimal Value Function:&quot;)<br>print(opt_val)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*heLdEe8BKW82RQYfrALLIA.png" /><figcaption>Output of the Python code — Source: Author</figcaption></figure><h3>Summary:</h3><ul><li><strong>Inventory optimization</strong> is not a static optimization problem; rather, it is a sequential decision-making problem. It means we need an “adaptive” policy where a decision (number of orders) is dependent on the state of the inventory.</li><li>In this blog, we found the “optimal” ordering policy, based on Dynamic Programming Algorithm.</li><li>The goal was to build a foundation on how to think about Inventory Optimization problems, how to frame them, and how to solve them using appropriate mathematical modeling.</li></ul><h3>References:</h3><ul><li>[1] You can read this example more in-depth in “<a href="https://www.amazon.com/Foundations-Reinforcement-Learning-Applications-Finance/dp/1032124121"><strong>Foundation of Reinforcement Learning with Application in Finance</strong></a>”. However, I have rewritten Python codes in this blog to make it easier to understand.</li><li>Bellman, Richard., <a href="http://www.jstor.org/stable/24900506">A Markovian Decision Process </a>(1957), Journal of Mathematics and Mechanics.</li><li>Howard, R. A. 1960. <a href="https://www.amazon.com/Programming-Processes-Technology-Research-Monographs/dp/0262080095">Dynamic Programming and Markov Processes</a>, (1960.), Cambridge, MA: MIT Press.</li></ul><h3>Thanks for reading so far!</h3><p>I hope this article has provided an easy-to-understand tutorial on how to do inventory optimization with Python.</p><p><em>If you think this article helped you to learn more about inventory optimization and Markov Process, please give it a 👏 and follow!</em></p><h3>Resources:</h3><p><strong>Connect:</strong> <a href="https://peymankor.com/"><strong>My Website</strong></a> | <a href="https://topmate.io/peyman_kor/692694"><strong>Book a Free Call with Me</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab1cc58ef34c" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/inventory-optimization-with-dynamic-programming-in-less-than-100-lines-of-python-code-ab1cc58ef34c">Inventory Optimization with Dynamic Programming in Less than 100 Lines of Python Code</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inventory Optimization with Data Science: Hands-On Tutorial with Python]]></title>
            <link>https://pub.towardsai.net/inventory-optimization-with-data-science-hands-on-tutorial-with-python-1360ef044f18?source=rss-d7edd6a4f65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1360ef044f18</guid>
            <category><![CDATA[inventory-management]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[markov-decision-process]]></category>
            <dc:creator><![CDATA[Peyman Kor]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 18:01:41 GMT</pubDate>
            <atom:updated>2023-12-24T14:59:42.929Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: A Gentle Introduction to Implementing the Markov Reward Process (MRP) for Inventory Optimization.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgytjkZb7y8yjjcHb5ywkw.jpeg" /></figure><h3>Intro</h3><p>Effective inventory management is important for businesses across various industries. <a href="https://medium.com/towards-artificial-intelligence/inventory-optimization-with-data-science-hands-on-tutorial-with-python-f49633fdd19a">In the previous blog</a>, we explored how to model the process and how to frame it with the Markov Process.</p><p>The below illustration shows how to model the probabilistic movement of the states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*vWAv5bGaKTT4-chJkO_laQ.png" /><figcaption>Transition probabilities of Markov Process — Image source: Author</figcaption></figure><blockquote>In this blog, we go one step ahead and think about how to frame inventory optimization with the Markov Reward Process (MRP). Here, we have the additional term “Reward,” meaning we need to think about how to assign “Reward“ to the process.</blockquote><p>This blog will have the following structure:</p><ul><li><strong>Markov Reward Process (MRP)</strong></li><li><strong>Reward Modeling Bike Shop Inventory Optimization</strong></li><li><strong>Hands-On Python Coding</strong></li><li><strong>Bellman Equation</strong></li><li><strong>Putting Everything Together</strong></li><li><strong>Key Summary</strong></li></ul><h4><strong>At the end of the blog, you will learn:</strong></h4><ul><li>How to frame the Markov Reward Process (MRP) for Bike Shop Inventory Optimization.</li><li>Write hands-on code to model MRP in Python.</li></ul><h3><strong>Markov Reward Process:</strong></h3><p>Markov Reward Process (in short MRP) is a Markov Process, where the sequence of “Rewards, State” tuple follows the <strong>Markov Reward Property</strong> as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*eMcF8PJzd4KJbBKtnC3Brw.png" /></figure><p>Here, R_{t+1} is a reward induced if we move from state S_{t} to S_{t+1}.</p><blockquote>MRP need a new Python data structure. The new data structure not only keeps state evolution with its probability, but this time it’s rewards too.</blockquote><p>To show how MRP data structure looks like in Python, I am giving an example of <strong>MarkovRewProcess_Exa </strong>data structure. Let me explain what it looks like:</p><pre>MarkovRewProcess_Exa = {&quot;Current State A&quot;:{(&quot;NextS1fromA&quot;,  &quot;RewardS1fromA&quot;):&quot;PNextS1fromA&quot;,<br>                                           (&quot;NextS2fromA&quot;, &quot;RewardS2fromA&quot;):&quot;PNextS2fromA&quot;},<br>                    <br>                     &quot;Current State B&quot;:{(&quot;NextS1fromB&quot;,  &quot;RewardS1fromB&quot;):&quot;PNextS1fromB&quot;,<br>                                       (&quot;NextS2fromB&quot;,  &quot;RewardS2fromB&quot;):&quot;PNextS2fromB&quot;}}</pre><p>The <strong>**MarkovRewProcess_Exa**</strong> is a dictionary where the <strong>keys</strong> are the current state, <strong>S_t</strong>. Then, each state going to a new state would have some rewards, and from<em> </em>state<em> </em><strong><em>S_t</em> </strong>to tuple of <strong>(S_{t+1}, R_{t+1}) </strong>has a specific probability<em>.</em></p><p>Here you can see when you are at <strong>S_t = Current State A, </strong>and you move to next <strong>(state, reward) </strong>written as (“NextS1fromA”, “RewardS1fromA”), the probability of happening of this move is : <strong>**PNextS1fromA**:</strong></p><pre>MarkovRewProcess_Exa[&quot;Current State A&quot;][(&quot;NextS1fromA&quot;,  &quot;RewardS1fromA&quot;)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTGzC3tj4MvPhP2OfVuYpg.png" /><figcaption>Code output — Image Source: Author</figcaption></figure><p>And we can iterate over all possible (new state, reward) to get the overview of the process evolves:</p><pre>for (state, value) in MarkovRewProcess_Exa.items():<br>    <br>    print(&quot;The Current state is: {}&quot;.format(state))<br>    <br>    for (next_state,reward),trans_prob  in value.items():<br>        <br>        print(&quot;The ({} with {}) \nwith Probability of: {} \<br>               &quot;.format(next_state, reward, trans_prob ))p</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37nTtXkxlUtTQ3vW3OKqng.png" /><figcaption>Code Output — Image Source: Author</figcaption></figure><h3>Reward Modeling Bike Shop Inventory Optimization</h3><p>Now, at this stage, we need to assign a reward to the Markov Process of Bike Shop, <a href="https://medium.com/towards-artificial-intelligence/inventory-optimization-with-data-science-hands-on-tutorial-with-python-f49633fdd19a">as we discussed in the previous article</a>. What we mean is that given you are at state S_t, if you move to state S_{t+1}, how much <strong>“cost/reward”</strong> is accrued?</p><p>In the example of <strong>Bike Shop Inventory Optimization, </strong>the cost is <strong>compromised of two parts:</strong></p><p><strong>- 1) </strong>When we hold inventory items in the inventory, we are making the cost of <strong>overnight holding costs</strong>. Imagine holding items in inventory is costly (maintenance or other fees).</p><p><strong>- 2)</strong> The second cost is <strong>missed customer cost</strong>. This happens when you have three bicycles in your inventory, but there are five customers. In this case, you missed two customers.</p><p>In other words, reward in the example of Bike Shop is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FyYVqmqocStWJZV2SU5USQ.png" /><figcaption>Defining Reward: Image Source: Author</figcaption></figure><p>However, we can not write the equation straightforwardly, as we need to distinguish two different cases,</p><p><strong>Case I) The number of available items in inventory meets the “demand”</strong></p><p>In this case, we do not have any<strong> “Missed Customer cost”</strong>. Meaning only we are dealing with overnight holding costs. We assume this cost of overholding per bicycle (item) is equal to <strong>h</strong>. We can write that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orkb6A5gKpNWUhx41NCrWA.png" /><figcaption>Reward Modeling Case I— Image Source: Author</figcaption></figure><p>Note that states are “recorded” each day at 8 PM . For example, today is Monday, and at 8 PM, you record that you have two bicycles in the inventory (α = 2) and one bicycle order that arrives tomorrow morning at 6 AM (β = 1). If tomorrow&#39;s demand is i=1. Given this, the reward is the equal cost of holding:</p><p>-hα=-h×2</p><p><strong>Case II) The number of available items in inventory is lower than the “demand”</strong></p><p>In this case, when demand i is equal and greater than all the bicycles you have in the early morning, α + β. In this case, the cost <em>is first -hα </em>plus the <strong><em>Missed Costumer cost</em></strong>, where the unit cost of the missed customer is equal to <strong>p</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0HhFMHg7zWhOPJNjna3Zg.png" /><figcaption>Reward Modeling Case II — Image Source: Author</figcaption></figure><p>The right side of the above equation needs to be explained. The term <strong>p</strong> is simply the unit cost of the missing customer, then the term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PEhyDj542mWD3L6qP1xuqQ.png" /><figcaption>The second part of Reward Modeling Case II — Image Source: Author</figcaption></figure><p>It is equal to an expected number of missed customers multiplied by p.</p><h3><strong>Hands-On Python Coding:</strong></h3><p>In the below, we wrote a function that is the generator of the <strong>Markov Reward Process Dictionary</strong>. The final output of the dictionary structure for the Markov Reward Process is as follows:</p><pre>from typing import Dict, Tuple<br><br>MRP_dict: Dict[Tuple[int, int], Dict[Tuple[Tuple[int, int], float], float]] = {}</pre><p>I did a little bit of explanation and annotation of the final data structure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBxhWZQ8UL32B0jCwOY2yw.png" /><figcaption>MRP_Dict is the final data data structure of MRP process. Image Source: Author</figcaption></figure><pre>from typing import Dict, Tuple<br>from scipy.stats import poisson<br><br>def generate_Markov_Rew_Process_Dict(user_capacity: int, user_poisson_lambda: int,<br>                                      holding_cost: int, missedcostumer_cost: int):<br>    &quot;&quot;&quot;<br>    Generate a Markov Reward Process Dictionary based on the provided parameters.<br><br>    Args:<br>        user_capacity (int): The the capacity of the inventory.<br>        user_poisson_lambda (int): The Poisson lambda parameter.<br>        holding_cost (int): The unit cost of holding item in inventory overnight.<br>        missedcostumer_cost (int):The unit cost of missed costumer.<br>    Returns:<br>        Dict[Tuple[int, int], Dict[Tuple[Tuple[int, int], float], float]]: The Markov Reward Process Dictionary.<br>    &quot;&quot;&quot;<br><br>    MRP_dict: Dict[Tuple[int, int], Dict[Tuple[Tuple[int, int], float], float]] = {}<br><br>    for alpha in range(user_capacity + 1):<br>        for beta in range(user_capacity + 1 - alpha):<br>            <br>            state = (alpha, beta)<br>            init_inv = alpha + beta<br>            beta1 = user_capacity - init_inv<br><br>            base_reward = -alpha * holding_cost<br>            <br>            for demand in range(init_inv + 1):<br>                    if demand &lt;= (init_inv - 1):<br>                        <br>                        # Calculate transition probability for demand<br>                        transition_prob = poisson.pmf(demand, user_poisson_lambda)<br>                                                <br>                        if state in MRP_dict:<br>                    <br>                            MRP_dict[state][((init_inv - demand, beta1), base_reward)]= transition_prob<br>                <br>                        else:<br>                    <br>                            MRP_dict[state] = {((init_inv - demand, beta1), base_reward):transition_prob}<br>                    <br>                    <br>                    else:<br>                        # probability of not meeting the demands<br>                        transition_prob = 1 - poisson.cdf(init_inv - 1, user_poisson_lambda)<br>                        <br>                        transition_prob2 = 1 - poisson.cdf(init_inv, user_poisson_lambda)<br>                        <br>                        <br>                        reward = base_reward - missedcostumer_cost * ((user_poisson_lambda * transition_prob) -<br>                                                                init_inv * transition_prob2)<br>                        <br>                        if state in MRP_dict:<br>                             <br>                             MRP_dict[state][((0, beta1),reward)]= transition_prob<br>                             <br>                        else:<br><br>                            MRP_dict[state] = {((0, beta1),reward):transition_prob}<br><br>    return MRP_dict</pre><p>Having the function, we can give the function&#39;s input (same as the previous article) and then get the dictionary of the Markov Reward Process.</p><pre># Example usage:<br>inv_capacity_val = 2<br>poisson_lambda_val = 2.0<br>holding_cost_val = 1<br>missedcostumer_cost_val = 10<br><br>MRP_dict = generate_Markov_Rew_Process_Dict(<br>    user_capacity= inv_capacity_val, <br>    user_poisson_lambda = poisson_lambda_val,<br>    holding_cost = holding_cost_val,<br>    missedcostumer_cost = missedcostumer_cost_val)</pre><p>We can print out this dictionary and figure out how the data has been stored in the dictionary:</p><pre>for (state, value) in MRP_dict.items():<br>    <br>    print(&quot;The Current state is: {}&quot;.format(state))<br>    <br>    for (next_state,reward),trans_prob  in value.items():<br>        <br>        print(&quot;The (State ,Reward): ({} , {:.2f}) occurs with Probability of: {:.2f} \<br>               &quot;.format(next_state, reward, trans_prob ))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GK4pqcvdzRvPqy1D3dZ8UA.png" /></figure><h3><strong>Bellman Equation:</strong></h3><p>The main idea of the Markov Reward Process is to figure out the expected total return of each state if we continue the process for a long time under a specific policy. The “<strong>State Value Function</strong>” that maps “Expected Return of Each State” to “State” called as “State Value Function” can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgFsN7YcKk_GEL3W_EyBBg.png" /><figcaption>Bellman Equation for Value Function of Each State — Image Source: Author</figcaption></figure><p>Some explanation of the second equation is needed. The <strong>V(s)</strong> is the expected total return of following specific policy from state<strong> s</strong>, compromised of two parts. The first part is the reward we expect to get right away (immediate), plus the average value of all the different states we could go to next, times the value of those new states<strong> V(S’)</strong>.</p><p>In other words, this equation is recursive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQdzmFnvW84OHie5pvcgdg.png" /><figcaption>Annotation of Bellman Equation for State Value Function — Image Source: Author</figcaption></figure><p>The goal of the rest of this blog is to find the state value function <strong>V(s)</strong>, which consists of two parts:</p><p><strong>- Part I) Find the Expected Immediate Reward for all states</strong></p><p><strong>- Part II) Build the Transition Probability Matrix</strong></p><h4><strong>Part I) Find the Expected Immediate Reward</strong></h4><p>The below function will find theR(s) for all the states. In fact, R(s) is the expected immediate reward for states in the inventory problem.</p><pre>def calculate_expected_immediate_rewards(MarkovRewProcessDict):<br>    &quot;&quot;&quot;<br>    Calculate the expected immediate rewards for each state in a Markov Reward Process.<br><br>    Args:<br>        MarkovRewProcessDict (dict): Markov Reward Process Dictionary.<br><br>    Returns:<br>        dict: Dictionary with states as keys and their expected immediate rewards as values.<br>    &quot;&quot;&quot;<br>    E_immediate_R = {}  # Initialize a dictionary to store expected immediate rewards<br><br>    for from_state, value in MarkovRewProcessDict.items():<br>        # Calculate the expected immediate reward for the current state<br>        expected_reward = sum(reward[1] * prob for (reward, prob) in value.items())<br>        E_immediate_R[from_state] = expected_reward<br><br>    return E_immediate_R<br><br># Example usage:<br># E_immediate_R = calculate_expected_immediate_rewards(MarkovRewProcessDict)</pre><p>Calling the function:</p><pre>R_exp_imm =calculate_expected_immediate_rewards(MRP_dict)<br>R_exp_imm</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbNsu735N7upup3eIZgpow.png" /></figure><h4><strong>Part II) Build the Transition Probability Matrix</strong></h4><p>The transition probability matrix is like a table where the <strong>*states*</strong> are the column names and rows, and each cell shows the likelihood of moving from one state to another.</p><p>We can initialize this matrix with:</p><pre>states = list(MRP_dict.keys())<br><br>df_trans_prob = pd.DataFrame(0.0, columns=states, index=states)<br>df_trans_prob</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*WNIwWgM51AGb3nKBdzscsA.png" /></figure><p>The above is the initialization of the matrix. Now we can go and start filling out this matrix as below:</p><pre>import numpy as np<br>import pandas as pd<br><br>def create_transition_probability_matrix(MarkovRewProcessDict):<br>    &quot;&quot;&quot;<br>    Create a transition probability matrix from a Markov Reward Process Dictionary.<br><br>    Args:<br>        MarkovRewProcessDict (dict): Markov Reward Process Dictionary.<br><br>    Returns:<br>        pd.DataFrame: Transition probability matrix.<br>    &quot;&quot;&quot;<br>    states = list(MarkovRewProcessDict.keys())<br>    num_states = len(states)<br><br>    # Initialize an empty matrix with zeros<br>    trans_prob = np.zeros((num_states, num_states))<br>    df_trans_prob = pd.DataFrame(trans_prob, columns=states, index=states)<br><br>    for i, from_state in enumerate(states):<br>        for j, to_state in enumerate(states):<br>            for (new_state, reward) in MarkovRewProcessDict.get(from_state, {}):<br>                if new_state == to_state:<br>                    probability = MarkovRewProcessDict[from_state].get((new_state, reward), 0.0)<br>                    df_trans_prob.iloc[i, j] = probability<br><br>    return df_trans_prob<br></pre><p>Calling the function:</p><pre>df_trans_prob = create_transition_probability_matrix(MRP_dict)<br>df_trans_prob</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*y8AQq5fYdmYgJCO8wJvmpw.png" /></figure><p>Let me explain what this matrix means. For example, think about the third row, which is state <strong>S_t=(0,2)</strong>, then the following probability can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXUKKny-aqv0R_ZIS2W6iA.png" /></figure><p>Now, having the transition matrix probability and expected immediate rewards of states, we can calculate the value function of each state using the vector and matrix format of the Bellman equation as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3B15iOUE1efzbRzz3WZFDQ.png" /></figure><pre>import numpy as np<br>import pandas as pd<br><br>def calculate_state_value_function(trans_prob_mat, expected_immediate_rew, gamma):<br>    &quot;&quot;&quot;<br>    Calculate the state value function using transition probability matrix and expected immediate rewards.<br><br>    Args:<br>        trans_prob_mat (pd.DataFrame): Transition probability matrix.<br>        expected_immediate_rew (dict): Dictionary with states as keys and expected immediate rewards as values.<br>        gamma (float): Discount factor.<br><br>    Returns:<br>        pd.DataFrame: DataFrame with &#39;Expected Immediate Reward&#39; and &#39;Value Function&#39; columns indexed by states.<br>    &quot;&quot;&quot;<br>    states = list(expected_immediate_rew.keys())<br><br>    R_exp = np.array(list(expected_immediate_rew.values()))<br><br>    # Calculate the value function vector using the equation<br>    val_func_vec = np.linalg.solve(np.eye(len(R_exp)) - gamma * trans_prob_mat, R_exp)<br><br>    # Create a DataFrame with &#39;Expected Immediate Reward&#39; and &#39;Value Function&#39; columns<br>    MarkRevData = pd.DataFrame({&#39;Expected Immediate Reward&#39;: R_exp, &#39;Value Function&#39;: val_func_vec}, index=states)<br><br>    return MarkRevData<br><br># Example usage:<br># MarkRevData = calculate_state_value_function(df_trans_prob, E_immediate_R, gamma)</pre><p>Calling this function:</p><pre>calculate_state_value_function(trans_prob_mat=df_trans_prob, expected_immediate_rew=R_exp_imm, gamma=0.9)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*Ktxv3qawCX8W083B7oJiqQ.png" /></figure><h3>Putting Everything Together:</h3><p>One way is to put all codes together, make a MarkovRewardProcess class, and call modules of the class. I have put full code (less than 100 lines) here:</p><pre>from typing import Dict, Tuple<br>from scipy.stats import poisson<br>import numpy as np<br>import pandas as pd<br><br>class MarkovRewardProcess:<br>    def __init__(self):<br>        self.MRP_dict = {}<br><br>    def generate_Markov_Rew_Process_Dict(self, user_capacity: int, user_poisson_lambda: int,<br>                                          holding_cost: int, missedcostumer_cost: int):<br>        self.MRP_dict = {}  # Initialize the Markov Reward Process Dictionary<br><br>        for alpha in range(user_capacity + 1):<br>            for beta in range(user_capacity + 1 - alpha):<br>            <br>                state = (alpha, beta)<br>                init_inv = alpha + beta<br>                beta1 = user_capacity - init_inv<br><br>                base_reward = -alpha * holding_cost<br>            <br>                for demand in range(init_inv + 1):<br>                    if demand &lt;= (init_inv - 1):<br>                        transition_prob = poisson.pmf(demand, user_poisson_lambda)<br>                                                <br>                        if state in self.MRP_dict:<br>                            self.MRP_dict[state][((init_inv - demand, beta1), base_reward)] = transition_prob<br>                        else:<br>                            self.MRP_dict[state] = {((init_inv - demand, beta1), base_reward): transition_prob}<br>                    else:<br>                        transition_prob = 1 - poisson.cdf(init_inv - 1, user_poisson_lambda)<br>                        transition_prob2 = 1 - poisson.cdf(init_inv, user_poisson_lambda)<br>                        reward = base_reward - missedcostumer_cost * ((user_poisson_lambda * transition_prob) -<br>                                                                init_inv * transition_prob2)<br>                        if state in self.MRP_dict:<br>                            self.MRP_dict[state][((0, beta1), reward)] = transition_prob<br>                        else:<br>                            self.MRP_dict[state] = {((0, beta1), reward): transition_prob}<br><br>    def calculate_expected_immediate_rewards(self):<br>        E_immediate_R = {}<br>        for from_state, value in self.MRP_dict.items():<br>            expected_reward = sum(reward[1] * prob for (reward, prob) in value.items())<br>            E_immediate_R[from_state] = expected_reward<br>        return E_immediate_R<br><br>    def create_transition_probability_matrix(self):<br>        states = list(self.MRP_dict.keys())<br>        num_states = len(states)<br>        trans_prob = np.zeros((num_states, num_states))<br>        df_trans_prob = pd.DataFrame(trans_prob, columns=states, index=states)<br><br>        for i, from_state in enumerate(states):<br>            for j, to_state in enumerate(states):<br>                for (new_state, reward) in self.MRP_dict.get(from_state, {}):<br>                    if new_state == to_state:<br>                        probability = self.MRP_dict[from_state].get((new_state, reward), 0.0)<br>                        df_trans_prob.iloc[i, j] = probability<br>        return df_trans_prob<br><br>    def calculate_state_value_function(self, trans_prob_mat, expected_immediate_rew, gamma):<br>        states = list(expected_immediate_rew.keys())<br>        R_exp = np.array(list(expected_immediate_rew.values()))<br>        val_func_vec = np.linalg.solve(np.eye(len(R_exp)) - gamma * trans_prob_mat, R_exp)<br>        MarkRevData = pd.DataFrame({&#39;Expected Immediate Reward&#39;: R_exp, &#39;Value Function&#39;: val_func_vec}, index=states)<br>        return MarkRevData<br><br>mrp = MarkovRewardProcess()<br><br># Generate the Markov Reward Process Dictionary<br>user_capacity = 2<br>user_poisson_lambda = 2<br>holding_cost = 1<br>missedcostumer_cost = 10<br><br>mrp.generate_Markov_Rew_Process_Dict(user_capacity, user_poisson_lambda, holding_cost, missedcostumer_cost)<br><br>E_immediate_R = mrp.calculate_expected_immediate_rewards()<br>trans_prob_mat = mrp.create_transition_probability_matrix()<br><br>gamma = 0.9  # Replace with your desired discount factor<br>MRP_Data = mrp.calculate_state_value_function(trans_prob_mat, E_immediate_R, gamma)<br><br>print(MRP_Data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXJn8j5TQ2UrXzbQ1X3BZg.png" /><figcaption>Code output using writing Python Class — Image Source: Author</figcaption></figure><h3><strong>Key Summary:</strong></h3><p>- In this blog, the <strong>Markov Reward Process </strong>was introduced, and in the example of inventory optimization, the “reward” of the process was defined.</p><p>- A new Python data structure, “MRP_dict,” was introduced where it tracks the states, the reward, and the probability of the next (state, reward).</p><p>- The Markov Reward Process aims to find a <strong>State Value Function</strong>, meaning what the “Expected Total Return” for every state is. This was achieved by using the <em>calculate_state_value_function</em> in the Python code.</p><p>[1] You can read this example more in-depth in “<a href="https://www.amazon.com/Foundations-Reinforcement-Learning-Applications-Finance/dp/1032124121"><strong>Foundation of Reinforcement Learning with Application in Finance</strong></a>”. However, I have rewritten Python codes in this blog to make it easier to understand.</p><h3>Resources:</h3><p><strong>Connect:</strong> <a href="https://peymankor.com/"><strong>My Website</strong></a> | <a href="https://topmate.io/peyman_kor/692694"><strong>Book a Free Call with Me</strong></a></p><h3>Thanks for reading so far!</h3><p>I hope this article has provided an easy-to-understand tutorial on how to do inventory optimization with Python.</p><p><em>If you think this article helped you to learn more about inventory optimization and Markov Process, please give it a 👏 and follow!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1360ef044f18" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/inventory-optimization-with-data-science-hands-on-tutorial-with-python-1360ef044f18">Inventory Optimization with Data Science: Hands-On Tutorial with Python</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>