<?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 Xinzhe Li, PhD in Language Intelligence on Medium]]></title>
        <description><![CDATA[Stories by Xinzhe Li, PhD in Language Intelligence on Medium]]></description>
        <link>https://medium.com/@sergioli?source=rss-23bba04f5843------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dCWliTqwIygqLpZcF2JfLg@2x.jpeg</url>
            <title>Stories by Xinzhe Li, PhD in Language Intelligence on Medium</title>
            <link>https://medium.com/@sergioli?source=rss-23bba04f5843------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 19 May 2026 08:48:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergioli/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[Efficiently Track and Cache Your LLM API Usage with LLMTrack]]></title>
            <link>https://levelup.gitconnected.com/efficiently-track-and-cache-your-llm-api-usage-with-llmtrack-cae5a8556feb?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/cae5a8556feb</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 07:34:40 GMT</pubDate>
            <atom:updated>2025-03-17T13:31:04.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyaRoKcA2UC6Pr3t0NzCMA.png" /></figure><p>Are you tired of repeatedly incurring costs and facing latency issues due to redundant API calls when working with Large Language Models (LLMs)? Do you want detailed insights into how different models consume tokens for your projects? Meet <a href="https://github.com/xinzhel/llmtrack"><strong>LLMTrack</strong></a>, the simple yet powerful Python package designed to streamline your workflow by caching results and precisely tracking token usage per model.</p><h3>Why LLMTrack?</h3><p>As developers, data scientists, or AI enthusiasts, we frequently interact with various LLMs such as OpenAI’s GPT models, Azure OpenAI, MoonShot, and Groq. Repeatedly calling these APIs for identical prompts wastes both time and money. Moreover, tracking token consumption helps optimize costs and ensures efficient usage of LLM resources.</p><p><strong>LLMTrack</strong> addresses these exact pain points:</p><ul><li><strong>Caching</strong>: Avoids repeated API calls by caching responses for each LLM model.</li><li><strong>Token Tracking</strong>: Records token usage separately for each LLM model.</li></ul><h3>Quick Installation</h3><p>Getting started with <strong>LLMTrack</strong> is straightforward:</p><pre>pip install llmtrack</pre><h3>Simplified Workflow</h3><p>Here’s how easy it is to integrate <strong>LLMTrack</strong> into your project:</p><pre>from llmtrack import set_root_dir, get_llm<br><br># Set up a custom root directory (optional)<br>set_root_dir(&quot;~/my_project/llmtrack&quot;)<br><br># Obtain an LLM instance with caching and token tracking enabled<br>client_name = &quot;openai&quot;<br>model_name = &quot;gpt-4o-mini&quot;<br>llm = get_llm(f&quot;{client_name}/{model_name}&quot;, cache=True, token_usage=True)<br><br># Generate a response<br>usr_message = &quot;ONLY generate a positive word&quot;<br>client_response = llm.respond(usr_message, verbal=True)</pre><p>The cache and token usage details are neatly organized in:</p><pre>~/my_project/llmtrack/openai/gpt-4o-mini</pre><h3>Easily Monitor Your Usage</h3><p>LLMTrack makes it easy to inspect your token usage and verify cache contents:</p><pre># Token Usage<br>usage = llm.token_usage<br>print(&#39;Token Usage:&#39;, usage)<br><br># Check Cache<br>cache_key = llm.get_cache_key(usr_message)<br>print(&#39;Cache:&#39;, llm.cache[cache_key])</pre><h3>Supported Models &amp; Clients</h3><p>LLMTrack seamlessly integrates with popular LLM APIs:</p><ul><li><strong>OpenAI</strong>: Supports models like gpt-4o-mini, gpt-3.5-turbo, and more (<a href="https://platform.openai.com/docs/models">all models</a>).</li><li><strong>Azure OpenAI</strong></li><li><strong>MoonShot</strong>: e.g., moonshot/moonshot-v1-8k</li><li><strong>Groq</strong>: Supports models listed in <a href="https://console.groq.com/docs/models">Groq’s documentation</a>.</li></ul><p>Just set the appropriate environment variables, and you’re good to go!</p><h3>Enhance Productivity, Reduce Costs</h3><p>Hopefully, you can stop worrying about repetitive API costs and start efficiently tracking your LLM interactions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cae5a8556feb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/efficiently-track-and-cache-your-llm-api-usage-with-llmtrack-cae5a8556feb">Efficiently Track and Cache Your LLM API Usage with LLMTrack</a> was originally published in <a href="https://levelup.gitconnected.com">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming LLMs Step-by-Step(Part 1): Pre-Training Large Language Models in PyTorch]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/comprehensive-guide-to-training-large-language-models-in-pytorch-4c50f4c5af7b?source=rss-23bba04f5843------2"><img src="https://cdn-images-1.medium.com/max/2600/0*-ZWDsU0nAYpBWeoH" width="5724"></a></p><p class="medium-feed-snippet">A Step-by-Step Tutorial on Transformer Architecture, Data Preparation, and Practical Training Techniques from Scratch</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/comprehensive-guide-to-training-large-language-models-in-pytorch-4c50f4c5af7b?source=rss-23bba04f5843------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/comprehensive-guide-to-training-large-language-models-in-pytorch-4c50f4c5af7b?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c50f4c5af7b</guid>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Sun, 19 May 2024 11:09:04 GMT</pubDate>
            <atom:updated>2024-05-21T04:46:03.894Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Implementation of LLM Agents: Should You Opt for LangChain?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/implementation-of-llm-agents-should-you-opt-for-langchain-8e7fec937a58?source=rss-23bba04f5843------2"><img src="https://cdn-images-1.medium.com/max/2600/0*K_SeCWPt6Z9GwWPu" width="2765"></a></p><p class="medium-feed-snippet">Comparing LangChain and From-Scratch Implementations</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/implementation-of-llm-agents-should-you-opt-for-langchain-8e7fec937a58?source=rss-23bba04f5843------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/implementation-of-llm-agents-should-you-opt-for-langchain-8e7fec937a58?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7fec937a58</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 21:52:28 GMT</pubDate>
            <atom:updated>2025-03-12T09:29:24.136Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From Theory to Code in Machine Learning (Part 2): Maximum Likelihood Estimation for Classification]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/from-theory-to-code-maximum-likelihood-estimation-for-classification-tasks-6ecd8d075eed?source=rss-23bba04f5843------2"><img src="https://cdn-images-1.medium.com/max/2600/0*N6PMfLDWD1gAlSkK" width="3504"></a></p><p class="medium-feed-snippet">Implementing Logistic Regression from Scratch in Python</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/from-theory-to-code-maximum-likelihood-estimation-for-classification-tasks-6ecd8d075eed?source=rss-23bba04f5843------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/from-theory-to-code-maximum-likelihood-estimation-for-classification-tasks-6ecd8d075eed?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ecd8d075eed</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 03:45:33 GMT</pubDate>
            <atom:updated>2024-04-24T13:51:14.894Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis: A Comprehensive Explanation]]></title>
            <link>https://levelup.gitconnected.com/principal-component-analysis-an-intuitive-mathematically-comprehensive-and-step-by-step-coding-e40f8a7f6417?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/e40f8a7f6417</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 03:57:42 GMT</pubDate>
            <atom:updated>2025-07-29T07:31:01.202Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Intuitive, Mathematically , and Step-by-Step Coding Guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J3J0WcazE-2tOA-Y" /><figcaption>Photo by <a href="https://unsplash.com/@sortino?utm_source=medium&amp;utm_medium=referral">Joshua Sortino</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the ever-expanding world of data, understanding the underlying patterns and extracting meaningful insights is crucial for making informed decisions. One of the powerful tools at our disposal for simplifying complex data sets into understandable formats is Principal Component Analysis (PCA). This blog post aims to unravel the intuition and comprehensive methodology behind PCA. We will explore the concepts of <strong>decorrelation </strong>and <strong>variance maximization</strong>. These concepts are pivotal in transforming raw data into a reduced dimensional space, where the essence of the data is preserved while minimizing redundancy. Join us on this journey to demystify PCA, a cornerstone technique in the field of machine learning and data science, making it accessible and intuitive for enthusiasts and professionals alike.</p><h3>Section 1: Why Should We Reduce Data Dimension?</h3><p><strong>One Running Example — Book Review: </strong>Imagine you’re trying to organize a set of book reviews based on whether they speak positively or negatively about the books. Each review mentions words like “bad,” “good,” or “superb” a certain number of times. You decide to keep track by creating a chart: for each review, you note how often each of these words appears. This chart is your document-word matrix, where each cell represents the frequency of a word in a document. For simplicity, we will use hypothetical frequencies that reflect the sentiment of each document.</p><pre>data = np.array([<br>    # good superb<br>    [0,    0],  # D1: Neutral or negative<br>    [3,    0],  # D2: Moderately positive<br>    [5,    2],  # D3: Positive<br>    [2,    5]   # D4: Highly positive<br>])</pre><ul><li>D1 shows no mention of either “good” or “superb”, suggesting a neutral or negative review.</li><li>D2 features “good” without “superb”, indicating moderate positivity.</li><li>D3 and D4 show increasing usage of “superb” alongside “good”, moving from positive to highly positive sentiments.</li></ul><p><strong>Redundancy and Risk of Using Correlated Features — “good” and “superb”: </strong>When we consider both “good” and “superb” together in our analysis, especially using simpler prediction models that rely on word counting, we might run into issues with correlation. This is because if “good” and “superb” are often used together in the same reviews, just adding up their counts might not give us the full picture. For example, a review that mentions “good” several times and “superb” a few times might end up being treated the same as one that only mentions “good” many times, even though the presence of “superb” suggests a stronger positive sentiment. This correlation between “good” and “superb” usage — where they increase together — can lead us to oversimplify our understanding of the reviews. In other words, by just counting words without considering the strength of sentiment they represent, we could miss out on the nuances between different levels of positivity. This approach might cause us to overlook the subtle but important distinctions that separate moderately positive reviews from those that are highly positive, leading to a less accurate or nuanced model of sentiment prediction.</p><p><strong>Real-world Issues:</strong> In summary, real-world machine learning models, similar to the oversimplified word counting approach, can suffer from issues related to feature correlation and oversimplification across various domains, including regression, recommendation systems, and computer vision. These challenges stem from models not accounting for the nuanced relationships between features, leading to potential misinterpretations and inaccuracies. Specifically, in linear regression models, multicollinearity arises when independent variables are highly correlated. In this condition, the coefficients (or weights) assigned to the independent variables may not be accurately estimated. Note that the model might still predict well on average, but it does indicate specific problems related to the interpretation and stability of the coefficient estimates. For example, in real estate pricing models, features like the number of bedrooms and the size of the house might be correlated, complicating the interpretation of their individual contributions to the house price.</p><p>Hence, here is C<strong><em>laim 1: We want decorrelated data.</em></strong></p><h3>Section 2: Why Should We Maximize Variance?</h3><h4>Another Example — Friends’ Hangout Frequencies</h4><p>Here, we have two features across three different data points (people), representing their hangout frequency with two friends (Friend A and Friend B) in a week.</p><pre># the frequency of hangouts with Friend A and Friend B within a year.<br>hangout = np.array([<br>   #Friend A     Friend B<br>        [2,       3],    # Me<br>        [10,      4],    # Person 1<br>        [20,      5]     # Person 2<br>])<br>hangout = np.array([<br>   #Friend A     Friend B  <br>        [2,       3],    # Introverted Person (Me)<br>        [10,      4],    # Outgoing Person  (Person 1)<br>        [20,      5]     # Extremely Outgoing Person  (Person 2)<br>])</pre><p>To determine which feature is more useful, you can think of it in terms of <strong>consistency</strong> and <strong>variability</strong> among the given data points and how these aspects can help predict or understand new data points (new persons).</p><ul><li>Variability: Friend A shows a wide range of hangout frequencies: from 2 to 20 times a week. This variability means that how often someone hangs out with Friend A could tell us a lot about their social habits or preferences.</li><li>Consistency: Friend B, on the other hand, shows less variability (from 2 to 4 times a week), suggesting that people’s interactions with Friend B are more uniform.</li></ul><p>One thing I have to emphasize is that, although the hangout features always uniquely identify each data point, the <strong>overfitting </strong>issue does not correlate during the process of exploring patterns. In modeling for predicting each data point (person), it definitely leads to overfitting, as the model might learn the specificities of the training data too closely, impairing its ability to generalize to new, unseen data. However, exploring patterns within the data, as opposed to individual identification, focuses on uncovering broader trends and relationships. This does not lead to overfitting since we do not care about each data point but the general pattern underlying the data.</p><p>Therefore, here is <strong><em>Claim 2: A Features with greater variance often have more predictive power, i.e., maximizing variance.</em></strong></p><p>Someone said Friend A is more friendly and hangs out more often. That’s why they choose A. Ok. Let’s look at an update one:</p><pre># the frequency of hangouts with Friend A and Friend B within a year.<br>hangout = np.array([<br>   #Friend A     Friend B  Friend C<br>        [2,       3,        12],    # Introverted Person<br>        [10,      4,        12],    # Outgoing Person <br>        [20,      5,        12]     # Extremely Outgoing Person <br>])</pre><p>Let’s go back to the book review example.</p><p><strong>Selecting Features According to Variation (Variance): </strong>Using the code snippet below, we can clearly see the variance of both features, as shown in Figure 1.</p><pre>good = data[:,0]<br>superb = data[:,1]<br>fig, ax = plt.subplots(figsize=(5, 3))<br>ax.hist(good, bins=15, alpha=1, label=f&#39;Var(good)={np.var(good):.2f}&#39;)<br>ax.hist(superb, bins=15, alpha=0.5, label=f&#39;Var(superb)= {np.var(superb):.2f}&#39;)<br>ax.set_title(&#39;Variance Demonstration&#39;)<br>ax.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*DEC157etoLzMPh5aprW4xA.png" /><figcaption>Figure 1: Variance of Word Frequency. The vertical axis shows the frequency of word frequency.</figcaption></figure><p>According to <strong><em>the Claim 2</em></strong>, we should choose the “superb” feature to represent data to reduce data dimension. However, solely focusing on “superb” risks losing information about moderately positive reviews, like D2, where “good” is present but “superb” is not. This exclusion could lead to an incomplete understanding of the sentiment spectrum represented in the data.</p><p>Therefore, here is <strong><em>Claim 3: New features should be generated by considering all the existing features.</em></strong></p><h3>Section 4: Principal Component Analysis</h3><p>PCA is designed to generate new dimensions (features) to satisfy all the three claim above, Specifically, it finds projection vectors, each of them meeting the two desired properties<strong><em>.</em></strong></p><ul><li>Maximizing variance: Data is projected onto the directions that spread out the data.</li><li>Orthogonality and Decorrelation: The directions are orthogonal to each others.</li></ul><p>This is what PCA does via the following processes:</p><ol><li>Computing the covariance matrix of the centered data (centering data with mean =0).</li><li>Performing Eigenvalue Decomposition on the covariance matrix to obtain the eigenvectors and eigenvalues.</li><li>Ordering the eigenvectors by decreasing eigenvalues and choosing a subset to form a matrix of principal components.</li><li>Transforming the original data through this matrix to obtain the reduced dataset.</li></ol><p>Generally, PCA identifies directions (eigenvectors <em>p</em>) in the feature space where the data (as represented by the covariance matrix <em>A</em>) shows the most spread or variance. To fully understand how these steps lead to eigenvectors satisfying the above two properties, let’s delve into the two important mathematical concepts: Covariance and Eigenvector (and corresponding eigenvalues).</p><h4>Section 4.1: Covariance</h4><p>Covariance is the average of the product of the differences of each data point between two features/variables from the sample mean. Covariance matrix is just a square matrix that describes the covariance between each pair of variables in a dataset, while the covariance between a variable itself is actually the variance. Below are the calculations in Python.</p><pre>def covar(x, y):<br>    &quot;&quot;&quot; Covariance of two variables.<br>    Args:<br>        x, y (np.ndarray): Two NumPy arrays of the same length.&quot;&quot;&quot;<br>    return np.sum((x - x.mean())*(y - y.mean()))/len(x)<br><br>def covar_matrix(X):<br>    &quot;&quot;&quot; Covariance matrix of a dataset.<br>    Args:<br>        X (np.ndarray): A NumPy array of shape (n_samples, n_features).&quot;&quot;&quot;<br>    n_samples, n_features = X.shape<br>    covar_matrix = np.zeros((n_features, n_features))<br>    for i in range(n_features):<br>        for j in range(n_features):<br>            covar_matrix[i, j] = covar(X[:, i], X[:, j])<br>    return covar_matrix</pre><p>No worries if the mathematical expression cannot give you an intuitive understanding : what is covariance? why does the covariance matrix help achieve the above goals? No worries. Let’s see it in examples.</p><p><strong>Covariance: Tracking the Harmony Between Two Variables.</strong> With the hangout data, you’re trying to figure out which groups of friends like to hang out together. The covariance matrix is like our way of keeping track of these appearances. It tells us if “Friend A” and “Friend A” often show up together (they’re positively related), if one shows up when the other doesn’t (negatively related), or if they don’t have much to do with each other at all. One confusion may be why the calculation of covariance requires the subtraction of sample means.Let’s think about each sample mean of a variable as a baseline, i.e., the number of occurrences without preference. So, only the co-occurrences removing the average can reflect its ture preference to hanging out with another friend or whether the words are highly correlated. Otherwise, the large number of co-occurrences may be just because the person is too outgoing or the word is very common, e.g., “the”, “a”.</p><p>Why does the covariance matrix help achieve our goals?<strong> </strong>Tracking the underlying correlation structure of the data (e.g., which words move together) is a good way to explain the global relationships between features in our data with as few explanations as possible. In other words, we can start to see our data in simpler, clearer ways, like finding the main reasons people come to the party or the semantic groups of words.</p><h4>Section 4.2: EigenDecomposition on Covariance Matrix</h4><p>As defined in Wikipedia, “a(nonzero) vector <strong>v</strong> of dimension <em>N</em> is an eigenvector of a square <em>N</em> × <em>N</em> matrix <strong>A</strong> if it satisfies a linear equation of the for Ap=λp”.</p><p><strong>Why does p in Ap=λp,where A is a covariance matrix, relate to an axis transforming original data with a refection of dataset variance? </strong>In the context of a covariance matrix, <em>p</em>, being an eigenvector, serves as a unique axis where the covariance matrix’s action is reduced to simple scaling. This scaling, quantified by <em>λ</em>, directly corresponds to the variance of data along <em>p</em> because it’s the measure of how much <em>A</em> stretches <em>p</em>. In essence, <em>p</em> isolates a specific “mode” or pattern of variance within the dataset, with <em>λ</em> quantifying the magnitude of this variance. This connection between <em>λ</em> and the variance along <em>p</em> underpins can be used to construct projection matrix, consisting of eigenvectors sorted by their corresponding eigenvalues<em>, </em>to transform the original data.</p><p>Let’s look at the eigenvalues and eigenvectors in the example of word-document matrix. After running the code below to following the first three steps of PCA:</p><ul><li>Computing covariance matrix</li><li>Performing Eigenvalue Decomposition</li><li>Ordering the eigenvalues and eigenvectors</li></ul><p>The results of eigenvectors (the components used to transform the original data satisfying the two goals — Maximizing variance and keeping orthogonality), as shown in <em>Figure 3</em> below.</p><pre>def covar(x, y):<br>    &quot;&quot;&quot; Covariance of two variables.<br>    It measures how two variables change together by <br>     the average of the product of the differences of each data point from the sample mean.<br>    Equation: cov(x, y) = Σ (x_i - mean(x)) * (y_i - mean(y)) / n<br>    Args:<br>        x, y (np.ndarray): Two NumPy arrays of the same length.&quot;&quot;&quot;<br>    return np.sum((x - x.mean())*(y - y.mean()))/len(x)<br><br>def covar_matrix(X):<br>    &quot;&quot;&quot; Covariance matrix of a dataset.<br>    It is a square matrix that describes the covariance between two or more variables in a dataset.<br>    Args:<br>        X (np.ndarray): A NumPy array of shape (n_samples, n_features).&quot;&quot;&quot;<br>    n_samples, n_features = X.shape<br>    covar_matrix = np.zeros((n_features, n_features))<br>    for i in range(n_features):<br>        for j in range(n_features):<br>            covar_matrix[i, j] = covar(X[:, i], X[:, j])<br>    return covar_matrix<br><br># plot eigenvectors on the data plot marked by components<br>def plot_eigenvectors(data, eigenvector):<br>    fig, ax = plt.subplots()<br>    ax.scatter(data[:,0], data[:,1])<br>    # add label on the data points<br>    labels = [&#39;Negative&#39;, &#39;Positive&#39;, &#39;Moderately Positive&#39;, &#39;Strongly Positive&#39;]<br>    for i in range(data.shape[0]):<br>        ax.text(data[i,0], data[i,1], labels[i], fontsize=6, ha=&#39;right&#39;)<br>    for i in range(2):<br>        ax.quiver(0, 0, eigenvector[i,0], eigenvector[i,1], angles=&#39;xy&#39;, scale_units=&#39;xy&#39;, scale=1, color=&#39;red&#39;)<br>        ax.text(eigenvector[i,0], eigenvector[i,1], f&#39;Component {i+1}&#39;, fontsize=6)<br>    ax.set_aspect(&#39;equal&#39;)<br>    ax.set_xlim(-1, 6)<br>    ax.set_ylim(-1, 6)<br>    plt.show()<br><br># Step1: Computing covariance matrix (divides by n-1 for populatoin covariance)<br>covmat=covar_matrix(data)* len(data) / (len(data) - 1)<br># Step2: Performing Eigenvalue Decomposition<br>lambd, eigenvector= np.linalg.eig(covmat)<br># Step3: Ordering the eigenvalues and eigenvectors<br>idx = lambd.argsort()[::-1]<br>lambd = lambd[idx]<br>eigenvector = eigenvector[:,idx]<br>print(&#39;Eigen values: {}&#39;.format(lambd))<br>print(&#39;Eigen vectors: {}&#39;.format(eigenvector))<br>plot_eigenvectors(data, eigenvector)<br># Covariance matrix: <br># [[4.33333333 0.83333333]<br>#  [0.83333333 5.58333333]]<br># Eigen values: [6.         3.91666667]<br># Eigen vectors: [[-0.4472136  -0.89442719]<br>#  [-0.89442719  0.4472136 ]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*QEeaE4a4lASCOHqsT6vOyA.png" /><figcaption>Figure 3: The first two eigenvectors/components. The graph is returned via the above code.</figcaption></figure><h4>Section 4.3: Transforming Data with Eigenvectors</h4><p>From the visualization, it’s evident that each eigenvector serves as a means to project high-dimensional data onto a line, thus creating a transformed feature that encapsulates a significant aspect of the data’s variance. But a question arises: “How could we calculate these transformed values?” The process involves using the dot product between the original data and each eigenvector, allowing us to transform the data into a new dimensional space defined by the principal components.</p><pre># Step4: Projecting the data onto the new feature space<br># matrix propagation<br>data_pca = np.dot(data-data.mean(axis=0), eigenvector) <br>print(data_pca)<br></pre><h4>Section 4.4: Proving The Above Claims</h4><p>C<strong><em>laim1: We want decorrelated data.</em></strong> By running the code below, we can see the covariance approximates to zero, indicating a data with decorrelated features.</p><pre>covar(data_pca[:,0], data_pca[:,1])<br># 2.220446049250313e-16-&gt; approximating to 0</pre><p><strong><em>Claim 2: Features with greater variance often have more predictive power, i.e., maximizing variance. </em></strong>If you compare these two values with the variances of the original feature (4.19, 3.25 as shown in Figure 1), the variance on the 1st component (4.5) is always larger than them. Although the variance on the 2nd component (2.93) is smaller, the key is that it is orthogonal, i.e., removing correlation.</p><pre># Step4: Projecting the data onto the new feature space<br>data_pca1 = np.dot(data, eigenvector[:,0]) <br>data_pca2 = np.dot(data, eigenvector[:,1])<br>print(&#39;Variance of PCA transformed data: {}, {}&#39;.format(var(data_pca1), var(data_pca2)))<br>print(&#39;Explained Variance Ratio: {}&#39;.format(lambd/np.sum(lambd)))<br># Variance of the transformed data: 4.5, 2.9375000000000004<br># Explained Variance Ratio: [0.60504202 0.39495798]</pre><p>We can visualize the original feature with the maximum variance (“superb”) and the one projected on the 1st component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*5A9opDPVX03wJew3pUUw9w.png" /><figcaption>Figure 1: Feature with maximum variance v.s. Projection on the 1st component. Both are centered for comparison.</figcaption></figure><p>Finally, let’s verify that the population variances of transformed data are indeed <strong>λ,</strong> as shown below.</p><pre>print(&#39;Variance of PCA transformed data: {}, {}&#39;.format(var(data_pca1)*len(data)/(len(data)-1), var(data_pca2)*len(data)/(len(data)-1)))<br># Variance of PCA transformed data: 6.0, 3.9166666666666674</pre><p><strong><em>Claim 3: both features should be considered to transform into one feature. </em></strong>It is very obvious. Because dot product between an eigenvector and each data point leads to a linear transformation of both features (“good” and “superb”). But this is also related to the limitation of transformed data from PCA: They hardly maintain the non-linear correlations.</p><h3>Conclusion</h3><p>Principal Component Analysis stands as a monumental technique in the realm of data analysis and machine learning, offering a window into the underlying structure of complex datasets. By embarking on a journey through sentiment analysis in book reviews, we have witnessed firsthand the transformative power of PCA in isolating key features that embody the most significant variations within data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e40f8a7f6417" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/principal-component-analysis-an-intuitive-mathematically-comprehensive-and-step-by-step-coding-e40f8a7f6417">Principal Component Analysis: A Comprehensive Explanation</a> was originally published in <a href="https://levelup.gitconnected.com">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Inference v.s. Statistical Estimation v.s. ML Inference]]></title>
            <link>https://medium.com/@sergioli/statistical-inference-v-s-statistical-estimation-v-s-ml-inference-03f79404645a?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/03f79404645a</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 22:52:35 GMT</pubDate>
            <atom:updated>2024-03-18T22:58:07.991Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post is used to reflect my students (also myself ) of some coarse arguments during the initial learning of statistical concepts.</p><p>Before providing my arguments, let’s look at the definitions from t<a href="https://online.stat.psu.edu/stat504/lesson/statistical-inference-and-estimation">he PSU’s lecture material</a>:</p><blockquote>A statistical inference aims at learning characteristics of the population from a sample; the population characteristics are parameters and sample characteristics are statistics.</blockquote><blockquote>Estimation represents ways or a process of learning and determining the population parameter based on the model fitted to the data.</blockquote><p><strong>Argument 1: Statistical Inference and Estimation are Essentially the Same</strong></p><p>This argument is rooted in the observation that both statistical inference and estimation aim to learn about population parameters using sample data. Indeed, the core objective of both processes is to generalize findings from a sample to the broader population, thereby making them seem fundamentally similar.</p><p>However, statistical inference encompasses a broader set of activities than estimation alone. While estimation focuses on determining the values of population parameters (like means or proportions), <strong><em>inference also includes hypothesis testing, confidence interval construction, prediction, and more</em></strong>. Estimation is a component of inference, specifically concerned with the calculation of an estimate of a parameter. So, while they share a common goal of understanding population parameters, inference covers a wider array of statistical processes. Below are specific perspectives:</p><ol><li><strong>Hypothesis Testing</strong>: Evaluating hypotheses about the population parameters, using sample data. This involves determining the likelihood of observing the sample data under different assumptions (null vs. alternative hypotheses) and making decisions about which hypothesis is more consistent with the observed data.</li><li><strong>Model Selection and Comparison</strong>: Inference involves comparing different statistical or machine learning models to determine which best describes the observed data, often using criteria that balance fit and complexity (e.g., Akaike Information Criterion, Bayesian Information Criterion).</li><li><strong>Predictions and Generalization</strong>: Making predictions or decisions based on the data and models, and understanding the reliability and applicability of these predictions to the broader population.</li></ol><p><strong>Argument 2: The Difference Lies in the Requirement of a Model for Estimation</strong></p><p>Both statistical inference and estimation can involve models, but the emphasis on models may vary depending on the specific approach or context.</p><p><strong>Estimation often directly involves fitting models to data to derive parameter estimates</strong>: It indeed often involves the use of statistical models to determine the value of population parameters. These models help to account for randomness and uncertainty in the data, enabling the derivation of point estimates (single values) and interval estimates (ranges of values) for parameters. The process of estimation can be as simple as calculating a sample mean to estimate a population mean or as complex as fitting a regression model to estimate relationships between variables.</p><p><strong>Statistical Inference can either rely on model-based approaches or employ model-free methods</strong>: While it can involve model-based approaches, statistical inference also includes model-free methods, such as non-parametric tests or basic hypothesis testing that does not explicitly rely on a parametric model of the data distribution. Inference is about making judgments or drawing conclusions about population parameters, which can involve estimation but also goes beyond it to include testing hypotheses about those parameters.</p><p><strong>Argument 3: Machine Learning Inference Prioritizes Predictions, a Component of Statistical Inference</strong></p><p><strong>Overlap with Statistical Inference</strong>: 1) Machine learning and statistical inference share common ground in that they both employ mathematical models to draw conclusions from data. 2) ML models prioritize the ability to generalize from learned data to make predictions about unseen data. This focus aligns with the prediction aspect of statistical inference, where the goal is to use sample data to make inferences about future or unknown outcomes.</p><p><strong>Distinction</strong>: The distinction lies in the fact that ML models often do not focus on understanding relationships between variables and estimated parameters and hypothesis testing, with a strong emphasis on model assumptions and theoretical underpinnings. Instead, Machine learning inference prioritizes performance and accuracy of predictions over strict adherence to statistical assumptions, emphasizing computational methods and algorithmic innovation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03f79404645a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Wrangling and Preprocessing in Python: A Practical Guide]]></title>
            <link>https://medium.com/@sergioli/data-wrangling-and-preprocessing-in-python-a-practical-guide-345aa2e55439?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/345aa2e55439</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 05:41:09 GMT</pubDate>
            <atom:updated>2024-03-11T05:41:09.284Z</atom:updated>
            <content:encoded><![CDATA[<p>Consider a dataset intended for a rating system, which spans a range from 1 to 10 but includes an outlier (100) and a missing value (NA): [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, NA]. Addressing the peculiarities of this dataset involves several critical steps:</p><ul><li>Understanding the Dataset Through Sample Statistics (noting the small size of this example compared to typically larger datasets)</li><li>Handling Missing or Incomplete Values</li><li>Identifying and Removing Outliers</li></ul><p>For preprocessing multivariate data in preparation for machine learning applications, it’s crucial to:</p><ul><li>Normalize the data, utilizing techniques such as Min-Max Scaling.</li></ul><h3>Section 1: Understanding the Dataset Through Sample Statistics</h3><p>Sample statistics provide a snapshot of the data’s characteristics, offering insights into its central tendency, spread, and shape. Among the most common sample statistics are the mean, median, variance, standard deviation, and skewness, each serving a unique purpose in data analysis.</p><h4>Sample Mean (Average):</h4><p>The sample mean is the sum of all observations divided by the number of observations. However, the mean is sensitive to outliers, which can significantly skew its value away from the center of the majority of the data. We will further analyze such effect in the next section for handling missing values.</p><pre>mean = sum(data) / len(data)<br>print(mean)</pre><h4>Median:</h4><p>The median is the middle value when the dataset is ordered from smallest to largest. For an even number of observations, it is the average of the two middle numbers. The median is less sensitive to outliers than the mean and often provides a better measure of central tendency for skewed data.</p><pre>data_sorted = sorted(data)<br>n = len(data_sorted)<br>median = data_sorted[n//2] if n % 2 != 0 else (data_sorted[n//2 - 1] + data_sorted[n//2]) / 2<br>print(median)</pre><h4><strong>Variance:</strong></h4><p>Variance measures the dispersion of a dataset. It is calculated as the average of the squared differences from the mean. A higher variance indicates that the data points are more spread out from the mean.</p><pre>variance = sum((x - mean) ** 2 for x in data) / (len(data) - 1)</pre><h4>Standard Deviation:</h4><p>The standard deviation is the square root of the variance. It provides a measure of the spread of the data points around the mean in the same units as the data.</p><pre>standard_deviation = variance ** 0.5</pre><h4>Skewness:</h4><p>Skewness measures the asymmetry of the distribution of values about the mean. A positive skewness indicates a right-skewed distribution with a long tail on the right, while a negative skewness indicates a left-skewed distribution with a long tail on the left.</p><pre>from scipy.stats import skew<br>skewness = skew(data)</pre><p>Understanding these sample statistics is crucial for effectively analyzing and interpreting data. They provide the foundational knowledge needed to assess the distribution’s characteristics and make informed decisions about handling missing values and other data preprocessing steps.</p><h3>Section 2: Handling Missing or Incomplete Values</h3><p>When dealing with skewed datasets, particularly those with a right-skewness, selecting the appropriate method for filling in missing values is crucial. The presence of outliers can significantly distort measures like the mean, making it unsuitable for representing the central tendency of the majority of the data.</p><h4>Understanding the Skewness:</h4><p>A dataset with extreme right-skewness, such as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, NA], is characterized by the majority of values clustering at the lower end and a long tail extending towards higher values. This can be quantitatively confirmed using the skew function from scipy.stats:</p><pre>from scipy.stats import skew<br>print(&quot;Skewness: &quot;, skew(right_skewed))<br># Skewness:  2.7937162913590363</pre><h4>The Problem with the Mean:</h4><p>In right-skewed distributions, the mean is inflated by the outliers ( leadning to positive skewness) and does not effectively represent the central tendency for the bulk of the data:</p><pre>print(&quot;Mean: &quot;, sum(right_skewed)/len(right_skewed))<br># Mean:  14.090909090909092</pre><h4>Median: The Better Alternative:</h4><p>The median, being the middle value of a sorted dataset, is less affected by outliers and provides a more accurate representation of the dataset’s central tendency:</p><pre>right_skewed_sorted = sorted(right_skewed)<br>n = len(right_skewed_sorted)<br>median = right_skewed_sorted[n//2] if n % 2 != 0 else (right_skewed_sorted[n//2 - 1] + right_skewed_sorted[n//2]) / 2<br>print(&quot;Median: &quot;, median)<br># Median:  6</pre><h3>Section 3: Identifying and Removing Outliers</h3><p>To avoid the above effect due to outliers, we can use the outlier detection methods.</p><h4>Visualizing Data Distribution</h4><p>A histogram plot helps visualize the distribution (e.g., variance and skewness), supporting the choice of median over mean for filling missing values:</p><pre>from matplotlib import pyplot as plt<br>plt.hist(right_skewed, bins=5, color=&#39;c&#39;, edgecolor=&#39;k&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*enMbEWNVZjGRqcHpnjTI_Q.png" /></figure><h4>Visualizing IQR Statistics</h4><p>A boxplot (or box-and-whisker plot) graphically depicts the distribution of a dataset based on a five-number summary: minimum, first quartile (Q1), median (second quartile, Q2), third quartile (Q3), and maximum. Interquartile Range (IQR) is calculated as the difference between the third quartile (Q3) and the first quartile (Q1). It represents the range within which the middle 50% of the data points lie.</p><pre>plt.boxplot(right_skewed)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*vjrpcBPMfZPTT8Lz3uouOA.png" /></figure><p>To identify potential outliers on the lower end of the data, 1.5 times the IQR is subtracted from the first quartile (Q1). Any data points that fall below this value are considered outliers. Mathematically, the lower bound for outliers is calculated as<em> Q1−1.5×IQR</em>.</p><p>To identify potential outliers on the upper end of the data, 1.5 times the IQR is added to the third quartile (Q3). Any data points that fall above this value are considered outliers. Mathematically, the upper bound for outliers is calculated as <em>Q</em>3+1.5×<em>IQR</em>.</p><pre>import numpy as np<br><br># Example dataset<br>data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100])<br><br># Calculate the first quartile (Q1) and third quartile (Q3)<br>Q1 = np.percentile(data, 25)<br>Q3 = np.percentile(data, 75)<br><br># Calculate the Interquartile Range (IQR)<br>IQR = Q3 - Q1<br><br># Calculate the lower and upper bounds for outliers<br>lower_bound = Q1 - 1.5 * IQR<br>upper_bound = Q3 + 1.5 * IQR<br><br># Print the results<br>print(f&quot;First Quartile (Q1): {Q1}&quot;)<br>print(f&quot;Third Quartile (Q3): {Q3}&quot;)<br>print(f&quot;Interquartile Range (IQR): {IQR}&quot;)<br>print(f&quot;Lower Bound for Outliers: {lower_bound}&quot;)<br>print(f&quot;Upper Bound for Outliers: {upper_bound}&quot;)<br># First Quartile (Q1): 3.5<br># Third Quartile (Q3): 8.5<br># Interquartile Range (IQR): 5.0<br># Lower Bound for Outliers: -4.0<br># Upper Bound for Outliers: 16.0</pre><h3>Section 4: Normalizing Data</h3><p>Data normalization is a crucial preprocessing step in machine learning, especially when dealing with features that vary in scale, distribution, or range. Specifically, if one feature (e.g., weight in kilograms) has a smaller numerical range compared to another feature (e.g., height in centimeters), it might contribute less to the model’s decision process simply because its values are lower in magnitude, not because the numerical range is larger.</p><p>Normalization techniques, such as Min-Max Scaling or Z-Score Normalization, are used to ensure that each feature contributes appropriately to the model by scaling them to a common range or distribution.</p><pre>import numpy as np<br><br># Sample height and weight data<br>heights = np.array([160, 175, 180, 190, 200])  # in cm<br>weights = np.array([55, 65, 75, 85, 95])  # in kg<br><br># Min-Max Scaling<br>heights_scaled = (heights - heights.min()) / (heights.max() - heights.min())<br>weights_scaled = (weights - weights.min()) / (weights.max() - weights.min())<br>print(&quot;Scaled Heights:&quot;, heights_scaled)<br>print(&quot;Scaled Weights:&quot;, weights_scaled)<br><br># Z-score normalization<br>heights_scaled = (heights - np.mean(heights)) / np.std(heights)<br>weights_scaled = (heights - np.mean(weights)) / np.std(weights)<br>print(&quot;Scaled Heights:&quot;, heights_scaled)<br>print(&quot;Scaled Weights:&quot;, weights_scaled)<br><br></pre><h3>Summary</h3><p>Through understanding sample statistics, managing missing values, eliminating outliers, and normalizing data for machine learning applications, this guide offers a comprehensive approach to preparing datasets for effective analysis and model training.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=345aa2e55439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Theory to Code in Machine Learning (Part 1): Maximum Likelihood Estimation in Regression]]></title>
            <link>https://levelup.gitconnected.com/statistical-estimation-for-machine-learning-ad1d6135ba62?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad1d6135ba62</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 06:54:13 GMT</pubDate>
            <atom:updated>2024-04-24T03:51:34.236Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing Linear Regression from Scratch in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Xb4CBE0Psb-BIa6I" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha">Fabio</a> on <a href="https://unsplash.com/photos/a-white-cube-with-a-yellow-and-blue-logo-on-it-ZIPFteu-R8k?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><strong>The Maximum Likelihood Estimation (MLE) principle </strong>provides a general starting point to determine certain criterion (optimization objectives) for optimization, which lead to the estimated values of parameters (characteristics of population). This article will introduce it from scratch and estimate the parameters of linear regression.</p><h3>Section 2: When Do We Need Statistical Estimation?</h3><h4>Section 2.1: No Statistical Estimation. First-principle, Physical Formulas</h4><p>Firstly, let’s consider the case without statistical estimation. Normally, when we want to model something, we “reason” over the case and develop professional domain knowledge through the study of underlying first principles for both <strong>physical formulas and parameters</strong>. This method relies heavily on a deep understanding of the theoretical foundations of a problem. The major advantage of this approach is its reliance on established scientific laws and principles, which can provide accurate and explainable models. However, this method might be limited in scenarios where the underlying principles are not well understood or too complex to model directly.</p><p><strong>An Example</strong>: The concept of mass-energy equivalence is encapsulated in the famous equation formulated by Albert Einstein, E=m c². The equation directly relates the mass of an object (<em>m</em>) to its energy equivalence (<em>E</em>) with <em>c</em> representing the speed of light in a vacuum, approximately 3.00×10⁸ meters per second. The insight of relating m to E was not directly derived from experimental data but from Einstein’s deep reflections on the nature of space, time, and energy.</p><p><strong>Limitation</strong>: Although first-principle derivation excels in areas with well-understood physical laws and offers models with high interpretability and theoretical justification, complex or poorly understood phenomena require leveraging data to uncover patterns and relationships that may not be apparent from theoretical analysis alone. That’s where we need statistical estimation.</p><blockquote>Sometimes, only function forms can be determined by first-principle reasoning. Hence, statistical estimation is still required as a complementary approach to estimate parameters. Often, this first-principle approach may involve statistical analysis: <strong>Understanding Underlying Data Distribution</strong>, as discussed in the beginning.</blockquote><h4>Section 2.2: Statistical Estimation for Parameters</h4><p>When the exact physical formulas or principles are unknown or too complex, a general universal approximator (neural network) or a hypothesized formula are commonly developed. Then, statistical estimation methods can be used to approximate their parameters using existing data.</p><p><strong>Pros &amp; Cons: </strong>Statistical estimation offers flexibility and is particularly powerful in handling large datasets and complex relationships that are not easily modeled using first principles alone. However, it may lack the interpretability and theoretical grounding of models derived from first principles, and its accuracy is heavily dependent on the quality and quantity of available data.</p><p><strong>An Example: </strong>Let’s take an intuitive example from the Natural Language Processing (NLP) domain to illustrate the concept of statistical estimation: sentiment analysis. <br>Imagine you’re tasked with developing a model that can automatically determine whether a piece of text (like a product review) expresses a positive, negative, or neutral sentiment. The first-principle derivation approach would require understanding and modeling the complex rules of language, including grammar, idioms, sarcasm, and other nuanced features that contribute to sentiment. This is highly challenging due to the vast complexity and variability of natural language.<br>So we need to apply statistical estimation. Instead of trying to manually codify these rules, you opt for a statistical estimation approach. You collect a large dataset of text reviews, each labeled with its corresponding sentiment (positive, negative, or neutral) by human annotators. You then use this dataset to train a machine learning model, such as a neural network, to estimate the function <em>fθ</em>​ that maps input text to sentiment labels.</p><h3>Section 3: Objective — Maximizing Likelihood</h3><p>The intuitive objective is to choose a set of model parameters <em>θ </em>that is most probable according to the observed data: features <em>x</em> and the labels <em>y, i.e., maximizing </em>the posterior probability of <em>P</em>(<em>θ</em>∣<em>x</em>,<em>y</em>). It is barely impossible to know this. However, according to the Bayes rule, we know</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*NzHF1W-aT4QwHdF9Y7CAAQ.png" /></figure><p><strong><em>P</em></strong><strong>(</strong><strong><em>θ</em></strong><strong>∣</strong><strong><em>x</em></strong><strong>,</strong><strong><em>y</em></strong><strong>)-&gt; </strong><strong><em>P</em></strong><strong>(</strong><strong><em>y</em></strong><strong>,</strong><strong><em>x</em></strong><strong>∣</strong><strong><em>θ</em></strong><strong>)</strong>: Utilizing Bayes’ theorem allows us to express the posterior probability <em>P</em>(<em>θ</em>∣<em>x</em>,<em>y</em>) in terms of the likelihood <em>P</em>(<em>y</em>,<em>x</em>∣<em>θ</em>), the prior probability <em>P</em>(<em>θ</em>), and the marginal likelihood <em>P</em>(<em>x</em>,<em>y</em>). When the goal is to find the parameter set <em>θ</em> that maximizes the posterior probability given the data (features <em>x</em> and labels <em>y</em>), we can simplify the optimization problem by focusing on maximizing the numerator of the Bayes’ formula because the denominator <em>P</em>(<em>x</em>,<em>y</em>) is independent of <em>θ</em> and acts as a constant normalization factor. Specifically, in the context of parameter estimation, the focus often shifts to maximizing <em>P</em>(<em>y</em>,<em>x</em>∣<em>θ</em>)⋅<em>P</em>(<em>θ</em>) because it directly influences the value of <em>P</em>(<em>θ</em>∣<em>x</em>,<em>y</em>). However, when assuming a uniform prior (where <em>P</em>(<em>θ</em>) is constant) or in situations where the prior knowledge about <em>θ</em> is not specifically leveraged, the problem simplifies further to maximizing the likelihood <em>P</em>(<em>y</em>,<em>x</em>∣<em>θ</em>) alone. This underlies the principle of Maximum Likelihood Estimation (MLE), where <em>P</em>(<em>θ</em>) is effectively considered constant and does not influence the optimization of <em>θ</em>.</p><p><em>P</em>(<em>y</em>,<em>x</em>∣<em>θ</em>) -&gt; <em>P</em>(<em>y</em>∣x, <em>θ</em>): Since <em>x</em> is known and fixed in supervised learning tasks, we often consider <em>x</em> as a given context rather than a variable we seek to model the distribution of. Thus, the model focuses on <em>y</em>’s distribution conditioned on <em>x</em> and <em>θ .</em></p><p>The total likelihood <em>L</em> on the sample (X, Y) is the product of <em>P</em>(<em>y</em>∣x, <em>θ</em>) for all n examples (x, y) in (X, Y) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*1ILL745YyT8BV1orNVUo2g.png" /></figure><blockquote>Note that the likelihood is not a probability distribution over <em>θ</em>(since it does not integrate to 1 over <em>θ</em>, but it is used to compare different values of <em>θ</em>in terms of how plausible they make the observed data appear.</blockquote><h3>Section 4: MLE for Regression Tasks</h3><p>Here is a function for linear regression: The predicted y <em>\hat{yi}</em>=<em>β</em>0​+<em>β</em>1​<em>xi</em>. To get the true y, we add the error term <em>ϵi :</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*kTU8OVUjfPqIVAP0PphsXg.png" /></figure><p>​ , where (xi, yi) is an example in training data.</p><p>In the context of linear regression, <em>ϵi</em>​ is typically assumed to be normally distributed around 0. It is intuitive considering that the random error is unlikely to be big if the linear regression model is a good choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*MF4NxMPOqmZ-01x1hvgAPA.png" /></figure><p>Now, we can derive the distribution of <em>P</em>(<em>y</em>∣x, <em>θ</em>) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*rv1NBmtGumvXBxzILqf45w.png" /></figure><p>Now, we can specify <em>P</em>(<em>yi</em>∣xi, <em>β</em>0​, <em>β</em>1) for the calculation of likelihood, where the right side of the equation below PDF for normal distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*w-B6EGYXkuXcptKIcEhplA.png" /></figure><p>The likelihood function for the entire dataset of <em>n</em> observations is the product of the individual probabilities for each data point, given the parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*Y9kVAHIU-lX4m7Q2xLJ4HQ.png" /></figure><p>To simplify the optimization, it’s common to take the logarithm of the likelihood function, converting the product into a sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*dibesVbr4X_0AaAYPZfZmw.png" /></figure><p>The maximization of the above function equals to minimize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*54M6ze-M5d-whIH0Dm_SLg.png" /></figure><p>Essentially, this process turns out to be equivalent to minimizing the sum of squared residuals, which is Ordinary Least Squares (OLS) objective when the variance is assumed to be constant.</p><p>With this MLE objective for linear regression (or OLS objective), we can easily know what are the optimal values for <em>β</em>0​, <em>β</em>1 because this is a convex function for both <em>β</em>0​, and <em>β</em>1 . According to some calculus knowledge, we can take the derivatives w.r.t. both <em>β</em>0​, <em>β</em>1 as 0, and then will have two equations for solving the problem. Below are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*RSyRbZKTL4X5dTQdrSDfQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*2Kxo377jKLF6Ae19oU7WLg.png" /></figure><p>You can watch my YouTube video for the step-by-step derivation of the results.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6o3TGLABTHc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6o3TGLABTHc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6o3TGLABTHc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec5877f1bab7d334e32dcd36fceae477/href">https://medium.com/media/ec5877f1bab7d334e32dcd36fceae477/href</a></iframe><h3>Section 5: Python Implementation</h3><p>Below is the code:</p><pre>def mle_estimate_for_linear_regression(X, Y):<br>    &quot;&quot;&quot;<br>    Parameters:<br>    - X: numpy array of independent variable values.<br>    - Y: numpy array of dependent variable values.<br><br>    Returns:<br>    - beta_0: Estimated intercept of the regression line.<br>    - beta_1: Estimated slope of the regression line.<br>    &quot;&quot;&quot;<br><br>    # Mean of X and Y<br>    X_mean = np.mean(X)<br>    Y_mean = np.mean(Y)<br><br>    # Calculate beta_1 (slope)<br>    beta_1 = np.sum((X - X_mean) * (Y - Y_mean)) / np.sum((X - X_mean) ** 2)<br><br>    # Calculate beta_0 (intercept)<br>    beta_0 = Y_mean - beta_1 * X_mean<br><br>    return beta_0, beta_1</pre><h3>Final Verification</h3><p>Below is the test code to verify the result.</p><pre>ture_beta_1 = 10<br>ture_beta_0 = 5<br>x = np.array([1, 2, 3, 4, 5])  <br>y = ture_beta_0 + ture_beta_1 * x <br>plot_regression_line(ture_beta_1, ture_beta_0, x, y)<br><br>beta_0, beta_1 = ols_estimate_for_linear_regression(x, y)<br>print(f&quot;beta_0: {beta_0}, beta_1: {beta_1}&quot;)</pre><p>Here is the output. beta_0: 5.0, beta_1: 10.0, same as the ture_beta_0 and ture_beta_1 . So, our closed-form solution is mathematically sound and works perfect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad1d6135ba62" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/statistical-estimation-for-machine-learning-ad1d6135ba62">From Theory to Code in Machine Learning (Part 1): Maximum Likelihood Estimation in Regression</a> was originally published in <a href="https://levelup.gitconnected.com">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Scripts, Modules andPackages]]></title>
            <link>https://levelup.gitconnected.com/python-scripts-modules-andpackages-232d5f749e64?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/232d5f749e64</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-package-management]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 12:50:42 GMT</pubDate>
            <atom:updated>2025-07-08T03:11:02.881Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying Python Scripts, Modules, and Packages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*9qYfvJfNwg24ciUl" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Rubaitul Azad</a> on <a href="https://unsplash.com/photos/a-white-cube-with-a-yellow-and-blue-logo-on-it-ZIPFteu-R8k?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Section 1: Scripts v.s. Modules</h3><p><strong>They look common </strong>since</p><ul><li>Both being Python files with .py extensions.</li><li>Both contain Python definitions (classes, functions, variables) and statements.</li></ul><p><strong>They are essentially different. </strong>If you search online, you can find many sources defining their use as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YjTPEVFygh3fKyFK-2CwA.png" /></figure><p>Think: Is hello.py below a Python module or script?</p><pre>print(&quot;hello, you are running a python code&quot;)</pre><h4><strong>Section 2: Python Modules</strong></h4><p>Why do we need it? Simply speaking, <strong>it enables code reuse with better readability and maintainability.</strong></p><p>For example, as a machine learning engineer, you commonly implement many models (e.g., Model-A, Model-B, Model-C) and metrics (e.g., Metric-A, Metric-B, Metric-C). Without Python module, you implement all the metrics for all the models.</p><ul><li><strong>Readability</strong>: The duplication challenges you for reading the code</li><li><strong>Maintainability</strong>: It also challenges you for maintaining the code. <br>For example, if you put the incorrect code below in the 3 model files to calculate the mean square error (MSE), you have to go to 3 files to correct the mistake.</li></ul><pre>difference = actual - predicted<br>mse = difference.mean()</pre><p>In constrast, if you save the mean square error (MSE) function in a Python module, you only need to change the function once.</p><p>To do this, you can create a module named metrics.py that contains the MSE function. This way, you can simply import the MSE function from your metrics module whenever you need to evaluate a regression model. Here is how you could define the MSE function within the metrics.py module:</p><pre>def mean_square_error(actual, predicted):<br>    &quot;&quot;&quot;<br>    Calculate the mean square error between actual and predicted values.<br>    <br>    Parameters:<br>    actual (list or numpy array): The actual values.<br>    predicted (list or numpy array): The predicted values.<br>    <br>    Returns:<br>    float: The mean square error.<br>    &quot;&quot;&quot;<br>    difference = actual - predicted<br>    squared_difference = difference ** 2<br>    mse = squared_difference.mean()<br>    return mse</pre><p>Then, in your script or any other module where you want to use the MSE function, you can import it and use it as follows:</p><pre>from metrics import mean_square_error<br><br># Example actual and predicted values<br>actual = [3, 5, 2.5, 6]<br>predicted = [2.5, 5.0, 2.0, 8]<br><br># Calculate MSE<br>mse = mean_square_error(actual, predicted)<br>print(f&quot;Mean Square Error: {mse}&quot;)</pre><p><strong>(Optional) What if you have different packages providing the same function.</strong> Python allows the same function names to be used in different modules without conflict. For instance, the mean_square_error function you&#39;ve defined in your metrics.py module can coexist with the mean_squared_error function available in the popular machine learning library, Scikit-learn (sklearn.metrics). Thanks to Python&#39;s namespace management, when you import these functions into your scripts, you can distinguish between them by prefixing them with the module name. For example, you could use your custom mean_square_error for certain tasks and sklearn.metrics.mean_squared_error for others, without any naming conflict. This is achieved by importing them like so:</p><pre>from metrics import mean_square_error as mse_custom<br>from sklearn.metrics import mean_squared_error as mse_sklearn<br><br># Example usage of your custom MSE<br>actual = [3, 5, 2.5, 6]<br>predicted = [2.5, 5.0, 2.0, 8]<br>mse_custom_result = mse_custom(actual, predicted)<br>print(f&quot;Custom MSE: {mse_custom_result}&quot;)<br><br># Example usage of Scikit-learn&#39;s MSE<br>mse_sklearn_result = mse_sklearn(actual, predicted)<br>print(f&quot;Scikit-learn MSE: {mse_sklearn_result}&quot;)</pre><h3>Section 3: Python Package</h3><p>Package structures Python modules. Normally, the presence of __init__.py files in each directory of a Python package is what distinguishes a package from a mere folder or directory.</p><blockquote><strong>Note: Before Python 3.3, </strong><strong>__init__.py file is used for Python interpretor to recognize directories as packages, </strong>allowing its modules to be imported. Now, it is not necessary.</blockquote><h4>A Practical Example</h4><p>Here is a practical machine learning package I devised called ml. Within this package, we have two subpackages: models and evaluation</p><pre>ml/<br>  models/<br>    __init__.py<br>    fully_connected_layer.py<br>    regression.py<br>python_script.py</pre><p>Here is the content of the module fully_connected_layer.py .</p><pre>class FullyConnectedLayer:<br>    &quot;&quot;&quot;Fully connected layer class for neural network model&quot;&quot;&quot;<br>    def __init__(self, learning_rate=0.01):<br>        self.learning_rate = learning_rate<br>        self.weights = None<br>        self.bias = None<br>        self.input_shape = None<br>        self.output_shape = None<br><br>    def forward(self, inputs):<br>        &quot;&quot;&quot;Forward pass of the fully connected layer&quot;&quot;&quot;<br>        return inputs @ self.weights + self.bias</pre><p><strong>Assess Python Definitions in A Modules</strong>:</p><ul><li>we use “dotted module names” to access Python’s module namespace by chaining the package and subpackages/modules (from package.module import item where item can be a function, a class, a variable or subpackage), e.g., from ml.models.fully_connected_layer import FullyConnectedLayer as below.</li></ul><pre># code in the python_script.py<br>from ml.models.fully_connected_layer import FullyConnectedLayer<br><br>model = FullyConnectedLayer()</pre><ul><li>Or we can use the pattern like from package import module and then use module to access the classes, functions and variables.</li></ul><pre># code in python_script.py<br>from ml.models import fully_connected_layer<br>model = fully_connected_layer.FullyConnectedLayer()</pre><ul><li>Modifying __init__.py Files for Direct Access: To directly access FullyConnectedLayer class from the models subpackage, modify the __init__.py files as follows:<br>ml/models/__init__.py:</li></ul><pre>from .models.fully_connected_layer import FullyConnectedLayer</pre><p>Now, users of your ml package can import the LinearRegression class and the mean_squared_error function directly from the package, without having to navigate through the subpackage structure:</p><pre># code in pytho_script.py<br>from ml import FullyConnectedLayer</pre><h3>Section 4: Using Public Packages</h3><p>To leverage the vast ecosystem of Python for data science and machine learning projects, you’ll likely need to install several key public packages. These packages provide a wide range of functionalities, from matrix manipulation to advanced machine learning algorithms and data visualization.</p><pre>pip install numpy         # Numpy for matrix manipulation<br>pip install scipy         # SciPy for statistic optimization and functions<br>pip install pandas        # pandas for reading data (Dealing with data as Numpy matrix)<br>pip install scikit-learn  # Sklearn for API call of ML algorithms<br>pip install matplotlib    # Matplotlib for visualization</pre><p>Instead of executing each pip install command separately, you can streamline the process by specifying all required packages in a single file named requirements.txt. This file lists each package (and optionally, the desired version) on a separate line. To install all the packages listed in requirements.txt, run the following command:</p><pre>pip install -r requirements.txt</pre><p>This approach not only saves time but also ensures consistency across different environments, making it easier to manage dependencies for projects.</p><h3>Section 5: Can We … ?</h3><h4>Can We Directly Run A Module?</h4><p>If we directly run the code in regression.py , an import error occurs: ImportError: attempted relative import with no known parent package . Because regression.py is used as a Python script, while the relative import via dots should be used between modules within a package.</p><pre># code in ml/models/regression.py<br>import numpy as np<br>from ..metrics import mean_squared_error, r2_score, variance_in_cv_scores</pre><pre>def ols_estimate_for_linear_regression(X, Y):</pre><pre>    # Mean of X and Y<br>    X_mean = np.mean(X)<br>    Y_mean = np.mean(Y)</pre><pre>    # Calculate beta_1 (slope)<br>    beta_1 = np.sum((X - X_mean) * (Y - Y_mean)) / np.sum((X - X_mean) ** 2)</pre><pre>    # Calculate beta_0 (intercept)<br>    beta_0 = Y_mean - beta_1 * X_mean</pre><pre>    return beta_0, beta_1</pre><pre>if __file__ == &quot;__main__&quot;:<br>    import pandas as pd<br>    df = pd.read_csv(&quot;data/house-prices/train.csv&quot;) # from <a href="https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/data">https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/data</a><br>    x = df[&#39;GrLivArea&#39;] # Above grade (ground) living area square feet<br>    y = df[&#39;SalePrice&#39;]<br>    beta_0, beta_1 = ols_estimate_for_linear_regression(x, y)<br>    predictions = beta_0 + beta_1 * x<br>    error  = mean_squared_error(y, predictions)</pre><p>To run this successfully, we have to tell Python interpreter that it works as a Python module within the ml library. You can use python -m command, e.g., python -m my_ml_package.models.regression .</p><h4>Can We Run A Notebook inside A Python Package?</h4><p>Yes. But you have to manually add the parent directory of the package into sys.path so that the Python import system can find the package.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=232d5f749e64" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/python-scripts-modules-andpackages-232d5f749e64">Python: Scripts, Modules andPackages</a> was originally published in <a href="https://levelup.gitconnected.com">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Simple to Complex: A Complete Overview of Reinforcement Learning]]></title>
            <link>https://medium.com/artificial-corner/from-simple-to-complex-a-complete-overview-of-reinforcement-learning-599a8c1ea689?source=rss-23bba04f5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/599a8c1ea689</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Xinzhe Li, PhD in Language Intelligence]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 05:24:54 GMT</pubDate>
            <atom:updated>2024-11-07T06:11:40.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Comprehensive Overview of Reinforcement Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*0SfhFBmBhbGSteKA" /><figcaption>Photo by <a href="https://unsplash.com/@alexandermils">Alexander Mils</a> on <a href="https://unsplash.com/photos/a-white-cube-with-a-yellow-and-blue-logo-on-it-ZIPFteu-R8k?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>This article aims to comprehensively demonstrate RL-related content.</p><p><strong>Working In Progress</strong></p><h3>Section 1: Unraveling the Complexity of Reinforcement Learning</h3><p>The exploration of Reinforcement Learning (RL) within the machine learning spectrum reveals a sophisticated landscape where traditional learning paradigms undergo a significant transformation.</p><p>This complexity is further nuanced by the shift from static data representations to dynamic states and actions, where the objective is not merely to predict the correct outcomes but to maximize <strong>rewards</strong> through <strong>sequential</strong> decision-making.</p><h4>Section 1.1: Reviewing Machine Learning</h4><p>In the realm of machine learning, various paradigms are utilized to teach machines how to interpret data and make predictions or decisions. At the core of these paradigms, symbols x and y are often used to delineate the process: x represents the input , while y symbolizes the ground-truth output we desire our models to generate. The objective is to maximize the probability of outputting the ground-truth given the input, i.e., p(y|x)</p><p><strong>Supervised learning </strong>is a paradigm that directly targets the optimization of p(y|x) by leveraging datasets where both x (input features) and y (target outcomes) are provided. The goal is to explicitly learn the mapping from x to y, thereby enabling the model to make predictions or decisions when presented with new, unseen instances of x.</p><p><strong>Unsupervised learning</strong> comes into play when y is not provided. This paradigm focuses on discerning patterns, structures, or insights from data where the outcome, or y, is unknown. The learning process revolves around the analysis of x alone, without direct guidance on what the output should be.</p><h4>Section 1.2: RL vs Supervised Learning</h4><p>An RL model aims to</p><blockquote>learn how to map situations (states) to actions — so as to maximize a numerical reward signal.</blockquote><blockquote>— from the Sutton&amp;Barto’s book (the Bible book in the field of RL),</blockquote><p>To achieve the goal, we need to learn one or some of the things below:</p><ul><li>A model mapping a given state s to an action a, denotated as policy <em>π</em>(<em>s</em>)</li><li>A model telling what’s the next state after executing a on s. Since. the transitions between s and s’ is not deterministic, this is actually a density estimation problem, where the transition function T(s’|s, a ) outputs a probability distribution over the state space. s’ is the next state after executing a on s.</li><li>A model evaluating whether the action a on s is good or bad, denoted as reward model R(s&#39;|s, a) . Actually, the output of policy can be either a distribution of <em>R(s, a)</em> over all the possible actions and a deterministic action sampled from the distributions</li></ul><p>In contrast, in typical supervised learning tasks, the task is simple (but universal): modeling the probability distribution p(y|x) so that we directly choose y based on p(y|x). Now, we do not have simple but general x, y mapping, although the state s is always input over all the three models above, while s’ is always the output in R and T.</p><p>This universal form can be used to model policy, reward function and transition function.</p><h4>Section 1.3: Fundamental Difference: Dynamic Learning</h4><p>Firstly, “dynamic” comes from the requirement of making sequences of decisions. RL models take the job to generate a sequence of decisions. During this process, rather than static mapping from a input to one or more ground-truth labels, both inputs and outputs are dynamically changed.</p><ul><li><strong>Dynamically changed states </strong>and actions: The original input is the perceived state from the environment. Obviously, for one example/trajectory, a sequence of different inputs could be injected into the model. Correspondingly, outputs can be different.</li></ul><p><strong>Secondly, dynamic comes from the unknown reward models for learning purpose. </strong>Ideally, the agent knows the reward models and transition models. Hence, they only need to adjust their actions (Policy output) conditioned on a state (Policy input) based on the weighted feedback/reward they receive. <br>However, reward models are often unknown. Hence, agents have to learn reward models through a sequence of trials and errors (or experience) by interacting with an environment. This leads to:</p><ul><li><strong>Dynamically changed objective function: </strong>Through the learning process, it is dynamically determined.</li><li><strong>Dynamically changed policy and optimal actions</strong>: The policy and the best action for a same input can be dynamically changed through the learning process.</li></ul><h4>Section 1.4: Fundamental Difference: Independent vs Dependent</h4><p><strong>Independent Assumption in Unsupervised/Supervised Learning Algorithms: </strong>This assumption exists in most of Supervised learning and unsupervised learning. In supervised learning, the independent assumption is crucial for the training process. It posits that each example in the dataset is independent of the others, meaning that the occurrence of one example does not influence the occurrence of another. <strong>This assumption simplifies the model training by allowing the algorithm to treat each example as an isolated instance</strong>, which is essential for the effectiveness of statistical inference and the reliability of predictive performance. However, this assumption can sometimes be violated in real-world scenarios where data points may be related, leading to challenges in model accuracy and generalization. For example, if the model assumes that each day’s stock price is independent of the previous day’s, it overlooks the critical temporal dependencies that often drive financial markets.</p><blockquote><strong>“Identically distributed”</strong> is another important assumption in common unsupervised/supervised Learning algorithms to ensure the training and future unseen data come from the same distribution, facilitating the model’s ability to generalize well from the training set to the test set or real-world scenarios. For example, the model might associate the word “avenger” with positive sentiments due to its positive connotation in the context of movie reviews, particularly for the “Avengers” movie series which is widely appreciated. When applied to a product review that uses “avenger” in a completely different context, e.g., “Total disappointment. This product turned me into an avenger, hunting for a refund. Save your money!”, the model may incorrectly predict the sentiment as positive due to its reliance on the learned association.</blockquote><p><strong>Dependent in Sequential Decision Making in RL: </strong>In the realm of Reinforcement Learning (RL), the scenario is markedly different due to the sequential and dependent nature of decisions, as opposed to the independent examples typically found in Supervised and Unsupervised Learning. The concept of dependency is pivotal, where the outcome of a previous action (a) directly influences the subsequent state or observation (s) encountered by the agent. <strong>The 1st challenge it leads to is exploration and exploitation.</strong> This intertwined relationship necessitates a nuanced approach in RL, known as the balance between exploration and exploitation. Exploration involves trying new actions (a) to gauge their outcomes, essential for uncovering potentially superior strategies. On the other hand, exploitation leverages the best-known actions to maximize immediate rewards. The art of RL lies in effectively managing this balance, as it directly impacts the learning efficiency and the ability of the agent to adapt to dynamic environments, thereby achieving optimal decision-making over time. <strong>The 2nd challenge it leads to is iterative calculations of objective.</strong> The Objective in Supervised Learning is easy: p(y|x). However, this dependency in Reinforcement Learning (RL) naturally leads to an iterative process for calculating the objective, which is typically defined as the sum of future rewards. To make it solvable, the concept of value is devised: a value under a policy <em>Vπ</em>(<em>s</em>) is the expected return (cumulative discounted reward) from state s .</p><blockquote>Thinking: Why do I use the term “expected return” rather than “expected reward”? The “return” in RL contexts refers to the sum of all rewards an agent receives, often discounted by a factor at each time step to account for the uncertainty or diminishing value of future rewards. This includes not just the immediate reward for the next action, but all subsequent rewards the agent will collect. The concept of return encompasses the entire sequence of rewards that follow a state or a state-action pair, reflecting the long-term consequences of actions.</blockquote><p>Specifically, following a policy at the state s yields a random path. The utility (or return) of a policy is the (discounted) sum of the rewards on the path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*KBBGMfzmCaSWZIOqhat9Xg.png" /></figure><p>The return from the timestep t is a random quantity. The random variable cannot be an objective for optimizing the policy. Hence, we need the expectation over the path coming from the current state sand ending at a terminal state or reaches a finite time horizon.</p><h4><strong>(Optional) Section 1.5: An Example Using All The Three Learning Paradigms — — ChatGPT-like LLMs</strong></h4><p>Since I always boast myself as a language intelligent researcher, let’s show off my expertize. All of you know ChatGPT, a Large Language Model. However, maybe you do not know is that ChatGPT is trained by including all the three learning paradigms:</p><ul><li>Unsupervised Learning: Self-supervised learning (SSL), a particular type of unsupervised learning, is used to <strong>let language models learn huge amounts of world knowledge</strong>. For detail, <a href="https://www.jmlr.org/papers/volume3/bengio03a/bengio03a.pdf">here</a> is a very early but typical paper by Yoshua Bengio. For a more intuitive one, I will release my own work later to demonstrate this)</li><li>Supervised Learning: It is used to tune the naive ChatGPT to behave like a human. In the leftmost part, you can see, in this stage, the ChatGPT model is called policy (A good time for you to refresh the terminology).</li><li>Reinforcement Learning: The middle section talks about training a reward model (Again, a good time for you to refresh the terminology) for optimizing the less naive ChatGPT.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3W21oTT7cii85elXeSLE5Q.png" /></figure><h3>Section 3: Modeling Dynamic World</h3><p>The model underlying RL is a decision process where an action y on a state x at the time t results in an indeterministic state x at the time t+1. i.e., the environment is dynamic . Here is a simple running example.</p><p>For each round r=1,2, …<br>- You choose stay or quit.<br>- If quit, you get $ 10 and we end the game.<br>- If stay, you get $ 4 and then I roll a 6 -sided dice.<br>- If the dice results in 1 or 2 , we end the game.<br>- Otherwise, continue to the next round.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_uuwFqjRKCLRxCB8QtMfCg.png" /></figure><p>The reason why we want to model this as a MDP problem is because the indeterministic resulting states when the action “state” is performed on the “in”, which is represented by the chance node (in, stay).</p><ul><li>Action: In the toy example, the action space A = {<em>stay, quit}.</em></li><li>States: In the toy example, the state space S = {<strong>in, end}.</strong></li><li>Transition models: Commonly, the transition models can be represented by the distribution of possible states and their rewards Pr(S, R|s, <em>π</em>) for each state and each action.<br>For the current state “<strong>in</strong>”: (the total number of transitions = the number of actions * the number of states)<br> For the action “<em>stay</em>”, p(<strong>end</strong>|<strong>in</strong>, <em>stay</em>)=1/3, p(<strong>in</strong>|<strong>in</strong>, <em>stay</em>)=2/3; <br> For the action “<em>quit</em>”, p(<strong>end</strong>|<strong>in</strong>, <em>quit</em>)=1, p(<strong>in</strong>|<strong>in</strong>, <em>quit</em>)=0.<br>If we use each state as the current state, the total number of transitions = the number of actions |A|* the number of states |S|²</li><li>Rewards: r(in, stay-&gt;end) = $4; r(in, stay-&gt;in) = $4</li></ul><h3>Section 4: Objective and Policy Evaluation</h3><p>As defined previously, “Policy” is a mapping from states of the environment to actions to be taken. Formally, it is a state-dependent distribution over the action space <em>π(a|s). </em>The number of policies = |A| to the power of |S|, which is combinatorially large. If there are 11 states and 4 actions, it equals to ⁴¹¹.</p><h4>Objective: Maximizing Utilities of Following A Policy π</h4><p>The Objective in Supervised Learning is easy: p(y|x) . The objective for RL is the cumulative reward of following a policy. Specifically, following a policy yields a random path. The utility (or return) of a policy is the (discounted) sum of the rewards on the path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*KBBGMfzmCaSWZIOqhat9Xg.png" /></figure><p>The return from the timestep t G_t is a random quantity. The random variable cannot be an objective for optimizing the policy. Hence, we need the expectation.<br>Note that the path comes from the current state s and ends at a terminal state or reaches a finite time horizon. Below show four paths and their utilities for the toy example.</p><blockquote>Terminology: “Horizon” refers to the number of future steps or decisions a model considers when calculating values like rewards.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*oMQgsjOpZFC1S47Y1P_CjQ.png" /></figure><p>However, these utilities can give us an intuitive sense of how the policy performs if we can simulate tons of them and average them, which is the idea of the Monte Carlo method. The method calculates the expected utility by sampling set of trajectories and average their returns.</p><h4>Objective: Maximizing Value of Following A Policy π</h4><p>The value referes to the expected utility (or return) received by following policy <em>π</em>.</p><p><strong>Why do I use the term “expected return” rather than “expected reward”?</strong>Here is the difference between utility (or return) and reward: The “return” in RL contexts refers to the sum of all rewards an agent receives, often discounted by a factor at each time step to account for the uncertainty or diminishing value of future rewards. This includes not just the immediate reward for the next action, but all subsequent rewards the agent will collect. The concept of return encompasses the entire sequence of rewards that follow a state or a state-action pair, reflecting the long-term consequences of actions.</p><p><strong>Each value is related to a particular state (so-called state-value function)</strong> Now, what we miss is the state. We can only follow a policy from a given state. Let’s rephrase again in a specific way by considering the state: the expected return from each individual state while adhering to the policy. Why do I emphasize this?<strong> </strong>Well, because I want to emphasize that policy evaluation involves computing the value for each state under the current policy but <strong>is not to sum the values of all states</strong>.</p><ul><li>The key point is that when evaluating a policy, you don’t add up these individual state values into one aggregate sum. Each state’s value is kept distinct because it serves a specific purpose in the context of policy evaluation and improvement.</li><li>For example, in algorithms like Policy Iteration or Value Iteration, these individual state values are used to inform decisions about which actions to take in each state (policy improvement) and to check for convergence to an optimal policy</li><li>The calculation of <em>Vπ</em>(<em>s</em>) for the particular state s take into account the other states that may occur in the future under policy <em>π</em>. This expected return is not just about the immediate rewards but also includes all the future rewards the agent can expect to receive, appropriately discounted.</li></ul><h4>Objective: Defining Value Function for Maximization</h4><p>Formally, the <strong>value function <em>Vπ</em>(<em>s</em>)</strong> is defined to map from a state s to the expected return. Intuitively, It answers the question: <strong>what is the expected return by starting in state <em>s</em> and following policy <em>π?</em></strong></p><h3>Section 5: Using Model-based Approaches with Reward Model and Transition Model</h3><p>Due to the probabilistic nature of state transitions, it is calculated by aggregating (technically we use the weighted sum) rewards (it can be discounted rewards) for all the one-timestep future states and corresponding rewards by taking an action according to the policy. Note that the rewards may be aggregated with discounts, e.g., more discounts for further future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmCaOpAtP6Mb0Ka4Eg7B3w.png" /></figure><p>The latter part of the expression is a recursive decomposition for the value function of a policy in a MDP, which is known as the Bellman equation.</p><blockquote>IMPORTANT: The Bellman equation is a fundamental concept in dynamic programming and reinforcement learning.</blockquote><blockquote>This recursive relationship provides a powerful tool for solving MDPs, especially when combined with algorithms like value iteration and policy iteration.</blockquote><blockquote><em>Generally, the Bellman equation is </em>the backbone of algorithms like Q-learning, Value Iteration, and Policy Iteration</blockquote><blockquote>Below is a less common recursive form, which simplifies the immediate reward as a direct consequence of being in state <em>s.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*S9Bza5Af83EMw5xO7SpyKA.png" /></figure><blockquote>Stochastic policy: We need two levels of expectation for stochastic policy where <em>π</em>(<em>a</em>′∣<em>s</em>′) gives the probability of taking action <em>a</em>′ when in state <em>s.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Stn31tvsCySWaQPQFHHMxA.png" /></figure><p>The sections below will give a more detailed introduction of the model-based method — Dynamic Programming and other model-free methods based on sampling experience.</p><h4>Why Does The Expressions Make Sense? Why is V(s) always stationary?</h4><p><strong>Markov Means “Memoryless</strong>”: The formulas and algorithms described here are often (not always) used for Markov Decision Process (MDP). It is “Markovian” because we assume that</p><ol><li>State: The next state is probabilistically determined by only the current state and action.</li><li>Value: No matter how we got to the current state, the value of the state is identical;</li><li><em>Action: the optimal decision at any point depends only on the current state and not on the path taken to reach that state </em>( how the state was reached); 4) Hence, we know the independence of future optimal decisions (actions) from past decisions (actions).</li></ol><p>In summary, the sequential decision-making process is thus simplified to a series of independent decisions, each based solely on the current state. This is why the above regressive forms make sense, and algorithms like Value Iteration and Policy Iteration can systematically improve policies by considering the optimality of actions at each state independently of the actions that led to that state.</p><blockquote>An optimal policy has the property that whatever the initial state and initial decision are, the remaining decisions must constitute an optimal policy with regard to the state resulting from the first decision. (See Bellman, 1957, Chap. III.3.)</blockquote><blockquote>Further Thought: How about it’s not stationary?</blockquote><h3>Section 6: Model-based Approach: Dynamic Programming</h3><p>Dynamic programming is used for policy evaluation via Bootstrapping and Recursion.</p><p>Policy Iteration and Value Iteration in the context of Dynamic Programming (DP) are indeed two parallel and distinct methods for finding the optimal policy in Markov Decision Processes (MDPs).</p><ul><li>In DP, the solution to a larger problem (finding <em>V</em>(<em>s</em>) for all <em>s</em>) is built upon the solutions to smaller problems (finding <em>Vk</em>−1​(<em>s</em>′) for all ′<em>s</em>′). This decomposition into subproblems is made possible by the <strong>model’s structure</strong> (the transition probabilities and rewards) and the <strong>recursive nature of the Bellman equations</strong>.</li><li>Model’s structure: In DP for MDPs, the model of the environment (specifically, the transition probabilities and reward structure) is known. This model tells us the probability of transitioning to various future states given the current state and action, as well as the rewards associated with these transitions.</li></ul><h4>Policy Iteration</h4><blockquote>Note: while value-based methods derive policies from value functions, policy-based methods optimize the policy directly, and actor-critic methods use a hybrid approach.</blockquote><ul><li><strong>Under the assumption of an infinite horizon</strong><br>1. <strong>Stationary policy</strong>, i.e., the policy does not change over time: In policy iteration, a policy is evaluated and improved iteratively. During the evaluation phase, the policy is considered stationary. That is, it’s assumed that the policy does not change while its value function is being calculated. Just note that the Bellman equation is typically formulated under a stationary policy <em>π.</em>(I am not sure whether it can be applied for non-stationary policies.)<br>2. <strong>Convergence of Value Function</strong>, i.e., V(s) becomes constant over time: When the value function under this stationary policy is computed (policy evaluation) over an infinite horizon, this value function converges to a constant as long as the policy remains unchanged. Specifically, the value function becomes stable and stops changing after sufficient iterations. Once the value function stabilizes, the policy is then improved based on the current value function, and the process repeats.</li></ul><p>Policy Iteration involves two iterative steps: policy evaluation and policy improvement, iterated until convergence.<br>1. <strong>Policy Evaluation:</strong></p><blockquote>Thought: Why iterative update of value function will finally converge?</blockquote><p>In this step, the value function for a given policy is calculated until it stabilizes. This involves solving a system of linear equations to find the expected returns from all states under the current policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*FTYeY_1SlH5Jmv_C3frOJg.png" /></figure><blockquote><strong>The subscripts k and (k-1)</strong>: Using just V(s) and <em>V</em>(<em>s</em>′) without specifying the iteration might imply that we’re referring to a static value function or the final, converged value function. By using the subscripts , we explicitly acknowledge that we’re working with the value function as it was estimated in certain iterations, not some static or final value function. For example, (k-1) is the previous iteration of k.</blockquote><p><strong>Bootstrapping </strong>referring to use the bootstrapping term below as a substitute for actually doing all the roll-out of future steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*qbSUHKSWQt9mTxuLvxE0kw.png" /></figure><p>Specifically, the essence of DP is to <strong>estimate the expectation over all the possible future</strong> by using a one-timestep values exactly. In other words, what would it be like if I start from each possible state of one-time step future, as denoted below? This is called</p><ul><li>We now have the estimate of values for all the possible states. However, our goal is to estimate the expectation over all the possible future. So we must know the distribution (probabilities)of reaching potential future states given the current state and action, as denoted below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*n4ejQhL-e2Q_oM4-MtAruw.png" /></figure><ul><li>Now would be the best time to explain the word “Dynamic”. It actually refers to the dynamics of the environment given by the probability function above and the reward model that returns the immediate reward.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*0YWukk3DE5kLn4Oq0YFHdQ.png" /></figure><blockquote>Note that the dynamic model (i.e., the probability distribution) and reward model above are the components of the Markov Decision Process Model.</blockquote><p><strong>2. Policy Improvement:</strong> Once the value function is stable, the policy is greedily updated for each state s with respect to its value function V(s) under the policy improvement theorem. This means for the state s, the policy chooses the action on s that leads to the highest expected return from the next state according to the current value function.</p><p><strong>3. Convergence to Optimal Policy:</strong> This process of evaluation and improvement is repeated until the policy no longer changes, at which point it is considered optimal.</p><h4>Value Iteration</h4><ul><li><strong>Single Step Process:</strong> Value Iteration simplifies the process by combining policy evaluation and improvement into a single step.</li><li><strong>Value Function Update:</strong> Instead of fully evaluating a policy, Value Iteration continuously updates the value function for each state. It does this by choosing the action at each state that maximizes the expected return, based on the current estimate of the value function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eg3YoFT5AcGxQb6MG3RAvQ.png" /></figure><ul><li><strong>Implicit Policy Improvement:</strong> The policy is implicitly improved in each iteration as the value function gets updated. The optimal policy can be easily derived from the converged value function by choosing the best action at each state.</li><li><strong>Faster Convergence:</strong> Value Iteration often converges faster than Policy Iteration because it doesn’t require the value function to stabilize under a particular policy before improving it.</li></ul><h4>Simpler Methods</h4><p>When the state and action spaces are small and the transition probabilities and reward structures are relatively simple, it might not be necessary to use complex algorithms like Value Iteration or Policy Iteration. In such cases, simpler methods might suffice.</p><p>Imagine a simple MDP with three states (S1, S2, S3) and two actions (A1, A2), where actions lead to different states with certain probabilities:</p><p><strong>Transitions and Rewards:</strong></p><ul><li>From S1, taking A1 leads to S2 with a probability of 0.7 and to S3 with a probability of 0.3. The reward is +1 in either case.</li><li>From S2, taking any action leads back to S1 with a reward of 0.</li><li>From S3, taking any action leads back to S1 with a reward of -1.</li></ul><p><strong>Policy:</strong></p><p>Consider a policy where:</p><ul><li>In S1, the policy chooses A1.</li><li>In S2 and S3, the action choice doesn’t matter (as all actions lead to the same outcome).</li></ul><p><strong>Objective:</strong></p><ul><li>To evaluate this policy, we calculate the expected return from each state under the policy.</li></ul><p><strong>Setting Up the Equations:</strong></p><ul><li>Assuming a discount factor ( = 0.9 ), the Bellman equations for our policy become:</li><li>For S1 under A1: ( V(S1) = 1 + 0.9 [0.7 V(S2) + 0.3 V(S3)] )</li><li>For S2: ( V(S2) = 0 + 0.9 V(S1) )</li><li>For S3: ( V(S3) = -1 + 0.9 V(S1) )</li></ul><p><strong>Solving the System:</strong></p><ul><li>This system of linear equations needs to be solved to find the values of V(S1) , V(S2) , and V(S3) .</li><li>This can be done using matrix algebra methods or iterative techniques like Gauss-Seidel iteration.</li></ul><h3>Section 7: Roll-out</h3><p>In a rollout algorithm, one simulates or “rolls out” an episode from a given state until a terminal state or a predefined horizon is reached according to a policy. This approach is used to estimate the value function or the quality of an action at a state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*08xJtHO07HAjNv338Xx64A.png" /></figure><p>It can be considered as a form of Monte Carlo simulation, as it relies on averaging over multiple random samples of trajectories (or episodes).</p><h3>Section 8: Model-free Approach: Monte-Carlo Methods — Learning from Experience</h3><blockquote>If we do not know the dynamic models and reward models, we will use other methods like Monte-carlo and Temporal Difference methods.</blockquote><h4>Policy Evaluation (Converged Value Function)</h4><p>The method calculates values (estimates the value function) by sampling set of trajectories(episodes) and average their returns.</p><p>It only suits for episodic MDP (e.g., we cannot use it for optimizing robots) but the good thing may be that it does not have markov assumption of states.</p><ul><li>It suits episodic tasks where episodes are guaranteed to terminate after a finite number of steps, allowing the calculation of the return for each state visited in the episode. Specifically, we. sample actions from <em>π</em> ,which leads to the sample episode: s_1, a_1, r_1, s_2, a_2, r_2, …, s_T</li><li>On-policy: Monte Carlo policy iteration, where a policy is evaluated using the returns generated by episodes produced under the same policy, and then the policy is improved based on the evaluation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2S2P5JXKVnNRBp2ViunlNw.png" /></figure><ul><li>Off-policy: Off-policy Monte Carlo methods evaluate or improve a policy different from the one generating the data. An example of this would be using importance sampling to re-weight the returns generated under a different policy (behavior policy) to evaluate or improve a target policy.</li></ul><h3>Section 9: Model-free Approach: Temporal Difference</h3><p>Now, I can easily understand the following expression, where we simply estimate the future reward G_t using the bootstrapping term in DP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IkfSoeXEfdg9sGXfogFCg.png" /></figure><p>Compared to the Monte-Carlo method, it has the following advantages:</p><ol><li>Faster Learning: TD methods update the value estimate after each step rather than waiting for the end of an episode as in Monte Carlo methods. This means that TD learning can learn from incomplete sequences and update its estimates partway through an episode. This leads to potentially faster learning since the algorithm doesn’t have to wait for the episode to finish before making value updates.</li><li>Handling of Continuous Tasks: Monte Carlo methods are primarily suited for episodic tasks where the episodes terminate. In contrast, TD methods can handle both episodic and continuous (non-terminating) tasks efficiently. This is because TD methods do not require the final outcome of an episode to update the value estimates.</li><li>Reduced Variance: The updates in TD learning are based on the difference between estimated values of successive states (TD error), which often leads to lower variance in the updates compared to Monte Carlo methods. Monte Carlo updates are based on full returns, which can have high variance especially in stochastic environments.</li></ol><p>~~~~ Uncompleted Article (TBC) ~~~~</p><p>~~~~ Welcome to correct me if I made any mistake here ~~~~~</p><p>How to solve optimize a policy model to maximize this objective?</p><p>1. Getting <strong>**a reward model**</strong> to calculate the reward?</p><p>2. Getting a value function? (or a action value function)?</p><p>3. Getting a dynamics model, i.e., the distribution of $x_{t+1}$ and action $a$ of the state $x_t$ will be transited to ($Pr(x_{t+1}, r|x_t, y’)$)?</p><h3>Summary</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=599a8c1ea689" width="1" height="1" alt=""><hr><p><a href="https://medium.com/artificial-corner/from-simple-to-complex-a-complete-overview-of-reinforcement-learning-599a8c1ea689">From Simple to Complex: A Complete Overview of Reinforcement Learning</a> was originally published in <a href="https://medium.com/artificial-corner">Artificial Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>