<?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 Josh Johnson on Medium]]></title>
        <description><![CDATA[Stories by Josh Johnson on Medium]]></description>
        <link>https://medium.com/@caellwyn?source=rss-6fad8f551b22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3InsU5z6mtSXWco15fCXnQ.jpeg</url>
            <title>Stories by Josh Johnson on Medium</title>
            <link>https://medium.com/@caellwyn?source=rss-6fad8f551b22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:43:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@caellwyn/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[Decoherence as a Gradient: Exploring Partial Overlap Between Universes]]></title>
            <link>https://caellwyn.medium.com/decoherence-as-a-gradient-exploring-partial-overlap-between-universes-c583895ee4a1?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/c583895ee4a1</guid>
            <category><![CDATA[theoretical-physics]]></category>
            <category><![CDATA[quantum-theory]]></category>
            <category><![CDATA[quantum-mechanics]]></category>
            <category><![CDATA[multiple-universe]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 22:16:30 GMT</pubDate>
            <atom:updated>2024-12-20T22:16:30.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kv8uh92XC0rBCkVo" /><figcaption>Universes in Hilbert Space</figcaption></figure><h3><strong>Abstract:</strong></h3><p>This document explores a novel perspective on quantum decoherence and its implications for the many-worlds interpretation of quantum mechanics. Instead of treating decoherence as a binary separation of universes, we propose that it is better understood as a continuum, where universes can partially overlap and interact dynamically. This perspective could provide alternative explanations for quantum effects such as tunneling, entanglement, and uncertainty, framing them as the result of subtle interactions between neighboring, “compatible” universes in Hilbert space. This framework suggests that decoherence involves degrees of separation and offers testable predictions for experimental physics.</p><h3>1. The Traditional View of Decoherence</h3><p>In the many-worlds interpretation of quantum mechanics, decoherence is traditionally understood as a process by which quantum systems interact with their environment, causing the wavefunction to branch into distinct, non-interacting worlds. Each world represents a unique outcome of quantum measurements, evolving independently in Hilbert space. The branches become orthogonal and lose the ability to interfere with one another, ensuring the appearance of classical reality in each world.</p><h3>2. The Proposed View: Decoherence as a Gradient</h3><p>Rather than treating decoherence as a strict binary process, we propose that it is a <strong>continuum</strong>:</p><ul><li><strong>Partial Overlap</strong>: Decohered universes may retain partial overlap in Hilbert space, allowing for subtle interactions or “leakage” between them. This overlap depends on the similarity of the systems involved and their degrees of freedom.</li><li><strong>Dynamic Stretching and Fluxing</strong>: Decoherence may involve a dynamic process of “stretching” and “fluxing,” where the degree of separation between universes fluctuates over time or under specific conditions. Universes are not fully distinct but interconnected regions of a continuous multiverse.</li></ul><h3>3. Interactions Between Universes</h3><p>If universes retain partial overlap in Hilbert space, this could provide alternative explanations for certain quantum phenomena:</p><ul><li><strong>Quantum Tunneling</strong>: A particle crossing a classically forbidden barrier might result from temporary alignment or energy exchange between neighboring universes.</li><li><strong>Entanglement</strong>: Correlations between entangled particles could reflect shared states across partially overlapping universes.</li><li><strong>Uncertainty Principle</strong>: The probabilistic nature of quantum mechanics might arise from averaging or blending measurements across overlapping universes.</li><li><strong>Vacuum Fluctuations</strong>: Effects like the Casimir effect might stem from subtle interactions with neighboring universes’ vacuum states.</li></ul><h3>4. The Role of Hilbert Space Dimensionality</h3><p>Max Tegmark’s work on Hilbert space provides a foundation for understanding why universes decohere:</p><ul><li><strong>Orthogonality and Decoherence</strong>: Universes that diverge significantly in Hilbert space become orthogonal and cease to interact.</li><li><strong>Compatible Universes</strong>: Universes with similar dimensions in Hilbert space may remain partially overlapping, allowing for interactions. This framework suggests that decoherence is a matter of degree rather than a complete separation.</li></ul><h3>5. Observable Implications and Testable Predictions</h3><p>If partial interactions between universes occur, they might leave detectable signatures in experiments:</p><ul><li><strong>Deviations from Quantum Predictions</strong>: Small anomalies in tunneling rates, entanglement correlations, or vacuum energy measurements could signal inter-universe interactions.</li><li><strong>Quantum Noise</strong>: Additional noise or interference patterns in controlled quantum systems might arise from fluxing overlaps between universes.</li></ul><h3>6. Challenges and Open Questions</h3><p>This framework raises several questions:</p><ul><li><strong>Conservation Laws</strong>: How are energy and momentum conserved across interacting universes?</li><li><strong>Mathematical Framework</strong>: Can the standard formalism of quantum mechanics accommodate this dynamic view of decoherence, or does it require modifications?</li><li><strong>Experimental Feasibility</strong>: What types of experiments could detect partial overlap or interaction between universes?</li></ul><h3>7. Philosophical Implications</h3><p>This perspective challenges the traditional view of universes as fully distinct and separate. Instead, it paints a picture of a dynamically interconnected multiverse where boundaries between worlds are soft and fluid. Decoherence becomes a matter of perspective and scale, with universes existing as gradients of phase-space density within Hilbert space.</p><h3>Conclusion</h3><p>By reimagining decoherence as a gradient rather than a binary separation, we open the door to new ways of understanding quantum mechanics and the multiverse. This framework suggests that universes are interconnected through subtle overlaps in Hilbert space, potentially explaining difficult-to-describe quantum phenomena. Further exploration of this idea could yield testable predictions and deepen our understanding of the quantum world and its relation to the multiverse.</p><p><em>ChatGPT 4o assisted in the writing of this article</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c583895ee4a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Psychic Mirrors We Carry: Technology, Self-Reflection, and Digital Narcissism]]></title>
            <link>https://caellwyn.medium.com/the-psychic-mirrors-we-carry-technology-self-reflection-and-digital-narcissism-e67b3990cf3f?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/e67b3990cf3f</guid>
            <category><![CDATA[dreamtime]]></category>
            <category><![CDATA[narcissism]]></category>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[social-media]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 23:34:05 GMT</pubDate>
            <atom:updated>2024-11-05T23:34:05.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q5nN0cVRQsOV1yuo" /></figure><p>In Wim Wenders’ prescient 1991 film “Until the End of the World,” a group of characters become addicted to watching recordings of their own dreams, gradually withdrawing from reality into a recursive loop of their own mental imagery. While the technology depicted in the film remains fictional, we may already be living through a similar phenomenon — one where the black mirrors we carry in our pockets serve as portals into increasingly personalized reflections of our own psyche. The film’s vision of technology-enabled psychological isolation, once seemingly far-fetched, now reads as an eerily accurate prediction of our current digital landscape.</p><h3>The Modern Dream Machine</h3><p>Today’s smartphones and social media algorithms function remarkably like Wenders’ dream machines. Rather than showing us an objective window into the world, they present us with a carefully curated reflection of our own interests, beliefs, and desires. Each scroll, like, and share further refines this reflection, creating an ever more compelling — and addictive — version of reality tailored specifically to us. Our feeds become increasingly personalized, showing us content that confirms our existing worldview, appeals to our established interests, and reflects our previously expressed opinions. Like the dream machines, these devices offer us an intoxicating vision of reality filtered through the lens of our own consciousness.</p><h3>Digital Narcissus</h3><p>The parallel to the myth of Narcissus is striking. Just as the young man became entranced by his reflection in a pool of water, we find ourselves captivated by these digital reflections of our own consciousness. But there’s a crucial difference: while Narcissus eventually recognized his reflection for what it was, we often remain unaware that we’re primarily interacting with algorithmically generated mirrors of our own psyche. The pool that transfixed Narcissus showed him a true reflection; our digital pools show us an optimized version of ourselves and our world, one calculated to hold our attention ever longer. The tragedy of modern digital narcissism lies not just in our self-absorption, but in our failure to recognize the nature of the reflection that entrances us.</p><h3>The Self-Reinforcing Loop</h3><p>This creates a dangerous feedback loop. The more time we spend engaging with these personalized reflections, the more our worldview becomes self-reinforcing. Our digital experience increasingly confirms our existing beliefs and preferences, creating what appears to be external validation but is actually just an echo of our own thoughts bouncing back at us. Like participants in a grand psychological experiment, we find ourselves in chambers of digital mirrors, each reflection slightly more appealing than the last, each interaction drawing us deeper into a world that seems expansive but is actually a carefully constructed reflection of our own minds.</p><h3>The Path Forward</h3><p>These digital mirrors are not simply passive reflections but carefully crafted systems, designed to create compelling and addictive versions of our own psyche. Social media platforms have learned to shape these reflections to keep us engaged — a design choice that serves their business models while potentially deepening our isolation in personalized reality bubbles.</p><p>Understanding this dynamic is crucial. When we recognize that our digital reflections are being subtly optimized to hold our gaze, we can begin to engage with them more consciously. Like the dream-watching technology in Wenders’ film, these platforms offer genuine value and connection — but they can also lead us into recursive loops of self-reflection if we’re not mindful of their design.</p><p>The challenge, then, is learning to use these tools while maintaining awareness of their nature. We can appreciate their benefits and acknowledge their risks, neither demonizing the technology nor absolving it of its intentional design choices. Perhaps by understanding these psychic mirrors more clearly, we can learn to look both into them and beyond them, maintaining our connection to the wider world that exists outside our own reflection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e67b3990cf3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a ChatGPT Powered Web App to Chat With Historical Philosophers, Part 2: Deploying to…]]></title>
            <link>https://caellwyn.medium.com/create-a-chatgpt-powered-web-app-to-chat-with-historical-philosophers-1c1c7c90033b?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c1c7c90033b</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Sun, 25 Jun 2023 18:00:49 GMT</pubDate>
            <atom:updated>2023-06-25T18:05:40.096Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@caellwyn/create-a-chatgpt-powered-web-app-to-chat-with-historical-philosophers-d4d602bd10f0?source=your_stories_page-------------------------------------">Create a ChatGPT Powered Web App to Chat With Historical Philosophers</a>, Part 2: Deploying to Streamlit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXDUU-dXyl93cAlDfiXz2g.png" /></figure><h3>Recap</h3><p>Welcome to Part 2 of our series on deploying a ChatGPT-powered web application to a Streamlit site. If you haven’t yet gone through <a href="https://medium.com/@caellwyn/create-a-chatgpt-powered-web-app-to-chat-with-historical-philosophers-d4d602bd10f0">Part 1</a>, I recommend you do so here before proceeding.</p><p>In this segment, we’ll be focusing on utilizing the knowledge gained from the previous article to implement our application on a Streamlit website.</p><p>For part 1, see <a href="https://medium.com/@caellwyn/create-a-chatgpt-powered-web-app-to-chat-with-historical-philosophers-d4d602bd10f0">this link</a>.</p><h3>Streamlit</h3><p>Streamlit is an intuitive Python package that facilitates the creation of web applications capable of running directly in your browser. It’s particularly designed for data science applications, offering a seamless experience when deploying models or managing databases through APIs.</p><p>Whether it’s interacting with remote databases like Snowflake or Amazon Web Services, running inferences from local or cloud-deployed models, or creating API endpoints for models hosted on AWS servers, Streamlit provides a versatile platform. An added bonus is the Streamlit community cloud, which allows you to deploy your apps publicly, like the one pictured above. You can access it here!</p><p>To get started, you will need the following:</p><h3>Requirements:</h3><ol><li><strong>Streamlit community cloud account</strong>: This is where you can deploy your apps. Sign up for a free account, which allows you to deploy unlimited public apps and one private app accessible by invitation only.</li><li><strong>Python and the Streamlit Python Package</strong>: Install the Streamlit package from your Python terminal using the pip install streamlit command.</li><li><strong>GitHub Account</strong>: This isn’t necessary for creating an app to run on your local machine. However, if you wish to deploy to the Streamlit Community Cloud, a GitHub account is essential.</li><li><strong>Material from Part 1</strong>: Ensure you’ve read and understood <a href="https://medium.com/@caellwyn/create-a-chatgpt-powered-web-app-to-chat-with-historical-philosophers-d4d602bd10f0">Part 1</a>, as it contains the essential code needed to interact with the ChatGPT API.</li></ol><p>Now that we’re all set, let’s dive in and continue our journey to deploying a ChatGPT-powered web application on Streamlit!</p><h3>Getting Started</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*LXnUP4Ps-R1caL6O9Tc1Yg.png" /></figure><p>In Part 1 of this series, you crafted the aiagent.py file, a vital component for interacting with ChatGPT. Now, in Part 2, we&#39;re going to develop the code that instructs Streamlit on how to construct your app.</p><p>Once you’ve initialized a new Python file, you’re ready to start programming. The initial steps involve importing the Streamlit package and the AIAgent from the aiagent.py file, which should reside in the same directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*Ilf5bMejE2xmiBXYINFKUw.png" /></figure><h3>Session ID and Cached Resources</h3><p>Streamlit’s operation needs some clarification. When a live app runs on Streamlit, it executes the entire file whenever there’s a change. This constant refreshing can pose challenges, particularly when you’re initializing variables that are expected to change later. For instance, any alteration in user input or slider bar movement will reset every global scope variable.</p><p>There’s ongoing dialogue in the Streamlit community about the issue of session persistent variables. As of now, Streamlit hasn’t implemented a direct solution for this, which is primarily because it’s not designed for this kind of operation.</p><p>However, there’s a feature called st.session_state that you can use as a dictionary to store function-generated variables. But take note: these are not session-specific variables. They persist across all sessions and ALL USERS. For instance, if you save your chat history as st.session_state[&#39;history&#39;], every user visiting your site will be able to view it - a clear privacy concern. So, this method is NOT recommended.</p><p>Here’s the two-part solution we propose: leveraging cached resources and a session ID.</p><p>Cached Resources: Streamlit, being optimized for data science, discourages repeatedly recreating resources like inference models. Instead, it provides a function decorator, @cache_resource, that caches resources, avoiding their recreation. As long as the function inputs remain consistent, the site will use the cached version. However, these cached resources will also be shared, like items stored in st.session_state. This is convenient if the resources are stateless, but it can also lead to session bleed-through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*ZZX29maV4etSwCV-6JMLHA.png" /></figure><p>Cached resources will also be shared, like items stored in st.session_state. This is handy as long as those resources are stateless. But, otherwise you get the same bleed through to other user sessions.</p><p>Session ID: It’s possible to fetch a unique session ID that changes with each new tab opened running a Streamlit app. The code provided below will retrieve that ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*dU-i-mdABlMElVnwMEAlhg.png" /></figure><p>Combining Them: Remember, cached resources aren’t recreated if the inputs don’t change. This means that as long as the Session ID remains constant, any cached resource with that input will stay cached. Conversely, if the Session ID changes, the resource will be re-initialized.</p><p>We can exploit this behavior to create a session-specific AIAgent whose attributes do not bleed into other sessions. This offers a convenient way to store variables like chat histories. If you recall the AIAgent code from Part 1 of this series, you&#39;ll remember that the class has several attributes like self.prefix, self.response, and self.history. These correspond to the prefix for subsequent prompts (to maintain consistency in chat), dynamic text field content that changes with user interaction, and chat history, respectively.</p><h3><strong>Functions:</strong></h3><p>Streamlit executes the entire code file every time a user interacts with the app. Therefore, it’s recommended to encapsulate as much of your code into functions as possible to ensure smoother code flow. We’ll start with three essential functions.</p><p><strong>AIAgent Instantiation Function</strong>: This function is responsible for creating an instance of our AIAgent and initializing the AIAgent.response attribute. This response will act as the initial value for a dynamic text block we&#39;ll create later. As we want this text to adapt and not revert to its initial state with every user interaction, we store it in the cached AIAgent object. Although the function doesn&#39;t directly use the session_id, it&#39;s included as an input to trigger the caching decorator to reinstantiate the AIAgent every time a new user opens the app or the same user refreshes the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*vfWQJCgTUYGHszLqIyAYjQ.png" /></figure><p><strong>Chat History Formatting Function</strong>: If you remember from Part 1, the openai.ChatCompletion.create method sends a list of dictionaries to the ChatGPT API. Each dictionary represents either a user prompt or a model reply. This arrangement allows the remote model to maintain a &#39;memory&#39; of the conversation, despite this memory actually residing on our end. This function accepts the message history and formats it for the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*W_kNCM5ousAKT5rbVVDUhQ.png" /></figure><p><strong>Query Function</strong>: This is the main function where the real action happens. You’ll notice an object named ‘current_response’ here. This is a Streamlit widget that will display our dynamic text cell. Upon first page opening, the widget displays the text: “Philosophers are waiting patiently, possibly smoking a cigar or pipe”. It’s crucial to verify that this variable has a value other than None before sending the query to the model. This variable is a global one, generated by a text input widget, which we will explain later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-yFUr3VqQ792zlVI8hoVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*W2Oy3_ew-UN66xyx9z-UkQ.png" /></figure><p>Querying the remote ChatGPT model takes some time, resulting in a slight delay between the prompt and response. During this waiting period, the dynamic text box will display a message saying, “The forum is considering your query and will send a representative soon.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*V4BCO3O3Q0Z6v7f9-wFAaA.png" /></figure><p>At times, ChatGPT may be overwhelmed and return an error. We’ve implemented a try-except block to manage such scenarios. If an error occurs, the dynamic text box will display the message: “I’m sorry, all philosophers are busy helping other wisdom seekers. Please try again later.”</p><p>If the query is successful, the model’s reply will appear in the dynamic text box and will also be added to the message history, which is displayed on the sidebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9HsVx6MEWnYyCha6PQEug.png" /></figure><p>One of our objectives in utilizing the AIAgent to store variables is to maintain a text box that can change without resetting each time Streamlit runs the page. It turns out that creating such a text box that can change its values without resetting isn&#39;t straightforward. Initializing the value in the function under the @cache_resource decorator and storing the value in the AIAgent allows us to navigate Streamlit&#39;s native behavior and the challenge of persistent variables effectively.</p><h3>Creating the Widgets for the App:</h3><p>Streamlit simplifies the process of creating widgets for your app. Each type of widget corresponds to a class, and they are arranged on the page in the order they appear in the code.</p><p><strong>Title:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*zNlrnwo9Q5-ySyukXdkgnw.png" /></figure><p>This is pretty straight forward. We use the st.title()method to create a header for our page.</p><p><strong>User Text Input:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*GEiVis1Dz3QugivQlqW8cw.png" /></figure><p>This is where it gets interesting. We can create an st.text_input widget to allow our users to input their questions. The widget code displays the results of the user input. The value of &#39;prompt&#39; is None until the user enters a value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qda1cTIMo4f_Vbh5Tdhi8Q.png" /></figure><p>The widget provides options to set a label, a help icon with a mouse-over value, and placeholder text. I’ve set the value to an empty string so that the box doesn’t contain any initial text, opting to use the placeholder argument instead to create faint text that isn’t an actual input value. Alternatively, you could set the value to be an initial prompt if you wanted a default input.</p><p><strong>Instantiate the AIAgent:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*txy-TT5BQgmMVXwnjl96jg.png" /></figure><p>This code will instantiate a new AIAgent, but only if one hasn&#39;t been created yet and the value of session_id hasn&#39;t changed. Otherwise, it utilizes the cached version.</p><p><strong>Input Button</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*_9plwuoQwSasM8NGjF_mrA.png" /></figure><p>To provide more control over the flow, I’ve used a button to trigger the query to the model. The st.button widget allows us to assign some text to the button and define what occurs when it is clicked. In this case, it will execute the query_agent() function to send the text from the text input widget to the ChatGPT API.</p><p><strong>Sidebar</strong></p><p>Streamlit makes it simple to add a sidebar or top bar to your app. We simply utilize the sidebar functions. In our case, we’ll add a slider to alter the “temperature” of the model reply, a button to clear the chat history and initiate a new conversation, and a text widget to showcase the conversation history for the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*n8CljLlhdQNdGuhE05og3Q.png" /></figure><p>st.sidebar.temperature</p><p>This widget allows the user to adjust a value within a specified range. We utilize this to manipulate the “temperature” of the ChatGPT model’s reply.</p><p>“Temperature” refers to the randomness level in a model’s response. A setting of 0 results in identical replies each time. Although the ChatGPT model allows temperatures up to 2, I restrict users to a maximum of 1 to avoid nonsensical responses. With a temperature of 2, the response often comprised mashed-up words and irrelevant word parts. To ensure sensible responses, I’ve set 1 as the maximum on the slider.</p><p>st.sidebar.button</p><p>The button here triggers the AIAgent.clear_history method, which resets the AIAgent to its initial message history, including the system message, initial prefix, and response for the dynamic text cell.</p><p>st.sidebar.markdown</p><p>This widget places a markdown text element on the sidebar to display a formatted version of the AIAgent.history attribute. Despite not using any markdown syntax, I prefer the markdown widget over the text widget because it formats more pleasingly and wraps itself to fit the sidebar. I&#39;m quite fond of the markdown widget.</p><p><strong>The Dynamic Text Cell</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*08LGvQJL_ov2zc3TbXuXpQ.png" /></figure><p>This seemingly simple line of code works because we employed the strategy of utilizing a cached resource, a session ID, and storing values in the AIAgent object, as opposed to having variables scattered throughout the global namespace. The text changes depending on if the user has not yet made a query, is waiting for a reply, the query failed, or shows the most recent response from the model.</p><p>This text will appear at the bottom of the main page, since it is the last widget defined. It’s important to remember that the creation order of widgets determines their appearance order on the page.</p><h3>Deployment</h3><p>Streamlit’s deployment process is a standout feature, providing ease and flexibility. It’s capable of fetching code directly from GitHub to run on its servers, and even detects new commits, thereby allowing dynamic updates to your app as your code evolves.</p><p>This functionality makes it surprisingly feasible to build your app using GitHub’s text editing web interface. You’ll have the advantage of observing changes on your Streamlit site immediately after each commit. It’s worth noting, however, that if your app has active users, frequent changes and updates could be disruptive to their experience.</p><p>Now let’s see how to get this baby on the web.</p><h3>GitHub Repository</h3><p>Begin by setting up a <a href="https://github.com/">GitHub</a> repository for your project, which will need to include certain specific files. <a href="https://github.com/Caellwyn/chat-with-a-philosopher">Here is a link to my repo</a> for this project, if you want to fork or explore it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YQF0i2kqMi4DMIbdG275A.png" /></figure><p>Streamlit primarily requires one file to function: app.py. This is the file where Streamlit will search for the code needed to construct your app. Keep in mind, however, the file doesn&#39;t necessarily need to bear the name app.py; just ensure that you remember which file contains the code for your Streamlit app.</p><p>In many instances, it’s also critical to incorporate a requirements.txt file. This is particularly necessary if your app needs to import any specific libraries to operate. The app we&#39;re discussing requires three libraries: streamlit, openai, and aiagent.</p><p>The Streamlit site already incorporates the streamlit package, and the aiagent is a custom package included within the repository. However, it&#39;s important to notify Streamlit to import the openai API package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*xb2WBX9YBaMKY2cpdQj87A.png" /></figure><p>You are now ready to create a Streamlit account, link it to your GitHub repository, and deploy your shiny new app!</p><h3>Deploy to Streamlit</h3><p>If you haven’t already, start by creating a Streamlit account <a href="https://share.streamlit.io/">here</a>. I used the ‘Sign in with GitHub’ option, since I’m connecting my account to GitHub anyway.</p><p>Once you’ve done that, click the big blue “New app” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*zDeOsDs8zVwCbZvd-bxSRA.png" /></figure><p>This will bring up the page pictured below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7uc7fzVUKbNnk8WcNPc2g.png" /></figure><p>The default app deployment page is an ‘Interactive Picker’. Streamlit peruses your GitHub and will look for likely repos for deployment. You should be able to find your app repo by clicking in the first box and selecting the one you want to deploy.</p><p>If not, you can select “Paste Github URL” here and paste in the URL to the app.py file in your repository. I actually find this to be the easier way.</p><p>You can choose a URL for your deployed app in the 2nd box.</p><p>But wait! Don’t deploy it yet! We have a secret…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPSEQ9PEO4bJTHfREEmzCA.png" /></figure><p>Click on ‘Advanced settings’ to bring up the next interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*p-q4N2-VhqOjsOz5vg0aug.png" /></figure><p>This section is important.</p><p>First off, be sure that Streamlit is using the same version of Python you used to create your app. In this case I used 3.9, but you should make sure it matches the version you used.</p><p>Next are the secrets. Streamlit secrets are how we can securely store things like passwords and api keys. The app can use them, but visitors can not see them. Since the openai API requires an API key, this is where you’ll put it.</p><p>You may recall from Part 1 of this tutorial that we uses openai.api_key = streamlit.secrets[&#39;OPENAI_API_KEY&#39;] to set the API key to allow us to make API calls that will be charged to our account. Be sure of 2 things:</p><ol><li>The dictionary key you use in your code to access the secret API key matches the key you set here.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*Ds0DmBWn2_vh7LqJAzTPqw.png" /></figure><p>2. You’ve added quotation marks around the API key you want to store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*9-mASwZzuDrkC45YXbVX0A.png" /></figure><p>Now, you are ready to deploy and enjoy!</p><p>If you run into errors, you can get some helpful outputs in the Manage app pull-out. You can see this when you are logged in, but other visitors will not see it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJPAtL0DOVLhVdXD_NVbTQ.png" /></figure><p>You can adjust the code for your app directly from the GitHub editor if you wish to debug from there, or you can deploy it locally on your machine for debugging, then push the working copy to your remote GitHub repository.</p><p>The 2nd option is probably better, especially if you expect anyone else to be interfacing with your app.</p><h3>Conclusion</h3><p>In this tutorial, we delved into the process of deploying an app via Streamlit by linking a GitHub repository to your Streamlit account. This process also illuminated how to effectively manage the control flow of your Streamlit app, keeping in mind that the entire code file is re-executed each time a user interacts with the deployed app.</p><p>You discovered the use of session IDs and class attributes of cached resources as a strategic approach to retain information and prevent data leakage between users. This method enables your app to exhibit dynamic responsiveness and maintain a pseudo-memory state, despite Streamlit’s inherent stateless design.</p><p>Moreover, we explored how to leverage widgets to enhance user interaction and provide real-time control over the app’s behavior. Importantly, we learned how to circumvent the challenges associated with Streamlit’s statelessness, such as implementing a dynamic text box that can retain changes, using a combination of cached resources, a session ID, and storing values in an object rather than having them in the global namespace.</p><p>We covered some crucial aspects of app deployment, including the importance of the app.py file and the necessity of a requirements.txt file for specifying library dependencies. All these insights equip you to create more robust, interactive, and user-friendly applications with Streamlit.</p><p>Finally, you saw how to deploy your app live to the web for others to enjoy.</p><h3>Links:</h3><p><strong>Project Repository</strong>: <a href="https://github.com/Caellwyn/chat-with-a-philosopher/tree/main">https://github.com/Caellwyn/chat-with-a-philosopher/tree/main</a></p><p><strong>Deployed Streamlit App</strong>: <a href="https://caellwyn-chat-with-a-philosopher-app-hgvk78.streamlit.app/">https://caellwyn-chat-with-a-philosopher-app-hgvk78.streamlit.app/</a></p><p><strong>OpenAI API Reference</strong>: <a href="https://platform.openai.com/docs/api-reference/completions/create">https://platform.openai.com/docs/api-reference/completions/create</a></p><p><strong>Streamlit API Reference:</strong> <a href="https://docs.streamlit.io/library/api-reference">https://docs.streamlit.io/library/api-reference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c1c7c90033b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a ChatGPT Powered Web App to Chat With Historical Philosophers]]></title>
            <link>https://caellwyn.medium.com/create-a-chatgpt-powered-web-app-to-chat-with-historical-philosophers-d4d602bd10f0?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4d602bd10f0</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-model-deployment]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 18:15:49 GMT</pubDate>
            <atom:updated>2023-06-25T18:05:53.194Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create a ChatGPT Powered Web App to Chat With Historical Philosophers, Part 1: OpenAI API and Prompt Engineering</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*P9f2yz6pctHAbciCs9-aSA.png" /></figure><h3>Introduction</h3><p>This is Part 1 of a 2 part tutorial on creating an app that leverages the ChatGPT PythonAPI and deploying it to the web using Streamlit.</p><p>This tutorial will guide you on creating a web app powered by ChatGPT, which enables users to chat with historical philosophers on any topic. The app selects a philosopher who has written about the question’s topic and responds from their perspective while providing references to their work.</p><p>Large Language Models (LLMs) like ChatGPT are versatile tools that can be applied to various tasks, from coding to chatting to formatting documents. However, their greatest strength lies in language understanding, be it English, Python, or SQL.</p><p>Philosophy is particularly suitable for LLMs because it revolves around language. It is a human attempt to articulate the world and utilize words to comprehend the enigmatic and bewildering aspects of our surroundings and experiences. For a more technical and mathematical take on this endeavor, we can turn to the field of “Data Science.”</p><p>In this tutorial, I will demonstrate how to utilize the OpenAI API, Streamlit, and effective prompt engineering to specialize an LLM for a specific task with minimal code. We will direct ChatGPT to research, summarize, and present the viewpoints of different philosophers on profound questions raised by users.</p><p>Requirements</p><ol><li><strong>OpenAI API Key and Python Package</strong>: To get started, sign up for an OpenAI API key using this link. Note that this service is not free, so expect a small fee. During the development of my app, I spent $0.77 on API calls. OpenAI allows you to set usage caps, but I haven’t made my app public to avoid exceeding them. To install the OpenAI API Python package, use the command pip install openai in your terminal.</li><li><strong>Python IDE</strong>: This tutorial employs Python, so you’ll need a Python environment to run the code. While it’s technically possible to replicate this and have a functional app using only GitHub and a Streamlit account (as Streamlit can read directly from GitHub and you can edit documents on the GitHub website), I recommend using a Python environment in a user-friendly IDE like VS Code. This way, you can test your app locally before deploying it to the web.</li><li><strong>Streamlit</strong>: Streamlit is a simplified Python package and web platform for building web applications. It makes it easy to insert text and widgets using an object-oriented approach. Install Streamlit into your Python environment with pip install streamlit in your terminal. Once you&#39;ve developed your app, you can run it locally from the terminal using streamlit run app.py. <br>What’s even more exciting is that after developing and pushing your app to a GitHub repository, the Streamlit website can create a live web-based app for you for free! I love that with Streamlit I can develop and test my app locally until it meets my requirements. Then, I simply push it to GitHub and deploy it with a few clicks on the Streamlit site. If I need to make changes, I can easily push the updates to the same repository. Streamlit automatically detects the changes and updates the live app. Development and troubleshooting are remarkably straightforward!</li><li><strong>GitHub Account:</strong> While optional if you don’t plan to deploy your app to the web, I recommend having a GitHub account if you’re here for code tutorials. If you wish to deploy your app using the Streamlit site, you’ll need a GitHub account and a repository for your code.</li></ol><h3>The ChatGPT API</h3><p>The code in this app is divided into two parts. “app.py” focuses on using Streamlit to create an interactive app that interacts with the model, while “AIAgent.py” contains the AIAgent class responsible for interacting with the ChatGPT model. This part of the tutorial will focus on the AIAgent.</p><p>OpenAI provides an excellent guide for using their API, which includes prompt engineering tips, new application ideas, and user-friendly API documentation. You can find their general guides, tips, and tricks <a href="https://platform.openai.com/docs/introduction">here</a>. However, to get started, we are interested in the actual API references found <a href="https://platform.openai.com/docs/api-reference/introduction">here</a>.</p><p>In this demonstration, we only need two API functions: setting the secret API key and passing a prompt, or more specifically a list of prompts that represent the history of a conversation.</p><p><strong>Cost</strong></p><p>As mentioned earlier, you’ll need an API key from OpenAI to make queries to the model from your code. Obtaining the key is free, but usage incurs a fee. You’ll need to provide a credit card, and you’ll be charged a very small amount per ‘token’. At the time of writing, the cost is $0.003/1000 tokens to use GPT-3.5.</p><p><strong>Tokens</strong></p><p>But what is a token? It’s similar to a word but not exactly the same. Tokens are semantic word parts used by the model to parse text. OpenAI suggests that 1 token is roughly equivalent to 3/4 of a word. Therefore, a 1000-word prompt would consume approximately 1250 tokens.</p><p><em>Remember that you’ll be charged for tokens both in the prompts and the model’s reply.</em></p><p>Once you have your API key, you can add it to the API by assigning it to the openai.api_key attribute.</p><pre>import openai<br>openai.api_key = &lt;your key&gt;</pre><p>If you’re committing your code to GitHub, <strong>ensure that your API key is NOT visible</strong> in your code or any files within your repository. Never make your API keys publicly viewable, as you’ve linked your credit card to them!</p><p>One approach to avoid exposing your API key is to set it as an environment variable. <a href="https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety">Here is a simple and straightforward guide on how to do that</a>. Once your key is stored as an environment variable, you can access it in your code like this:</p><pre>import os<br>import openai<br>openai.api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)</pre><p>When you’re ready to deploy to Streamlit, you’ll need to add your key to the “Streamlit Secrets” for your app. I’ll explain how to do that in Part 2.</p><p><strong>Completions and ChatCompletions</strong></p><p>Why does OpenAI call questions to the model ‘completions’?</p><p>ChatGPT is, in fact, a text completion model sometimes referred to as ‘Autocomplete on Steroids.’ Large Language Models like ChatGPT are prediction engines that forecast the next token. They use your prompt as context and generate tokens in response one at a time. After each new token, the model evaluates the context prompt and the text generated so far, and predicts the next token. The model repeats this process until the &lt;end&gt; token is predicted. For an informative introduction to this topic, check out this <a href="https://blog.dataiku.com/large-language-model-chatgpt">Dataiku article by Kurt Muehmel.</a></p><p>Once you’ve added your API key to the openai.api_key attribute, you&#39;re ready to try a completion.</p><p>There are two classes to choose from when requesting completions: openai.Completion and openai.ChatCompletion.</p><p>But what’s the difference?</p><p>The Completion class is suitable for a single prompt without any follow-up. You only need to specify the model to access and the prompt itself.</p><pre>response = openai.Completion.create(<br>      model=&quot;gpt-3.5&quot;,<br>      prompt=&quot;What is the meaning of life?&quot;<br>      )</pre><p>On the other hand, the ChatCompletion class can maintain a conversation by stringing together multiple prompts. The model &#39;remembers&#39; the previous conversation and considers it as part of its context for each new prompt.</p><p>However, the ‘memory’ is not stored on OpenAI’s side; it’s your responsibility! You need to maintain a list of all the messages exchanged and provide the entire list to the API for each new prompt.</p><p>Note: You’ll be charged for each token in the conversation for both messages and responses in subsequent completions. For example, if your conversation spans five turns, you’ll be charged for the first prompt five times, once for each time it was sent back to the model as part of the conversation history.</p><p>While the Completion class requires only a single string prompt, the ChatCompletion class accepts a list of dictionaries using the messages argument.</p><pre>response = openai.ChatCompletion.create(<br>  model=&quot;gpt-3.5-turbo&quot;,<br>  messages=[<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello!&quot;},<br>    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Hello! How can I assist you today?&quot;},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;I&#39;d like to know about the meaning of life.&quot;}<br>  ]<br>)</pre><p>Each dictionary in the messages list identifies the speaker and their content using the &quot;role&quot; and &quot;content&quot; keys, respectively. The &quot;role&quot; key indicates whether it&#39;s the user or the model speaking, while the &quot;content&quot; key holds the actual prompt or reply. This way, your code can maintain a local memory for the model.</p><p>It’s important to note that the actual model running on OpenAI servers does not remember your conversation. It lacks its own memory and is neither conscious nor self-aware. This distinction is crucial given our philosophical theme. The model’s memory is an illusion that you create for your users or, at best, an additional component to the actual model.</p><p>Both openai.Completion.create and openai.ChatCompletion.create offer additional arguments to fine-tune the responses or limit their size, but for a quick start, these are the only ones we need.</p><h3>System Message and Prompt Engineering</h3><p>The true magic behind the Chat with a Philosopher app lies in the system prompt and prompt engineering strategies.</p><p>The system prompt allows us to include a hidden “system” message as the first message, which primes the model to respond in a specific manner. It adds an element of mystery to the app, making it seem like magic. Let’s take a closer look at the system message that transforms ChatGPT into a philosopher:</p><pre>system_message = &quot;&quot;&quot;For each query, consider writings by philosophers that have<br>         addressed that question and choose one.<br>        Respond to the query from the point of view of that philosopher<br>        Finally, use those referenced sources to form a response to the <br>        query that the chosen philosopher would support.<br>        Your response should be written from the point of view of that <br>        philosopher and be sure your response is supported by original sources<br>        of text authored by that philosopher.  <br>        You should reference those sources in your response.<br>        For example:<br>        Query: What is the meaning of life?<br>        Response: Hi, my name is Albert Camus.  In The Myth of Sysyphus, <br>        I wrote about how life is meaningless from<br>        an objective viewpoint, but that we can create our own meaning for our<br>        lives.  In my works of fiction, I describe situations where people <br>        must make their own meaning in during times of crisis, doubt and <br>        confusion.<br>        Ultimately, life is what you make of it and it means what it means <br>        to you.  One of my most famous quotes is:<br>        &quot;The meaning of life is whatever you are doing that keeps you <br>        from killing yourself.&quot;&quot;&quot;<br>        message = [{&#39;role&#39;: &#39;system&#39;, &#39;content&#39;:system_message}]</pre><p>Implementing several prompt engineering strategies, the system message is the result of multiple iterations. It’s important to note that you may not achieve the perfect prompt on the first attempt. Continue tweaking it until you obtain the desired responses.</p><p>Let’s discuss the prompt engineering strategies employed:</p><ol><li><strong>Explicitly guide the model’s thought process:</strong></li></ol><blockquote>“For each query, consider writings by philosophers that have addressed that question and choose one”</blockquote><ul><li>We want the model to conduct research and identify philosophers who have written about the given topic. This prevents the model from inventing information and attributing it to the wrong philosopher.</li></ul><blockquote>“Respond to the query from the point of view of that philosopher”</blockquote><ul><li>This step adds an immersive experience as the model pretends to be the philosopher while responding.</li></ul><blockquote>“Finally, use those referenced sources to form a response to the query that the chosen philosopher would support”</blockquote><ul><li>We emphasize the importance of grounding the response in references and writings that the philosopher has authored to help prevent ‘Hallucinations’, or incorrect information that the model has invented on its own.</li></ul><p><strong>2. Define the expected response:</strong></p><blockquote>“Your response should be written from the point of view of that philosopher and be sure your response is supported by original sources of text authored by that philosopher. You should reference those sources in your response.”</blockquote><ul><li>We instruct the model to ensure that the response reflects the philosopher’s perspective and is supported by references to their original works.</li></ul><p><strong>3. Utilize few-shot learning by providing an example:</strong></p><blockquote>Query: “What is the meaning of life?”</blockquote><blockquote>Response: “Hi, my name is Albert Camus. In The Myth of Sysyphus, I wrote about how life is meaningless from an objective viewpoint, but that we can create our own meaning for our lives. In my works of fiction, I describe situations where people must make their own meaning during times of crisis, doubt, and confusion. Ultimately, life is what you make of it and it means what it means to you. One of my most famous quotes is: ‘The meaning of life is whatever you are doing that keeps you from killing yourself.’”</blockquote><p>In this example, we not only tell the model what we expect but also show it through the provided response. By assuming the role of Albert Camus, we include textual references and even incorporate a quote.</p><p>Prompt engineering is a powerful technique that improves the model’s performance. By providing explicit instructions, assuming roles, and using references, we enhance the accuracy and quality of the responses.</p><p>Compare the above example response to an actual response the model provided:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*P9f2yz6pctHAbciCs9-aSA.png" /><figcaption>Chat with a Philosopher: What is the meaning of life?</figcaption></figure><p>Notice that while the model is responding to the same question as the example we gave it, it answers as a different philosopher with a different point of view.</p><p>The model:</p><ol><li>Starts with a greeting playing the role of Aristotle</li><li>Immediately provides a text reference to Nicomachean Ethics and a summary of its relevant content.</li><li>Provides a second reference with more information.</li><li>Summarizes the response.</li></ol><p>It doesn’t include a quote, but I also did not ask for that in my instructions outside of the example. If we wanted this to be more consistent, we could add the requirement explicitly before the example reponse.</p><h3>Putting the Pieces Together and Sending the prompt</h3><p>Now that we have our system prompt, it’s time to add a user prompt. The AIAgent class maintains a list of messages, acting as a &#39;memory&#39; for the conversation. The system message is placed first and is not visible to the user. The remaining messages in the list alternate between the roles of &quot;user&quot; and &quot;assistant&quot;.</p><p>When a query is made, the user prompt is added to the list. The entire conversation history is then sent to the model, and the model generates a response, which is subsequently added to the conversation history.</p><pre>import os<br>import openai<br><br># Set the OpenAI API key<br>openai.api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>    <br>class AIAgent():<br>    def __init__(self, model=&quot;gpt-3.5-turbo&quot;):<br>        &quot;&quot;&quot;Initialize the AI Agent.  Set the system message, <br>        initial prompt prefix, and initial response&quot;&quot;&quot;<br><br>        self.model=model<br><br>        self.system_message = &quot;&quot;&quot;For each query, consider writings by philosophers that have addressed that question and choose one.<br>        Respond to the query from the point of view of that philosopher<br>        Finally, use those referenced sources to form a response to the query that the chosen philosopher would support.<br>        Your response should be written from the point of view of that philosopher and be sure your response is supported by original sources<br>        of text authored by that philosopher.  You should reference those sources in your response.<br>        For example:<br>        Query: What is the meaning of life?<br>        Response: Hi, my name is Albert Camus.  In The Myth of Sisyphus, I wrote about how life is meaningless from<br>        an objective viewpoint, but that we can create our own meaning for our lives.  In my works of fiction, I describe<br>        situations where people must make their own meaning in during times of crisis, doubt and confusion.<br>        Ultimately, life is what you make of it and it means what it means to you.  One of my most famous quotes is:<br>        &quot;The meaning of life is whatever you are doing that keeps you from killing yourself.&quot;&quot;&quot;<br>        <br>        # Initialize the prompt prefix<br>        self.prefix = &#39;&#39;<br><br>        # Add system message to message history<br>        self.history = [{&#39;role&#39;: &#39;system&#39;, &#39;content&#39;:self.system_message}]<br><br>        # Intialize pre-prompt output<br>        self.response = &#39;Philosophers are waiting patiently, possibly smoking a cigar or pipe&#39;<br>        <br>    def add_message(self, text, role):<br>        &quot;&quot;&quot;Add a message to the conversation history&quot;&quot;&quot;<br><br>        message = {&#39;role&#39;:role, &#39;content&#39;:text}<br>        self.history.append(message)<br>        <br>    def query(self, prompt, temperature=.1):<br>        &quot;&quot;&quot;Query the remote model and add messages to the hisotry&quot;&quot;&quot;<br>        <br>        # Add user prompt to history<br>        self.add_message(self.prefix + prompt, &#39;user&#39;)<br><br>        # Query the model through the API <br>        result = openai.ChatCompletion.create(<br>            model=self.model,<br>            messages=self.history,<br>            temperature=temperature, # this is the degree of randomness of the model&#39;s output<br>        )<br><br>        self.response = result.choices[0].message[&quot;content&quot;]<br><br>        # Add reply to message history<br>        self.add_message(self.response, &#39;assistant&#39;)<br>        <br>        # set prompt prefix to ensure same philosopher answers each time.<br>        self.prefix = &#39;Please continue to respond as the previous philosopher: &#39;<br>           <br>    def clear_history(self):<br>        &quot;&quot;&quot;Reset the history to its initial state.  <br>        Also reset the prefix and current response&quot;&quot;&quot;<br>        <br>        self.history = [{&#39;role&#39;:&#39;system&#39;, &#39;content&#39;:self.system_message}]<br>        self.prefix = &#39;&#39;<br>        self.response = &#39;Philosophers are waiting patiently, possibly smoking a cigar or pipe&#39;</pre><p>The response object contains a lot of information about the transaction, but we are interested in the actual content of the response:</p><pre>self.response = result.choices[0].message[&quot;content&quot;]</pre><p>This is what we want to show the user and add to the message history.</p><p><strong>Prompt Wrappers</strong></p><p>The last thing to notice is that prompts can be wrapped in additional instructions. In this case we add “Please continue to respond as the previous philosopher: ” to the beginning of each prompt after the first.</p><pre>self.prefix = &#39;Please continue to respond as the previous philosopher: &#39;</pre><pre>self.add_message(self.prefix + prompt, &#39;user&#39;)</pre><p>This ensures that the model is consistent and the user can continue to converse with the same philosopher until they start a new conversation.</p><h3><strong>Summary</strong></h3><p>In this section, you gained insights into using the OpenAI API to engage with the ChatGPT-3.5 model. You explored the Completion and ChatCompletion classes, understanding their distinctions and how to leverage conversation history in the form of a list of dictionaries when interacting with the model through the API.</p><p>Additionally, you discovered essential prompt engineering strategies aimed at ensuring the model produces the desired responses. By explicitly guiding the model’s thought process and defining the expected format of the responses, you can influence the model’s behavior and enhance the accuracy and relevance of its outputs.</p><p>In <a href="https://caellwyn.medium.com/create-a-chatgpt-powered-web-app-to-chat-with-historical-philosophers-1c1c7c90033b">Part 2</a> you’ll learn how to transform your code into a web-app for others to interact with.</p><h3>Links</h3><p><a href="https://caellwyn.medium.com/create-a-chatgpt-powered-web-app-to-chat-with-historical-philosophers-1c1c7c90033b">Link to Part 2</a></p><p><a href="https://github.com/Caellwyn/chat-with-a-philosopher">Link to GitHub repository for this project</a></p><p><a href="https://caellwyn-chat-with-a-philosopher-app-hgvk78.streamlit.app/">Link to Chat with a Philosopher Site</a></p><h3>References:</h3><p>OpenAI Documentation References: <a href="https://platform.openai.com/docs/introduction">https://platform.openai.com/docs/introduction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4d602bd10f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Trace Data to Time Series With Panda Magic]]></title>
            <link>https://medium.com/data-science/from-trace-data-to-time-series-with-panda-magic-8efe0fa4ea82?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/8efe0fa4ea82</guid>
            <category><![CDATA[join-tables]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[time-series-data]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Sun, 16 May 2021 22:12:07 GMT</pubDate>
            <atom:updated>2021-05-16T23:34:17.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lCeI-2FQhBYX4aqt" /><figcaption>Photo by <a href="https://unsplash.com/@julilona?utm_source=medium&amp;utm_medium=referral">Ilona Froehlich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article will guide you through quickly transforming millions of rows of trace data into a wide format time series table using the power of mighty Pandas.</p><h3>The Data</h3><p>For this demonstration, I’ll be using the <a href="https://analyse.kmi.open.ac.uk/open_dataset">OULAD dataset</a> from Open University. The full dataset, as well as a lovely data description, is available at the link above. This is a dataset about student activity in a virtual learning environment in online classes. It spans 2 years and four cohorts for each of 7 modules.</p><p>I’ve written about this dataset before, as it’s one of my favorites. You can read about some of my previous work building predictive models using this data in my article, <a href="https://towardsdatascience.com/predicting-student-outcomes-by-how-they-interact-with-their-learning-environment-41b84e46c839">Predicting Student Outcomes by How They Interact With Their Learning Environment</a>.</p><p>Today we will be exploring the student_vle.csv file in the zipped collection. This file contains trace data for student interactions with online activities accessible in the learning environment. Each row represents one activity that the student completed and includes the number of clicks they made in that activity.</p><h3>The Goal</h3><p>In my previous approach to this dataset I used aggregations of this trace data to make predictions on whether students would pass the class or not. I used the total number of clicks the student had made.</p><p>But now I use student behavior on a day by day basis to make my predictions. This means using time series data to describe how the student’s engagement changes over the course of time. For this article, I’ll just record the number of clicks the student made each day, though for my actual model I use more variables, and have multiple columns for each day of the course as input variables.</p><p>Since I want time series data for each student, I will create a wide format time series table from the individual activity interaction observations. Each row will be a single student in a given cohort of a given course. Each column describes the number of clicks a student made on activities in the learning environment on that day.</p><p>The dates are relative to the start date of that cohort. Some student started working up to 25 days before the start of the course and the courses are 270 days long. Therefore our final table will have 295 columns.</p><p>This is what we want it to look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-SinsnCi9SgmgsoFPGu7Q.png" /><figcaption>Image by Author</figcaption></figure><h3>Process Overview</h3><p>The first time I tried to transform my data from the trace log to the wide form time series table I tried to use a nested for loop to read each entry in the trace log and place in the correct place on the new table. <strong>Don’t do this. </strong>I watched the process progress for a bit, using a counter, and did some quick math. With a little more than 10 million rows of trace data, this was going to take me over 5 days of run time to complete. There’s a saying, “If you are using a nested for loop with Pandas, there is probably a better way.”</p><p>Instead, I used boolean masks to create what the Pandas documentation calls ‘views’, or filtered looks into the data without mangling the original. I did this by filtering the data for each day individually and merging the results of that view into a new dataframe in chronological order.</p><h3>Process Details</h3><p>The trace data starts a just a list of activity interactions with variables describing the activity, the module, the cohort, the student, and the number of clicks. I combined the module, cohort, and student into one ‘registration’ column for easier indexing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*r7tE4T2JZAxhGpXRVGT3fA.png" /><figcaption>Image by Author</figcaption></figure><p>As you can see, there are multiple entries per student per day, and even per activity, since each entry is an individual interaction with an individual activity. Students often seem to interact with the same activity several times on the same day. The first thing we need to do, to get data on clicks per day, is to group the data. To learn more about how to use Pandas Groupby functions, you can read my <a href="https://towardsdatascience.com/pandas-groupby-love-5b3bce19c35e">article on the subject</a>.</p><p>We can group this table by student and day with the following code:</p><h4>Group by Student and Day</h4><pre>def group_by_day(student_vle):</pre><pre>   #group by registration and day<br>   vle_group = student_vle.groupby(by = [‘registration’, ‘date’])</pre><pre>   #sum up the clicks for each day for each student<br>   sum_clicks = vle_group.sum().reset_index()<br>   sum_clicks = sum_clicks.drop(columns=[&#39;id_site&#39;])</pre><pre>   #sort by student and day<br>   sum_clicks = sum_clicks.sort_values(by=[‘registration’,’date’])</pre><pre>   return sum_clicks</pre><p>The function group_by_day() uses the df.groupby() Pandas method to group the data by student and day, and the df.sum() aggregation method to make a new dataframe with each student’s clicks summed up for each day.</p><p>I also do a completely unnecessary sort, because it’s nice to see the data sorted by student and day to get a brief sense of it, but that is not at all needed for the next steps. If you are processing an even larger dataset, or putting code into production, definitely skip this step.</p><p>This code returns the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FinKggVc147iPkd1Nrv7Yw.png" /><figcaption>Image by Author</figcaption></figure><p>We now have just one entry per student per day. The sums of their clicks per activity have been added together to represent the sum of their clicks for the whole day, rather than per activity interaction instance.</p><p>Thanks to my need for order, the entries are organized by student and day. I think it’s nice to see each student’s workflow through the days of the module.</p><p>Now we can start cutting apart this table, day by day, and gluing those pieces back together side by side with the following code:</p><h4>Filter and Merge</h4><pre>def create_time_series(sum_clicks):</pre><pre>   #Create a new dataframe to hold our timeseries data.<br>   time_series = pd.DataFrame()</pre><pre>   #Create one row for each student registration<br>   time_series[&#39;registration&#39;] = sum_clicks[&#39;registration&#39;].unique()</pre><pre>   start_date = sum_clicks[&#39;date&#39;].min()<br>   end_date = sum_clicks[&#39;date&#39;].max()<br>   date_range = range(start_date, end_date)</pre><pre>   counter = len(date_range)</pre><pre>   #Iterate through the days of the course:</pre><pre>   for date in date_range:</pre><pre>      #create a views of the data, one day at a time.</pre><pre>      single_date_df = sum_clicks[sum_clicks[&#39;date&#39;] == date]<br>      single_date_df = single_date_df.drop(columns=[&#39;date&#39;])</pre><pre>      #rename columns to describe date and data.<br>      new_cols = [&#39;registration&#39;] +   [f&#39;clicks_on_day_{date}&#39;]</pre><pre>      single_date_df.columns = new_cols</pre><pre>      #merge into the time series dataframe.</pre><pre>      time_series = time_series.merge(single_date_df,<br>                                      how=&#39;left&#39;,<br>                                      on=&#39;registration&#39;,<br>                                      validate = &#39;1:m&#39;)</pre><pre>      print(&#39;Days remaining to be processed: &#39;, counter)<br>      clear_output(wait=True)<br>      counter -= 1</pre><pre>   #Missing data represents no clicks that day, so fill with 0.</pre><pre>   time_series = time_series.fillna(0)</pre><pre>   time_series = time_series.set_index(&#39;registration&#39;, drop=True)</pre><pre>   return time_series</pre><h4>Filter</h4><p>The above function iterates through each day of the module and uses a boolean array, an array of Trues and Falses, to filter for data from just that day. It checks the ‘date’ variable for each row and returns only the rows whose dates match the current date for that iteration.</p><p>For example:</p><p>sum_clicks[&#39;date&#39;] == 0would return a series the same length as sum_clicks, but filled a True for each row whose data variable is ‘0’ and False for the rest.</p><p>sum_clicks[sum_clicks[&#39;date&#39;] == 0] will return a view of only the rows where the boolean array contains True.</p><p>When we apply the above filter to the sum_clicks table, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*zHsSnnuIAC_QC3_tujLJ8g.png" /><figcaption>Image by Author</figcaption></figure><p>Notice that we only have the sum of the clicks for each student for day 0, or the first day of the course. You might also realize that most students probably don’t do work in the virtual learning environment for every day. So each daily view will not contain every student. The left join in the next step will help resolve that.</p><p>The next part of the above function merges each daily view onto a dataframe we already prepared that has a row for each student registration, but no data.</p><h4>Merge</h4><pre>time_series = time_series.merge(single_date_df,<br>                                how=’left’,<br>                                on=’registration’,<br>                                validate = ‘1:m’)</pre><p>df.merge() is one way to merge one dataframe to another. This is equivalent to joining tables in SQL another data management tools. The magic in this approach is here in the merge. I prepared the empty dataframe named ‘time_series’ specifically to join each of these views onto in chronological order. This dataframe has one column called ‘registration’ that represents the unique registrations present in the data. One row per student registration, no more, no less. This is important.</p><p>When I merge each daily view in my for loop, I use ‘registration’ as a key. This ensures that the right data goes into the right row, even if the rows are not in the same order in both ‘time_series’ and the daily view we are merging. We also need to think about our data integrity when we are transforming data like this. Merging with keys is the best way to make sure your values don’t get mixed up between your rows.</p><p>how=&#39;left&#39; tells Pandas to preserve the records of the left dataframe, in this case, ‘time_series’. Don’t drop any, don’t add any, don’t rearrange them. Just take the rows in the right dataframe, in this case, ‘single_date_df’, and attach the ones that match. Drop any that don’t. We want to make sure there is exactly one record per registration for each day.</p><p>on=&#39;registration&#39; tells Pandas to use that column as the key to match the rows of each dataframe. Otherwise it won’t know which rows in the single_date_df dataframe go where when they merge! Finally, validate=&#39;m:1&#39; means ‘Many-to-One’. This tells Pandas to check that there is only one value in the right dataframe for each day. One more way to make sure our data doesn’t get messed up. If there is no record in the right dataframe, ‘single_day_df’, that matches a registration in the left, ‘time_series’, Pandas will fill that value with np.nan, or ‘no data’.</p><p>Once this loop finishes, the dataframe will have all the click counts for each day, for each student, arranged chronologically left to right. Anyplace that no clicks were found for a student on a particular day will have an np.nan. We will use time_series = time_series.fillna(0) to replace those np.nans with zeros. After all, that’s what that np.nan really means: the student didn’t click anything that day.</p><p>I also set ‘registration’ as the index, because Pandas lets me, it’s fast, and that’s really what that column is, the index of student registrations. I didn’t do it earlier because it simplifies the merging syntax a little to have it as its own column.</p><p>Here is our final table. It’s very sparse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLFQOjLWpe4qU9ht78E4-Q.png" /><figcaption>Image by Author</figcaption></figure><h3>Bonus: Sparsify!</h3><p>Just because I love you all, I want to show you one more trick. The time series dataframe we created above is mostly full of zeros. This is known in the biz as a ‘sparse dataframe’. This one is just a little sparse, but other dataframes we might use are overwhelmingly filled with zeros. If we save them like this it wastes a lot of space recording each zero separately. Once again, Pandas to the rescue!</p><p>We can compress the dataframe by essentially removing the zeros while keeping track of where they should go with:</p><p>sparse_time_series = time_series.astype(pd.SparseDtype(&#39;int&#39;, 0))</p><p>The above code compresses the time series dataframe by about 1/3 the size, by removing the zeros. In the (pd.SparseDtype(&#39;int&#39;, 0) part of the code, we tell Pandas that the resulting sparse dataframe will have values of type ‘int’ or integer, and that the zeros are what we want to compress.</p><p>In other applications, especially Natural Language Processing, data can be compressed to MANY times smaller using this method.</p><h3>Summary</h3><p>You learned how to convert a trace data record, which could be user interactions, or Internet of Things pings, or anything the returns a value periodically, into a wide form time series data frame aggregated by a chosen period, in this case by day. You learned how to use df.groupby to aggregate to the data, to pass a boolean mask to a dataframe, such as df[df[&#39;date&#39;] == 0]] to create a view of just the data you want in a column, and df.merge() to iteratively attach each period’s data to the previous to make that wide format time series dataframe.</p><p>As a bonus, you learned a compression method to story sparse dataframes more efficiently. This becomes very important when you have very large, very sparse data sets you want to use for modeling. Many standard machine learning tools handle sparse dataframes efficiently.</p><p>In the case of the above example, these strategies reduce processing times from 5 days to under 1 or 2 minutes, depending on your machine.</p><h3>Full Code:</h3><p>Here’s a Github Gist of the full code that will download, unzip, and transform this particular dataset. Please feel free to copy it and use it as a template for your own projects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac75fef0b4ea1232d7d75f79fbd5c8b4/href">https://medium.com/media/ac75fef0b4ea1232d7d75f79fbd5c8b4/href</a></iframe><h3>References:</h3><p>Kuzilek J., Hlosta M., Zdrahal Z. <a href="https://www.nature.com/articles/sdata2017171">Open University Learning Analytics dataset </a>Sci. Data 4:170171 doi: 10.1038/sdata.2017.171 (2017).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8efe0fa4ea82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-trace-data-to-time-series-with-panda-magic-8efe0fa4ea82">From Trace Data to Time Series With Panda Magic</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Groupby Love]]></title>
            <link>https://medium.com/data-science/pandas-groupby-love-5b3bce19c35e?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b3bce19c35e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python-pandas]]></category>
            <category><![CDATA[pandas-groupby]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 20:39:24 GMT</pubDate>
            <atom:updated>2021-03-16T12:09:39.751Z</atom:updated>
            <content:encoded><![CDATA[<h4>Wrap your brain around one of Pandas’ most powerful tools for statistical analysis.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qBG-iqtu3hg62BrR" /><figcaption>Photo by <a href="https://unsplash.com/@millerthachiller?utm_source=medium&amp;utm_medium=referral">Pascal Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial you will learn how to use the Pandas dataframe .groupby() method and aggregator methods such as .mean() and .count() to quickly extract statistics from a large dataset (over 10 million rows). You will also be introduced to the <a href="https://analyse.kmi.open.ac.uk/open_dataset">Open University Learning Analytics dataset</a></p><h3>Pandas</h3><p>Pandas is the most adorable and cuddly tabular data management library for Python. Once you get the hang of it its intuitive, object-oriented implementation and clever tricks to improve computational efficiency make for flexible and powerful data handling.</p><p>Pandas facilitates data mining, data processing, data cleaning, data visualization, and some basic statistical analysis on small to largish datasets.</p><h3>Groupby</h3><p>One of Pandas’ most important analytical tools is the .groupby() method for Pandas DataFrame objects. When you pass the name of a column of categorical data to the .groupby(by=&#39;column&#39;) of a dataframe, the returned object will have each of the unique categories in the grouped column as the indices of the rows, the other features you did not group by as columns, and a third dimension of stacks of samples organized by the category used for the grouping. This method returns a new groupby object with one dimension more than the one that called it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w96xHC3s1XZzNkESlitGJA.png" /><figcaption>Image by Author</figcaption></figure><h3>Aggregators</h3><p>Aggregators return a matrix with one fewer dimensions than they aggregate and full of the desired statistic for the squished dimension. If groupbyis a groupby object, groupby.mean() will return a dataframe of mean averages of features of samples in each of the categories the groupby object was grouped by. Other aggregators include: .count(), .sum(), and .std().</p><p><strong>Open University Learning Analytics Dataset</strong></p><p>Let’s see this all in action. I’ll be using the studentVle.csv data from <a href="https://analyse.kmi.open.ac.uk/open_dataset">https://analyse.kmi.open.ac.uk/open_dataset</a>. This is a dataset of anonymized online learner records for several courses over a 2 year period. The table I’ve chosen is a record of individual interactions between a student and a learning activity or resource connected to the virtual learning environment (VLE).</p><p>As a data scientist, we always want to be clear about our goals. In this groupby example I want to find out how many activities each student engaged and the average number of clicks per activity.</p><p>The code below will download the dataset, which is large, and it make take awhile. Once it downloads the data, it will unzip the file with student/VLE interaction records. As always, I encourage you to use my examples as a starting point to use with your own data.</p><pre>import pandas as pd<br>import zipfile<br>import wget</pre><pre>url = &#39;<a href="https://analyse.kmi.open.ac.uk/open_dataset/download&#39;">https://analyse.kmi.open.ac.uk/open_dataset/download&#39;</a><br># filename = wget.download(url)<br>zpf = zipfile.ZipFile(filename)<br>student_vle = pd.read_csv(zpf.open(&#39;studentVle.csv&#39;))<br>student_vle</pre><p>The output of this code, shown below, tells us that there are over 10 million rows of data. Each row represents one activity engaged at one time by one student. The data include module, presentation of the module, student id, activity id, date, and number of clicks the student made on the activity. As a note, the date column is days after the course start date. For a more complete description of the data, please <a href="https://analyse.kmi.open.ac.uk/open_dataset">visit the source</a>. The team there is great and does amazing work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9i9zktgYX4EVT8vkdWm_sg.png" /><figcaption>Image by Author</figcaption></figure><p>We can’t realistically look through every record; our brains would explode. Looping through 10 million records to collect statistics with a for loop would be be excruciatingly computationally expensive. Luckily, the geniuses who make Pandas have figured out some array magic to aggregate statistics ridiculously fast.</p><h3>Count Aggregator</h3><p>Let’s start with a count of the number of activities that each student engaged. We will groupby the student_id column. If you are visual like me, you might imagine the groupby method stacking all rows with a given number in the id_student column on top of each other to make that 3D table. When we call an aggregator method on the groupby object, each of those stacks flattens into whichever statistic we want. In this case we will use the .count() method.</p><pre>student_groups = student_vle.groupby(&#39;id_student&#39;)<br>activity_counts = student_groups.count()<br>activity_counts.head()</pre><p>In the output below you can see that id_student has become the index, and each of the original features is aggregated into a count of the number activity engagements are present in the dataset for each student.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*_8Eaj4pPSfmiJLqLNI402A.png" /><figcaption>Image by Author</figcaption></figure><p>If there is no missing data, the numbers across each row will all be the same. The .count() method returns counts in every one of the original columns, but methods like .mean() will only return numeric columns. The categorical ones will be missing from the resulting dataframe.</p><h3>Mean Average Aggregator</h3><p>We also wanted to know the average number of clicks students made per activity, So we will use the .mean() aggregator method to collect that statistic for each student. It will return the average value in the sum_click column, which corresponds to the average number of clicks each student made per activity, as well as some numbers we don’t care about.</p><pre>average_clicks = student_groups.mean()</pre><pre>print(&#39;Mean of median clicks per activity is&#39;,    <br>       average_clicks[&#39;sum_click&#39;].mean())</pre><pre>average_clicks.head()</pre><p>Notice that this time we don’t get back the module or the presentation columns because those are categorical. The mean of the dates and activity ids are not meaningful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*Q_mg6U2T3FjWrDaYjs7fdQ.png" /><figcaption>Image by Author</figcaption></figure><p>As you can see, the mean of the means of numbers of clicks per activity for these students is 3.2, and in the original dataset I see a lot of 1-click activities. I’m guessing a lot of these activities are links to outside resources.</p><p>Let’s bring our desired statistics together into one table with a pd.merge() call.</p><pre>activities_and_clicks = pd.merge(left=activity_counts[&#39;id_site&#39;], <br>                                 right=average_clicks[&#39;sum_click&#39;],<br>                                 how=&#39;inner&#39;,<br>                                 on=&#39;id_student&#39;)</pre><pre>cols = [&#39;Total Activities Engaged&#39;, &#39;Average Clicks per Activity&#39;]<br>activities_and_clicks.columns = cols</pre><pre>activities_and_clicks.head()</pre><p>We now have a table with one row for each student, a column describing how many activities that student engaged and another describing their average clicks per activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*Jj6gmweK-UhiO0VlqYmWMQ.png" /><figcaption>Image by Author</figcaption></figure><p>This table gives us statistics specific to each student.</p><h3>Other Groupings:</h3><p>Perhaps we want statistics for a module or a presentation. We can get those by changing the column we groupby. For instance:</p><pre>module_group = student_vle.groupby(&#39;code_module&#39;)<br>module_averages = module_group.mean()<br>module_counts = module_group.count()</pre><pre>modules = pd.merge(module_counts[&#39;id_site&#39;], <br>                                module_averages[&#39;sum_click&#39;],<br>                                how=&#39;inner&#39;,<br>                                on=&#39;code_module&#39;)</pre><pre>modules.columns = [&#39;Total Activities Engaged&#39;,&#39;Average Clicks per Activity&#39;]</pre><pre>modules</pre><p>This returns a table of activity counts and click averages <em>per module</em> rather than per student.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ZAQwcFIh3bUD-EiAtgKXcw.png" /><figcaption>Image by Author</figcaption></figure><p>Some modules average a lot more clicks than others. Why does module DDD require an average of 2 fewer clicks per activity than module FFF? Hmm…</p><h3>Multi-Indexing</h3><p>As we get to know our data better, we realize that we’ve made a mistake. We want to know the average clicks per student, but some students are in multiple classes simultaneously or take the same course multiple times.</p><p>What we really want, after our stakeholders clarify the original question above, is how many activities each student engaged and how many clicks they averaged on a <em>per course presentation </em>basis. In other words, we want statistics on each course registration, not each student. There may be multiple records for the same student if they repeat a module or take multiple modules. Above, we found out the stats on a per module basis and on a per student basis, but lets see how we can get statistics on a per course, per presentation, per student basis.</p><p>A little side note, creating multiple records for the same student violates the assumption that the observations are independent. Some kinds of analysis will need to take that into account for validity.</p><p>We will need to group the data by three different columns: code_module, code_presentation, and id_student. Luckily for us, the .groupby() method allows us to pass a list of columns to the by= argument. This will create a groupby object with another dimension for each column passed. Another way you can think about it the result is as a dataframe of dataframes of…times the number of columns you passed. The code below will create a five dimensional groupby object, then return the mean averages of each unique module presentation registration for the remaining features.</p><pre>cols = [&#39;id_student&#39;,&#39;code_presentation&#39;,&#39;code_module&#39;]<br>reg_groups = student_vle.groupby(cols)</pre><pre><br>reg_averages = reg_groups.mean()<br>reg_averages.head()</pre><p>The dataframe has three index columns: id_student, code_presentation, and code_module. The first is individual students, the second is the semester they attended a course, and the 3rd is the course they attended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*F9ceHTZwikIBYwoKNq-F4Q.png" /><figcaption>Image by Author</figcaption></figure><p>You can see that student 8462 took module DDD twice, once in October 2013 and once in October 2014. (The letters are the months, so J == 10th month.) Student 8462 averaged 2.15 clicks per activity the first time they took the course and 2.5 the second time. Did they work harder? engage different activities? Here’s an opportunity for deeper analysis, but outside the scope of our current task. Let’s put that in the icebox for later.</p><h3>Tuple Indices</h3><p>If we want to index into this multi-indexed dataframe to retrieve a specific datum, we need to use a tuple as the row indexer. If we want to know student 8462’s average clicks per activity during the October 2013 presentation of module DDD, we would index like so:</p><pre>reg_averages.loc[(8462,&#39;2013J&#39;,&#39;DDD&#39;), &#39;sum_click&#39;]</pre><p>This returns 2.15333, as we hoped.</p><p>We can also reverse the order of the list of columns we passed to the groupby method constructor to get a different ordering of the data. Let’s flip &#39;code_module&#39; and id_student and see how that changes the result.</p><pre>cols = [&#39;code_module&#39;,&#39;code_presentation&#39;,&#39;id_student&#39;]<br>groupby_module= student_vle.groupby(cols)</pre><pre>module_averages = groupby_module.mean()<br>module_averages.head()</pre><p>The above code groups the statistics first by the module, then by presentation, and finally by student. We get data for whole class lists organized by module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*mE3mFlN6m27ZbeUxXDEPjA.png" /><figcaption>Image by Author</figcaption></figure><p>If we want to see the data for Module BBB, presentation 2014B we would index like so:</p><pre>module_averages.loc[(&#39;BBB&#39;,&#39;2014B&#39;), &#39;sum_click&#39;]</pre><p>This returns a Pandas series containing the mean average clicks per activity for all the students in that cohort. There were almost 1300 students, but this is an online university so the classes are virtual, self-paced, and can be larger.</p><h3>Flattening a Multi-Index</h3><p>The last trick I wished I had known sooner was how to flatten a multi-index table into a single index one. It’s actually quite simple and intuitive…once you already know!</p><pre>flat_module_averages = module_averages.reset_index()<br>flat_module_averages.head()</pre><p>The above code restacks the rows into a 2D table, ordered the same way as the groupby object displayed. The groupby object indices become columns and a new index is added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*QMuUJMPK0AMQDckPYMMZzg.png" /><figcaption>Image by Author</figcaption></figure><p>Notice, this is not the same dataframe from the first time we grouped by just one column. In our first groupby object each student was one sample. When we used all three columns to group, then flattened, we now have average click statistics on a per module, per registration, per student basis.</p><h3>Summary</h3><p>In this tutorial you downloaded a table with 10 million rows of student/virtual learning environment interactions and used the Pandas .groupby() dataframe method to group the data in different ways. Finally, you use the aggregator methods .count() and .mean() to extract the number of activities each student engaged during a course and the average number of clicks per activity for each student and return them in a neat table. As a bonus, you learned how to flatten your multi-indexed dataframe back down to a single-index dataframe.</p><h3>Full Gist</h3><p>The below Gist brings together all of the skills you learned and returns a single-index table showing the number of activities and average clicks per activity for each student in each presentation of each module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ef221d858d5a608e446b0bf6ef6c574/href">https://medium.com/media/9ef221d858d5a608e446b0bf6ef6c574/href</a></iframe><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHo-rfvKTLMs5qZq5cxUnw.png" /><figcaption>Image by Author</figcaption></figure><h3>References:</h3><p>Kuzilek J., Hlosta M., Zdrahal Z. <a href="https://www.nature.com/articles/sdata2017171">Open University Learning Analytics dataset </a>Sci. Data 4:170171 doi: 10.1038/sdata.2017.171 (2017).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b3bce19c35e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/pandas-groupby-love-5b3bce19c35e">Pandas Groupby Love</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Online Learning Open Datasets]]></title>
            <link>https://medium.com/age-of-awareness/online-learning-open-datasets-df8cd3be9452?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/df8cd3be9452</guid>
            <category><![CDATA[online-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[learning-science]]></category>
            <category><![CDATA[learning-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 14:46:13 GMT</pubDate>
            <atom:updated>2021-03-02T16:43:02.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e1YP89qr99NS0d7J" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The opportunities for humans to contribute to the work of the world are changing rapidly. Businesses growing to take advantage of these opportunities need workers with new skills. Programmers, data scientists, web developers, and leadership positions are hiring, but there are not enough folks with the right skills to fill the need. This is true of many industries.</p><p>Education is expensive. Traditional teachers have to be multi-talented, high educated, passionate, and hard-working. Teaching and assessing are done manually and at considerable expense of time and money. However, we live in a magical age where data driven, accessible, personalized, and effective virtual education is possible. But how does an enterprise achieve those lofty goals? Data and data science are the answers</p><p>I jumped into the work of learning analytics with a <a href="https://github.com/Caellwyn/ou_student_predictions">project to predict course outcomes by online study patterns in user data</a> and had a hard time finding data on learning and learning platform interaction patterns. Fortunately I found <a href="https://analyse.kmi.open.ac.uk/open_dataset">this dataset from Open University</a> which has been a well-used source of study.</p><p>Traditional educational research is hard. Kids are squirrely and inconsistent. Classrooms are unique and external variables abound making controlled experimentation difficult. Group sizes are small and variables differ greatly between classrooms. The data is labor intensive to collect and often subjective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HQ_5GJpuLRmGOl4X" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Educational technologies and distance learning providers have opportunities for rigorous research with hard numbers on large samples of students. Every interaction with the computer can be tracked and anonymized to find correlations between product features, user behaviors and learning outcomes to iteratively redevelop course standards and interactive tools. The data is hypothetically available, and with many interactive cloud-based learning platforms being adopted by schools, the data may begin to span many years. Researchers can begin to model correlations between product features years ago to later outcomes, conducting cheaper longitudinal learning research.</p><p>If data is collected ethically and anonymously, according to <a href="https://www2.ed.gov/policy/gen/guid/fpco/ferpa/index.html">FERPA </a>guidelines, the community of online educational institutions have the opportunity to share research, data, and data drive practices for learning analytics and modeling.</p><p>Data from online learning gathered by online learning providers should be, as a norm, anonymized and provided as public datasets. These datasets can be a source of important and generalizable learning research by academic, professional, and amateur data scientists. Modern data science tools make data and analysis much more transparent than they used to be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jGQgwZvxRBvp9Qpf" /><figcaption>Photo by <a href="https://unsplash.com/@dose?utm_source=medium&amp;utm_medium=referral">Dose Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If marketable skills can be efficiently built in a diversity of learners, as is the mission of companies like Coursera and Udemy, we can re-employ millions of people into higher paying and highly needed jobs or business ventures.</p><p>Open source online learning datasets can be a source of important new research and advance the science of learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df8cd3be9452" width="1" height="1" alt=""><hr><p><a href="https://medium.com/age-of-awareness/online-learning-open-datasets-df8cd3be9452">Online Learning Open Datasets</a> was originally published in <a href="https://medium.com/age-of-awareness">Age of Awareness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keras Callbacks and How to Save Your Model from Overtraining]]></title>
            <link>https://medium.com/data-science/keras-callbacks-and-how-to-save-your-model-from-overtraining-244fc1de8608?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/244fc1de8608</guid>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 17:42:09 GMT</pubDate>
            <atom:updated>2021-06-24T16:42:24.972Z</atom:updated>
            <content:encoded><![CDATA[<h4>Callbacks allow you to adjust settings or save your model during training.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gs71Z1A7r6AxcmCm" /><figcaption>Photo by <a href="https://unsplash.com/@karsten116?utm_source=medium&amp;utm_medium=referral">Karsten Winegeart</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, you will learn how to use the ModelCheckpoint callback in Keras to save the best version of your model during training.</p><h3>Modeling is Fun!</h3><p>I love building predictive deep learning models. I love watching the training outputs, seeing the loss fall and watching for the diverging losses between training and validation sets that indicate overfitting. But sometimes a model finds a great solution…and keeps training to a solution that only works for the training set. Now, if I’m there, staring like it’s a fish tank, I can interrupt the training before too much damage is done. But, who wants to sit there and stare at models training all day? I mean, I do, but my time is better spent doing other work during long training sessions.</p><p>Then I learned about Keras callbacks, and specifically ModelCheckpoint!</p><h3>Overtraining</h3><p>Top athletes always ride the edge of over-training. The right about of training will optimize an athlete’s performance, but training too much leads to injury and reduced performance. Deep-learning models are similar. The right amount of training makes a strong model, but too much and performance can drop off on new data.</p><p>During training deep learning models seek to minimize their loss, to be more accurate according to a given loss function. However, they judge that accuracy on the set of data they are training on. Imagine a school-kid who takes a practice test home and memorizes every problem on it and every answer. If they haven’t found the underlying patterns, the strategies that the test is meant to assess, they will be at a loss because none of the questions on the practice test are on the exam!</p><p>Deep learning models can do that same thing. If they train too much on a dataset, they can learn that dataset specifically, rather than picking up the underlying functions connecting features and labels. The model can overfit the data.</p><p>There are many strategies to combat overfitting in predictive modeling, and those should be deployed as necessary, but overfitting from overtraining is a unique hazard.</p><p>Luckily, Keras has some help for us in the form of callbacks! Before I knew about callbacks I thought I had to guess the right number of training epochs, or use trial and error to tune them. Luckily, we don’t! We can use the Keras callback keras.callbacks.ModelCheckpoint() to save the model at its best performing epoch.</p><h3>Callbacks</h3><p>A callback is a function that can run after each epoch. It takes as arguments the epoch number and any metrics you have your model keeping track of. They can be used to do such useful things as scheduling reductions in the learning rate (I love a well-tuned decaying learning rate, don’t you?), early stopping of training, or saving the model between epochs. You can even code your own callback functions for your own special purposes.</p><p>If you want to know more about all of the available callbacks, check out the <a href="https://keras.io/api/callbacks/">Keras documentation here.</a></p><h3>ModelCheckpoint</h3><p>One of my favorite callbacks is ModelCheckpoint. I like to multi-task and often open a few Google Colab windows, set some deep models to train in them, and then work on other tasks on my local machine (I don’t have the GPU hardware to do efficient Tensorflow model training like Google does). I can set my models to train for a little longer than I think they might need and come back later to load them from the point before they began overfitting and losing accuracy on the validation set.</p><p>The ModelCheckpoint callback can be loaded from keras.callbacks</p><pre>from keras.callbacks import ModelCheckpoint</pre><p>We initialize the class object with the filepath to which to save, the conditions under which we want it saved, and how transparent the process should be. For example, let’s say we want only the very best version of the model and we define ‘best’ as the one with the lowest validation loss. You can choose as a trigger either your loss function or any of the metrics you passed to the metrics argument when you compiled the model.</p><p>We would initialize our callback like so:</p><pre>checkpoint = ModelCheckpoint(filepath=filepath, <br>                             monitor=’val_loss’,<br>                             verbose=1, <br>                             save_best_only=True,<br>                             mode=’min’)</pre><p>One cool trick for saving multiple times is to append the epoch number and/or current metric you are monitoring to the filepath, since the epoch will be passed to the ModelCheckpoint object.</p><pre>filepath = &#39;my_best_model.epoch{epoch:02d}-loss{val_loss:.2f}.hdf5&#39;</pre><p>The above will save your model to disk as something like:</p><p>my_best_model.epoch_01-loss_13.31.hdf5</p><h3>Back to Callbacks</h3><p>Keras models take a list of callbacks as an argument in the .fit() call. The argument expects a list, even if you are passing only one callback. However, you can deck your model out with all kinds of fancy callbacks. My favorite combo is ModelCheckpoint and ReduceLROnPlateau. The second one monitors a metric and reduces the learning rate by a given amount when that metric plateaus.</p><p>We pass our list of callbacks to the .fit() method like so:</p><pre>callbacks = [checkpoint, &lt;other_callbacks_you_want&gt;]<br>model.fit(X_train,<br>          y_train,<br>          epochs=epochs<br>          callbacks=callbacks)</pre><h4>Saving Models</h4><p>A note about saving models: models saved in .hdf5 format are great because the whole model is one place and can be loaded somewhere else, such as in deployment. However the files can get large, and saving your model at every epoch can get storage intensive fast. One option available in the ModelCheckpoint callback constructor is save_weights_only=True. This will save space, but will not save the entire model architecture. In order to recover it, you would rebuild the model and then assign the saved weights, rather than just loading it all in one step.</p><p>Another quirk I’ve found is that not every layer likes to be saved in .hdf5 format. In a previous blog post I showed you how to add a TextVectorization layer to a NLP model to do preprocessing as part of the model itself. However, I found that that I couldn’t save my model in .hdf5 format if I used that layer. However, if I leave off the .hdf5 extension, then keras saves the model as a file directory of assets, and this works for the TextVectorization layer.</p><p>After fitting, we can reload our model for evaluation at its best performing epoch with:</p><p>model = keras.models.load_model(filepath)</p><p>Let’s see it all in action!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5771992e79c4f2ed17aefa834b688870/href">https://medium.com/media/5771992e79c4f2ed17aefa834b688870/href</a></iframe><p>Data provided by Carnegie Mellon University via the Statlib library. Embedded Gist by author</p><p>I hope the ModelCheckpoint and the other callbacks that Keras provides and the ones you devise yourself will help you make the best predictive models!</p><h3>Summary</h3><p>In this article, you learned about callbacks for deep models using the Keras api for Tensorflow. Specifically, you learned how to use the ModelCheckpoint callback to save the best version of your model before it over-trains and a few ways to customize the callback.</p><p>As always, use your data science powers for good, and have lots of fun! Please leave any questions, comments, or kind and polite feedback in the comments.</p><p>Happy Modeling!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=244fc1de8608" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/keras-callbacks-and-how-to-save-your-model-from-overtraining-244fc1de8608">Keras Callbacks and How to Save Your Model from Overtraining</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pretrained Word Embeddings using SpaCy and Keras TextVectorization]]></title>
            <link>https://medium.com/data-science/pretrained-word-embeddings-using-spacy-and-keras-textvectorization-ef75ecd56360?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef75ecd56360</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spacy]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Sat, 06 Feb 2021 13:45:47 GMT</pubDate>
            <atom:updated>2021-02-06T14:35:00.238Z</atom:updated>
            <content:encoded><![CDATA[<p>Using <a href="https://spacy.io/">SpaCy </a>pre-trained embedding vectors for transfer learning in a Keras deep learning model. Also, bonus, how to use <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization">TextVectorization </a>to add a preprocessing layer to the your model to tokenize, vectorize, and pad inputs before the embedding layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFx5oGv8Y4ieW9wP" /><figcaption>Photo by <a href="https://unsplash.com/@alex_tsl?utm_source=medium&amp;utm_medium=referral">Alexandra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article you will learn how to use <a href="https://spacy.io/">SpaCy </a>embedding vectors to create a pre-trained embedding layer for natural language processing models in Keras. This reduces training time for NLP models and transfers learning about words and their relationships from larger models.</p><h3>Words</h3><p>Words make up most of the world most of us live in. If you are reading this, I would wager that you work with words most of your day, whether writing, reading, speaking, or hearing. I could be wrong, but this is true for many of us. As AI learns to interact with humans (to serve us, remember, always to serve us!) it must learn to understand our language.</p><p>Our language is made up of words. I dare you to imagine your life without words. Lamps are not lamps, the sky is not the sky, people don’t have names. I don’t even know how I would put a thought together without words! Words tie us to the world and give us symbols to manipulate that stand in for ideas we form about the world. The ‘tree’ is ‘falling’. There are billions of trees, but before we created a word for them, they were each unique. With the word ‘tree’ I can generalize to mean any tree. With the word ‘falling’, I can communicate to you something important to you. Move out of the way!</p><h3>Natural Language Processing</h3><p>Computers don’t think in words, like us, they think in numbers. Don’t get hung up on whether computers ‘think’; that’s not my point here. In order for computers to be able to use language for predictive models…or you might say ‘understand’ words, the words must be translated into numbers.</p><p>NLP researchers are clever and cross-disciplinary. They have to know about linguists and engineers, and they have developed several ways to turn words into numbers. This process is called ‘Vectorizing’, turning language into vectors (one dimensional arrays). Word embedding is one way to do this.</p><h3>My Project</h3><p>Let me tell you a little about the project I’m working on, so you can understand the choices I’m making in this article. I am building a regressor that estimates the appropriate grade level for a piece of student writing. By grade-level I don’t mean A,B,C,D,F. I mean Kindergarten, 1st grade, 2nd grade, etc.</p><p>Data collection for this project has been slow and my dataset is woefully small. However, my models have been surprisingly accurate with many estimating on average within 2 grade levels of the actual grade of the student. It’s a start. I included a link to my current data in the Gist below, but that dataset will grow (hopefully). For your own project you can probably find better data, so just adjust text = pd.read_csv(&lt;link here&gt;) to point to where your data is.</p><h3>Vectorizing and Embedding</h3><p>Computer models don’t understand words, only numbers. Our documents need to be transformed from strings to vectors.</p><p>There are several great strategies for turning a document into a vector. A count-vector describes a document by how many of which words are in it, and a TF-IDF vectorization uses a floating point number to describe how specific each word is to that document. Since my project is about writing style itself, rather than the content of the writing, however, I won’t use those. While they retain information about the vocabulary used in each document, those strategies toss out the order and relationships between the words.</p><h4>Embedding</h4><p>In word embedding, on the other hand, words are ‘embedded’ in n-dimensional space, where n in a developer defined value. Each dimension, represented by each position in the vector array, maps to some kind of relationship between words. If you consult the image below you can see 3D slices of the high dimensional embedding space highlighting particular word relationships. On the left, one dimension represents ‘binary gender’ and on the right another represents the relationship between countries and capitals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVosK7lBsmtDGt3JiM9WaQ.png" /><figcaption>Image from <a href="https://developers.google.com/machine-learning/crash-course/embeddings/translating-to-a-lower-dimensional-space">Google Machine Learning Crash Course</a></figcaption></figure><p>Word embeddings ideally preserve the semantic relationships between words and allow a deep learning model to consider a text in order. However there is another step involved.</p><h3><strong>Preparing the Data for Embedding: Tokenizing, Vectorizing, and Padding Sequences (in one step!):</strong></h3><p>Before our embedding layer can embed our words, we need to prepare them. Each document needs to be passed to the embedding layer as a vector integers of a fixed length.</p><h4>Tokenizing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WP1nVEZE6qQhc-m-" /><figcaption>Photo by <a href="https://unsplash.com/@sharonmccutcheon?utm_source=medium&amp;utm_medium=referral">Sharon McCutcheon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The first step of preparing text for modeling is tokenizing documents. In this step, words are isolated by transforming a text string with many words, like a sentence or a document, into a list of individual words.</p><p>When tokenizing:</p><p>&#39;A machine will never replace a teacher.&#39;</p><p>will be replaced with</p><p>[&#39;A&#39;, &#39;machine&#39;, &#39;will&#39;, &#39;never&#39;, &#39;replace&#39;, &#39;a&#39;, &#39;teacher.&#39;]</p><p>At this point it’s often useful to remove punctuation, make words lower case, remove common words like ‘the’ and ‘a’, and other text specific transformations like that will help the model focus on what is important. Each word will be treated differently by the model otherwise. It’s not always important that your model know the difference between ‘a’ and ‘an’, ‘Run’ and ‘run’, or ‘;’ and ‘:’. If they aren’t standardized at this point they can be distractions to the model later and increase computational load.</p><p>Since I want to include grammatical information in my model’s input vectors, I don’t want to remove stopwords or lemmatize words. My model needs to know how students are using words and which forms of the words they use.</p><h4>Vectorizing</h4><p>Next, the tokenized words need to be encoded as integers. When the coded sequences are passed to the embedding layer, they will be used as indices to look up the proper embedding for the word in the embedding layer.</p><p>What I want in this step is for:</p><p>[&#39;a&#39;, &#39;machine&#39;, &#39;will&#39;, &#39;never&#39;, &#39;replace&#39;, &#39;a&#39; &#39;teacher&#39;]</p><p>to be replaced with something like:</p><p>[2, 427, 34, 67, 89, 2, 245]</p><p>An interesting point here is that the embedding layer will actually add a dimension to the vector representing a document. Imagine each integer ‘word’ in the input sequence, the encoded document, grows a tail out to the side which represents that word’s embedding vector. So, it’s a vector of vectors, a matrix.</p><h4>Padding Sequences</h4><p>All inputs to most kinds of models must have the same shape, but the documents in our corpus are of varying lengths. As the AI engineer, you need decide the length of sequence you want to use to represent your documents. It might be the max document length, or the average document length, or some other choice that makes sense for your use case. My student texts not terribly long, so I’ll use the max document length for my sequences. If the length of the vectorized sequences is smaller than your longest document, this layer will truncate documents that are too long to fit. For documents shorter than the sequence length, the layer will pad the empty space with 0s. 0 is a special reserved code for ‘no word’.</p><p>Let’s say I set the sequence length to 15. Since our document example from above is only 7 words,</p><p>&#39;A machine will never replace a teacher&#39;</p><p>it will be encoded and padded to become:</p><p>[2, 427, 34, 67, 89, 2, 245, 0, 0, 0, 0, 0, 0, 0, 0]</p><p>We could actually stop right there and this would be a perfectly feasible way to vectorize our documents to hand off to the model. No further embedding layer is technically needed. Many NLP problems can be solved just by passing these padded sequences. However, I want to embed pretrained semantic relationships between words to help my model better consider the meanings of the words.</p><h4>Keras TextVectorization layer</h4><p>Keras has an experimental text preprocessing layer than can be placed before an embedding layer. In total, it allows documents of various sizes to be passed to the model. The <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization">TextVectorization </a>layer will tokenize, vectorize, and pad sequences representing those documents to be passed to the embedding layer. It can also be used as an integer index to tell the embedding layer which integer encoded words represent which embedding vectors.</p><p>Often more extensive preprocessing is desired, such as lemmatizing, stemming, parts-of-speech tagging, and more. If I wanted to do more preprocessing than described above, I would use the Natural Language Tool Kit or <a href="https://www.nltk.org/">NLTK </a>package. After all, the real art of NLP is in the preprocessing.</p><p>But for our purposes, the services offered by <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization">TextVectorization </a>is enough.</p><h3>Embedding Layers</h3><h4>Trainable Embeddings</h4><p>Now that our text is stored in padded sequences of word indices, it’s ready to pass to an embedding layer. Embedding can layers learn the relationships between words in your document corpus through the same learning algorithm as the rest of your model. They are often the work horses of an deep NLP model and can have millions of weights (vocabulary length* embedding vector length).</p><h4><strong>Transferring Embeddings</strong></h4><p>But…why should we do the work of training an embedding layer? In fact there are several high powered embedding dictionaries already out there. <a href="https://www.tensorflow.org/tutorials/text/word2vec">Word2Vec</a>, <a href="https://nlp.stanford.edu/projects/glove/">GloVe</a>, and <a href="https://spacy.io/">SpaCy </a>are some to consider. These have been trained on computers bigger than we have and over more time than we are likely willing to devote. The question here is what kind of semantic representation do you want your embedding matrix to represent? Do you want the embeddings to be specific to your corpus, or is it okay if they are more general to the language at large? Also consider the time and computational resources you have for training.</p><p>If you can handle or would benefit from more general embeddings, pre-trained embeddings will reduce your training time dramatically. Each is, at its heart, a dictionary of words to vectors. The size of that dictionary depends on how many words you want available for embedding and how long of embeddings vectors you want. The largest <a href="https://nlp.stanford.edu/projects/glove/">GloVe </a>dictionary, trained by geniuses at Stanford on obscene computers over years, is almost a gigabyte.</p><h4>Transforming the Embedding Dictionary to an Embedding Layer</h4><p>If you want to use someone else’s trained embeddings in your model, you’ll need to create a mapping from the word indices the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization">TextVectorizer </a>layer uses to encode your vocabulary to the word embedding vectors from your embedding dictionary.</p><p>The embedding layer will look at the index integer for each word in the passed by the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization">TextVectorizer</a>, use that to look up the embedding, then pass the embeddings of each word in the input sequence to the next layer. The index position of each word in the vocabulary list returned by TextVectorizer.get_vocabulary() is also the encoding that the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization">TextVectorizer </a>will return for each word. We will next create the weights matrix we will use to initialize the embedding layer. We do this by looping over the words in the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization">TextVectorizer </a>vocabulary and the embedding dictionary. Each word encoding from the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization">TextVectorizer </a>will be a row index in the weights matrix and the vector accessed for that word will be the one from the embedding dictionary we chose.</p><p>I’ll be using <a href="https://spacy.io/">SpaCy </a>because the embeddings load much faster than the <a href="https://nlp.stanford.edu/projects/glove/">GloVe </a>ones. The code will look like:</p><p>for i, word in enumerate(vectorizer.get_vocabulary()):<br> embedding_matrix[i] = embedding_dictionary[word]</p><p>You’ll set these weights to be untrainable to reduce computational load.</p><h3><a href="https://spacy.io/">SpaCy</a></h3><p>Spacy is awesome!! There is so much it can do, from lemmatizing and embedding to creating parts-of-speech tags for words and syntactic trees for sentences. I’m just using its trained word embeddings here, but it does much more. For another project, for instance, I might use sentence level embedding vectors (an average of the word vectors) using <a href="https://spacy.io/">SpaCy’s </a>built in methods. Definitely check out what <a href="https://spacy.io/">SpaCy </a>can do for your NLP project!</p><p>Here is the full code to take you from zero to predicting student grade levels (with medium success).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b772988e1f6d1f27df0444813de7f2f/href">https://medium.com/media/5b772988e1f6d1f27df0444813de7f2f/href</a></iframe><h3>Bias</h3><p>This is a bit of an aside, but I think an important one. We talked about how a word’s embedding defines its relationship to other words as a sort of stand in for conceptualization. Well, researchers have found that NLP models tend to get racist and/or sexist because racism and sexism are embedded in our language and how we use it. The really fascinating thing about that bias is that it can be quantified! Skilled modelers can find the dimension of that racism and flatten it, effectively reducing the dimensionality of the embedding vector. This helps removes the biased word relationships in the embedding space. In fact, ethically, this is something every developer of a chatbot should look into.</p><p>Jerry Wei talks more about this in their article: <a href="https://towardsdatascience.com/bias-in-natural-language-processing-nlp-a-dangerous-but-fixable-problem-7d01a12cf0f7">Bias in Natural Language Processing (NLP): A Dangerous But Fixable Problem</a></p><h3>Summary:</h3><p>In this article you learned how to use <a href="https://spacy.io/">SpaCy </a>and <a href="https://keras.io/">Keras </a>to build an natural language processing model with a text vectorizing layer and a pre-trained embedding layer. You also got to see a snippet of my project to teach a model to read student writing as a Github Gist to get you started on your own NLP projects</p><p>Please enjoy the above Gist, and use it as a jumping off point for your own projects. My NLP project is not complete, so I’m not going to link it you, but if you are clever you can find it yourself with the hints I’ve provided here.</p><p>As always, please let me know what you think, how this inspires you, and any questions or comments you have. Happy modeling!</p><h3>Further Learning:</h3><p><strong>Why you should use embedding layers for more than NLP:<br></strong><a href="https://towardsdatascience.com/deep-learning-4-embedding-layers-f9a02d55ac12">https://towardsdatascience.com/deep-learning-4-embedding-layers-f9a02d55ac12</a></p><p><strong>How to get more out of NLTK:<br></strong><a href="https://www.guru99.com/nltk-tutorial.html">https://www.guru99.com/nltk-tutorial.html</a></p><p><strong>The magic of SpaCy:<br></strong><a href="https://realpython.com/natural-language-processing-spacy-python/">https://realpython.com/natural-language-processing-spacy-python/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef75ecd56360" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/pretrained-word-embeddings-using-spacy-and-keras-textvectorization-ef75ecd56360">Pretrained Word Embeddings using SpaCy and Keras TextVectorization</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplified Forecasting with Facebook Prophet]]></title>
            <link>https://medium.com/data-science/simplified-forecasting-with-facebook-prophet-d5789d32acdf?source=rss-6fad8f551b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5789d32acdf</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[facebook-prophet]]></category>
            <dc:creator><![CDATA[Josh Johnson]]></dc:creator>
            <pubDate>Wed, 27 Jan 2021 12:20:42 GMT</pubDate>
            <atom:updated>2022-05-19T01:41:27.233Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with forecasting quickly with the fbprophet library</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u2UXkJzWsrOIe24M" /><figcaption>Photo by <a href="https://unsplash.com/@drew_beamer?utm_source=medium&amp;utm_medium=referral">Drew Beamer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Facebook Prophet?</h3><h4>The Challenges of Timeseries Forecasting</h4><p>Timeseries forecasting is a complex art form. Many models are very sensitive to trends, cycles (called ‘seasons’) and changing magnitudes of fluctuations, and instead require stationary data, which lack these features.</p><p>A good example of data that not-stationary is the cumulative spread of COVID-19 in the United States over the year 2020. For this project I will be using data from the Coronavirus Government Response Tracker, which provides daily updated data on every country, including government interventions. If you want to take your forecasting further by including exogenous variables (variables outside of the data being modeled that may have an effect on it) you can find many relevant ones in this dataset. However, for this example we will only be using cumulative reported infections in the United States.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lACs-biLbjpVBWJDef3FA.png" /></figure><p>You can see above that not only is there an upward trend, but the trend keeps changing. The seasonality is not apparent from the cumulative data, but when we do a first order differencing to transform cumulative cases to daily new cases, we see the seasonality appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlpWj9PmMcfo5ys2N-LhRQ.png" /><figcaption>Image by Author</figcaption></figure><p>The weekly seasonality is probably because:</p><ol><li>People tend to get tested on weekends and their results tend to come back on Wednesdays, creating a peak of reported cases on Wednesdays and valleys on other days. Or,</li><li>Labs report cases in bulk on certain days.</li></ol><p>Notice the dips on 12–07, 12–14, 12–21, etc. There are also a large dips on 12–25 and 01–01. I assume not many lab workers were working on Christmas and New Year’s day, so reports dipped.</p><p>We must keep in mind that data is not reality, and cases charted are actually cases reported, not actual infections. The patterns of reporting create the seasonality in the data.</p><h4>The ARMA Family of Models</h4><p>An ARMA model is a combination of an autoregressive and a moving average model, and a crucial tool in predicting stationary time series data. I won’t explain it fully here, since this post is about a different technique, but you can read about it <a href="https://en.wikipedia.org/wiki/Autoregressive%E2%80%93moving-average_model">here</a>.</p><p>Extensions to the ARMA model, such as ARIMA can account for trends and SARIMA can take into account the seasonality of data. However, the accuracy of these models require carefully tuning several hyperparameters to determine how and to what degree past data effects the future. data scientists often make a series of transforms on the data, such as subtracting moving averages or standard deviations, or log scaling it to get good predictions. With enough effort and expertise these are powerful models.</p><p>With effort and thorough data exploration I tuned mine to predict cases in the first 18 days of January at 99% accuracy. You can experience my adventures in SARIMA modeling through my <a href="https://github.com/Violet-Spiral/covid-xprize/blob/main/models/sarima_models.ipynb">Github repo predicting COVID case rates.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L883xnncdQMkIOjEL62wUg.png" /><figcaption>A prediction of cumulative COVID-19 cases in January 2021 using a SARIMA model trained on data only from 2020 compared with actual cumulative cases during that period. Image by Author</figcaption></figure><h3>Making A Simple Forecast with Facebook Prophet</h3><p>The Facebook Prophet library for R and Python does a lot of that work for you. It allows for quick and easy time series forecasts, but also provides options for more seasoned forecasters to tune the internal settings. It can detect and adjust to seasonality, trends and shifting standard deviations in the residuals. However, it is particular about how you implement it. Let’s see how to get started.</p><h4>Loading fbprophet and Preparing the Data</h4><p>We can easily install Prophet into Google Colab notebooks with !pip install fbprophet.</p><p>On my local Windows machine running the Anaconda package manager, I installed it using a bash terminal with conda install -c conda-forge fbprophet. Facebook has more<a href="https://facebook.github.io/prophet/docs/installation.html"> guidance on installation here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba0521e2a154c896df8d0f14b655feda/href">https://medium.com/media/ba0521e2a154c896df8d0f14b655feda/href</a></iframe><p>You may notice that the last line renames the ‘Date’ columns to ‘ds’ and the ‘CumulativeCases’ column to ‘y’. This is required by Facebook in order to use the dataframe for modeling. Many experienced Pandas users may be tempted to make the datetime column the index, but for Prophet,<strong> don’t do that.</strong></p><h4>Forecasting with Prophet</h4><p>Our dataframe is ready for modeling. Creating and training the out-of-the-box model is very simple:</p><p>m = Prophet()<br>m.fit(df)</p><p>But, here is the tricky part. You have to prepare a special dataframe to store the actual prediction. Luckily the model comes with a handy method to do it for you.</p><p>future = m.make_future_dataframe(periods=length_of_desired_forecast)</p><p>Finally, to make the prediction, simply feed the future dataframe as an argument to the the model’s .predict() method, like so:</p><p>forecast = m.predict(future)</p><p>I love the variable name conventions that the folks at Facebook have created, where the model predicts the future to make forecast. It’s satisfying and just the right amount of on the nose for me.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cdcb2b7bde0c6fa96b22d8275f73d53/href">https://medium.com/media/4cdcb2b7bde0c6fa96b22d8275f73d53/href</a></iframe><p>forecast will be a dataframe that contains your prediction, out to the end of the ‘ds’ column in your future dataframe. It includes confidence intervals and all the parameters the model used for each step of the prediction. This allows some lovely inspection the internal workings of the model and opportunity to do some fun graphs with confidence bands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*IyEudtu9MhCB42acHVt7fA.png" /><figcaption>Image by Author</figcaption></figure><p>As you can see above, this out of the box Prophet model has made a very basic linear regression as a prediction. Further tuning of the model will improve the accuracy. If you run the code you will see warnings that indicate the Prophet has automatically identified weekly seasonality in the data, but that you can manually tell it to look for monthly or yearly seasonality. There are a number of other tweaks and refinements you can try including adding extra (exogenous) variables, such as holidays or the government interventions provided in the dataset we used.</p><p>A much more comprehensive guide can by found in this awesome <a href="https://towardsdatascience.com/forecasting-in-python-with-facebook-prophet-29810eb57e66">article by Greg Rafferty</a>. But, the above should get you off the ground and give you something to get started with.</p><p>If you want to see my full work on trying to predict COVID-19 cases for an Xprize competition, <a href="https://github.com/Violet-Spiral/covid-xprize">you can check it out here:</a><br>(Spoiler, I ended up going with a more accurate SARIMA model)</p><h4><strong>References</strong>:</h4><p><a href="https://facebook.github.io/prophet/docs/quick_start.html">Facebook Prophet Quickstart Guide</a></p><p><a href="https://towardsdatascience.com/forecasting-in-python-with-facebook-prophet-29810eb57e66">Forecasting in Python with Facebook Prophet</a> by Greg Rafferty</p><p><strong>Data:</strong></p><p><a href="https://www.bsg.ox.ac.uk/research/research-projects/coronavirus-government-response-tracker">Coronavirus Government Response Tracker</a><br>Thanks to the Blavatnic School of Government and the University of Oxford</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5789d32acdf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/simplified-forecasting-with-facebook-prophet-d5789d32acdf">Simplified Forecasting with Facebook Prophet</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>