<?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 Andrés Berejnoi on Medium]]></title>
        <description><![CDATA[Stories by Andrés Berejnoi on Medium]]></description>
        <link>https://medium.com/@andresberejnoi?source=rss-70883f107800------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_NJbbkkqyuzcWPda4Brang.png</url>
            <title>Stories by Andrés Berejnoi on Medium</title>
            <link>https://medium.com/@andresberejnoi?source=rss-70883f107800------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:43:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andresberejnoi/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[Amazon Prime Day Deals for Book Lovers — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/amazon-prime-day-deals-for-book-lovers-andres-berejnoi-96a9c4bedf0d?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/96a9c4bedf0d</guid>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[deals-and-discounts]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[amazon-prime]]></category>
            <category><![CDATA[kindle]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 19:52:20 GMT</pubDate>
            <atom:updated>2024-07-15T20:02:38.052Z</atom:updated>
            <content:encoded><![CDATA[<h3>Amazon Prime Day Deals for Book Lovers — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IqGimj9TjlUzFwz3.jpg" /></figure><p>Amazon Prime Day is only one day away (from July 16–17) so I wanted to briefly share some deals I found, particularly for those who enjoy reading books, e-books, audio books, etc. Keep in mind that there will still be new deals on the days after Amazon Prime day. The links I share in this post may be affiliate links and therefore I might earn a commission if you end up purchasing something through that link, although the price for you won’t change, and it is a way to support this blog.</p><p>If you are interested in my reading lists, you can take a look at past posts with <a href="https://andresberejnoi.com/blog/category/reading-list/">some book recommendations</a>.</p><h3>What do you need to take advantage of these deals?</h3><p>As the name indicates, you need an <a href="https://amzn.to/4d0zBej">Amazon Prime subscription</a> to access the discounts available. If you follow my link, you might be eligible for a 30-day trial. Otherwise, it costs $14.99 a month. Since you only need the subscription for the next few days, I think getting the subscription just for one month is sufficient, but make sure to cancel auto-renewal if you want to go that route.</p><h3>Two Free E-books For July</h3><p>I recently found out Amazon has a free subscription program called “ <a href="https://amzn.to/4d53Voh">Amazon First Reads</a> “. Amazon selects 10 new e-books every month to recommend. Moreover, if you have a Prime subscription, you can choose one of them every month. The book is yours to keep, even if you stop your Amazon Prime subscription. And, on top of that, it seems that for the month of July, they increased the offer for Prime members. Now members can choose two e-books from the selection and keep them. I think this is a great way to get exposed to new books you might otherwise not find out about.</p><h3>Discounts on Kindle E-Readers and 3 Months of Free Kindle Unlimited</h3><p>I have been looking forward to Amazon Prime day specifically to buy a new e-reader. The most exciting deal from Amazon Kindle e-readers is the <a href="https://amzn.to/4f4nTRJ">Kindle Scribe</a>. The Scribe is Amazon’s largest reading tablet, with a screen at 10.3&quot;. Another important feature is the inclusion of a pen that you can use to take digital notes on the Scribe. Normally, it costs $369.99 but right now it is already discounted ahead of Prime day to $259.99, so a $110 discount. This version comes with a premium pen. You can also get the version with the basic pen for about $25 less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*uV6VKfLmaIN0hHJs" /><figcaption>Kindle Scribe | Amazon Store</figcaption></figure><p>If you were thinking about buying a new e-reader in the near future, this might be the perfect chance. In case the big screen or the pen does not interest you, I think the next best option is the <a href="https://amzn.to/4cGcBBs">Kindle Paperwhite Signature Edition</a>.</p><p>Another deal that comes with purchasing an Amazon e-reader is a free three-month subscription to Kindle Unlimited. It has a large catalog of e-books and audio books you can read without buying them. Just make sure you select the “Kindle Unlimited” option when you are purchasing the tablet and to cancel it after the three months are over, unless you want to keep it and pay full price.</p><h3>Other Reading Tablets</h3><p>Even though there is a massive discount on the <a href="https://amzn.to/4bFlY33">Kindle Scribe</a>, there is another e-reader that I’m deciding on. It is the <a href="https://amzn.to/4d2Qx3M">Kobo Libra Colour</a> (selling for $219.99). It is not on discount and has a different ecosystem than that of Amazon, but it has features I like. For one, the Libra Colour has a color screen, which makes it great to read comics and view book covers in color. I do wish the screen were a little bigger but at 7&quot; it will be sufficient for most reading use-cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*wJlv3dhT8nYWhuwl" /><figcaption>Kobo Libra Colour | Amazon Store</figcaption></figure><p>Both the Kindle Scribe and Libra Colour support a pen to take notes. The pen for the Libra Colour is sold separately but I read you can use third party ones, like the ones for Microsoft Surface tablets (don’t quote me on that).</p><h3>Conclusion</h3><p>I wanted to make a quick post so that more people can take advantage of these deals. Some of them have been active for a few days, and many more will become active starting tomorrow. I think paying for a month of Amazon Prime to access the deals is a good tradeoff in this case.</p><p>If you have a book recommendation, I would be happy to hear it. Let me know in the comments.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/blog/amazon-prime-day-deals-for-book-lovers/"><em>https://andresberejnoi.com</em></a><em> on July 15, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96a9c4bedf0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build A Simple Data Science App With Streamlit — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/build-a-simple-data-science-app-with-streamlit-andres-berejnoi-cc56e21f9b13?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc56e21f9b13</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[data-dashboard]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 20:48:21 GMT</pubDate>
            <atom:updated>2024-01-27T21:45:28.653Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build A Simple Data Science App With Streamlit — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cwxg4yMOtWopuMoF.jpg" /></figure><p>In today’s post, we will cover the basics of the web framework I am especially interested in Streamlit’s focus on data science applications. Therefore, we will build a simple web app with some data visualization on a housing price dataset. Read until the end to see a working example. At the same time, I want to see how it compares to Flask in ease of use and flexibility. I previously wrote these posts on building a web app with Flask and a MySQL databse, so they will serve as a comparison:</p><ul><li><a href="https://andresberejnoi.com/blog/building-a-simple-flask-app-with-sqlalchemy/">https://andresberejnoi.com/blog/building-a-simple-flask-app-with-sqlalchemy/</a></li><li><a href="https://andresberejnoi.com/blog/how-to-use-sqlalchemy-and-python-to-read-and-write-to-your-database/">https://andresberejnoi.com/blog/how-to-use-sqlalchemy-and-python-to-read-and-write-to-your-database/</a></li></ul><p>There might be referral links to books I used or recommend on this topic below.</p><h3>Project Scope</h3><p>For this project, we will create a simple multi-page app that displays information on California’s housing data, such as the raw dataframe, and a map of the population clusters used in the dataset. By the way, I borrowed this dataset from the third edition of the book “<a href="https://amzn.to/49eFeUz"><strong>Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow</strong></a><strong>”</strong> by Aurélien Géron. I recommend checking it out if you are interested in improving your machine learning skills. Additionally, here are two potentially interesting books on developing and deploying Streamlit apps (I have not personally read them yet):</p><ul><li><a href="https://amzn.to/3vKu4s1">Streamlit for Data Science: Create interactive data apps in Python</a></li><li><a href="https://amzn.to/3Oh8ku2">Getting Started with Streamlit for Data Science: Create and deploy Streamlit web applications from scratch in Python</a></li></ul><p>I deployed the app for today’s project on Streamlit Community site for free, and you can take a look at it <a href="https://sample-data-visualization-andresberejnoi.streamlit.app/">here</a>.</p><h3>How To Install Streamlit</h3><p>You can find <a href="https://docs.streamlit.io/get-started/installation">installation instructions</a> on Streamlit’s documentation page, but basically, the two easiest methods are using pip and conda:</p><ul><li>Note: I highly recommend creating a virtual environment before installing Streamlit.</li><li>With pip</li></ul><pre>#this method is the recommended one on the documentation page <br>pip install streamlit</pre><ul><li>With Conda</li></ul><pre>conda install -c conda-forge::streamlit</pre><h3>Loading the Data And Displaying It</h3><p>Streamlit makes it really easy to quickly show data. For any Streamlit project, we need an entry-point Python file. We will call it “Home.py”. Keep in mind that the file name will be automatically used as the page name; that’s why I capitalized it.</p><p>In our “Home.py” file, we can load the data as a pandas dataframe and it will be displayed on the page.</p><pre>import streamlit as st<br>import pandas as pd<br> <br>df = pd.read_csv(&quot;datasets/housing.csv&quot;)<br>st.markdown(&quot;#Raw Housing Data&quot;)<br> <br>df</pre><p>Then from the terminal, in the same folder as the project, we run the app:</p><pre>streamlit run Home.py</pre><p>Now we should see a URL on the terminal where we can find the app. The website should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*h6YQbYn4ooykFGDQ" /></figure><p>Notice that we didn’t explicitly tell Streamlit to display the dataframe on the page. It happens automatically when a variable name is typed without any other expression.</p><p>Personally, I prefer to explicitly tell Streamlit how to display my data. For instance, we can use st.dataframe to display an interactive dataframe, or st.data_editor(df) to be able to modify entries in the dataframe:</p><pre>import streamlit as st<br>import pandas as pd <br> <br>df = pd.read_csv(&#39;datasets/housing.csv&#39;)<br> <br>st.markdown(&quot;# Raw Housing Data&quot;)<br>st.data_editor(<br>    df, <br>    num_rows=&#39;dynamic&#39;, #allows deleting entire rows<br>)</pre><h3>Adding A Map With Streamlit.map</h3><p>One neat feature of Streamlit is its built-in API for displaying data on a map using . It uses <a href="https://mapbox.com/">Mapbox</a> under the hood. The Streamlit documentation mentions that Mapbox requires an API token to use. However, Streamlit is providing their own token so we don’t have to worry about it (this may change in the future). If you encounter issues where the map is not displayed, you may need to create your own token and configure Streamlit to use it; just follow the st.map documentation above.</p><p>The code to add a map is surprisingly simple:</p><pre>#display a simple map<br>st.map(<br>    df, <br>    longitude=&#39;longitude&#39;, <br>    latitude=&#39;latitude&#39;, <br>    size=&#39;population&#39;,<br>    #color=&#39;population&#39;, <br>)</pre><p>As you can see, expects a dataframe or similar data structure as the first argument. This dataframe should contain columns with latitude and longitude values. Conveniently, st.map also supports passing <em>size</em> and <em>color</em> columns. <em>Size</em> controls the size of each data point plotted on the map. <em>Color,</em> as the name indicates, controls the color of the points. We can pass a single color for the entire dataset, or we can provide a different color for each point on the map by providing a list of colors or the name of a column in the dataframe containing color hex values.</p><p>In the example above, I used the “population” column from the dataframe as the size.</p><p>Here is an overlook of the map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*WDNqGO4LkEu-1YkM" /></figure><p>When we zoom in the map, we can see that the dots vary in size based on the population value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*4XZO53ddhBhHp45n" /></figure><h3>Adding More Pages to Streamlit App</h3><p>So far, we have created a single page for our app. To add more, Streamlit expects a folder called “pages” at the same level as our entry script. We will put all of the sub-pages under this folder and they will show up in the sidebar of our Streamlit application in alphabetical order. For instance, let’s add an information page with useful links and another page with a form that counts the word frequency in the text entered. Here is the project structure now:</p><pre>your-root-folder/<br>|---- Home.py<br>|---- pages/<br>|     |---- Info.py<br>|     |---- Word_Counter.py</pre><p>Streamlit will automatically show Info.py first since pages are sorted alphabetically. However, there are ways to force a certain order. The simplest is to add a number followed by an underscore in front of the file name. Additionally, you can even add emojis directly to the file name. Take a look at both of these examples:</p><pre>your-root-folder/<br>|---- Home.py<br>|---- pages/<br>|     |---- 1_Info.py<br>|     |---- 2_Word_Counter.py</pre><p>and</p><pre>your-root-folder/<br>|---- Home.py<br>|---- pages/<br>|     |---- ℹ️_Info.py<br>|     |---- 📝_Word_Counter.py</pre><p>When you look again at your running app, you should see a side bar like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*fDs4a3ZsQAKt5f0Z" /></figure><p>Now, lets actually fill those pages with interesting stuff.</p><h3>ℹ️_Info.py</h3><p>In this page I will simply add some links to my post, my <a href="https://github.com/andresberejnoi/Streamlit-Apps">Github repository</a>, and some Streamlit documentation pages used for the project.</p><p>Here is the code:</p><pre>import streamlit as st <br> <br>st.title(&quot;Project Information&quot;)<br> <br>st.markdown(&quot;This is an example project to show the basics of Streamlit.&quot;)<br>st.markdown(&quot;Here is a [blog post](https://andresberejnoi.com/blog/build-a-simple-data-science-app-with-streamlit/) explaining how this page was made. Additionally, here is the link to the [Github repository](&lt;https://github.com/andresberejnoi/Streamlit-Apps/tree/main/Housing%20Prices&gt;) for the project.&quot;)<br> <br>st.markdown(&quot;&quot;&quot;<br>    ### Streamlit Elements Used:<br>* [st.data_editor](&lt;https://docs.streamlit.io/library/api-reference/data/st.data_editor&gt;)<br>* [st.map](&lt;https://docs.streamlit.io/library/api-reference/charts/st.map&gt;)<br>* [st.form](&lt;https://docs.streamlit.io/library/api-reference/control-flow/st.form&gt;)<br>* [st.text_area](&lt;https://docs.streamlit.io/library/api-reference/widgets/st.text_area&gt;)<br>&quot;&quot;&quot;)</pre><h3>📝_Word_Counter.py</h3><p>For this page, I decided to have some fun and add a simple text submission form using <a href="https://docs.streamlit.io/library/api-reference/control-flow/st.form">Streamlit’s </a><a href="https://docs.streamlit.io/library/api-reference/control-flow/st.form">form</a> component. If you type something into the text box and click submit, the app will tell you how many words were in the text and display the 15 most used words as a bar chart.</p><p>The code for st.form is very intuitive. You can add elements to a form by using Python&#39;s with statement. Here is my code for this page:</p><pre>import streamlit as st <br>from collections import Counter<br> <br>with st.form(&quot;counter_form&quot;):<br>    st.title(&quot;Word Counter Form&quot;)<br>    txt = st.text_area(&quot;Leave a message below:&quot;)<br> <br>    submitted = st.form_submit_button(&quot;Submit&quot;)   #every form must contain st.form_submit_button<br>    if submitted:  #do something with the data entered<br>        num_words = len(txt.split())<br>        st.write(&quot;You pressed the `Submit` button.&quot;)<br>        st.write(f&quot;Your text has {num_words} words.&quot;)<br> <br>        if num_words &gt; 0:<br>            st.write(f&quot;Here is a frequency count of the top 15 words:&quot;)<br>            words = txt.split()<br>            word_frequency = Counter(words)<br>            top_15_words = word_frequency.most_common()[:15]<br> <br>            st.bar_chart(dict(top_15_words))</pre><p>Now if you go to the word counter sub-page and enter some text in the input area, you should get an output like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*1Dd5V4b6fn2sN4oh" /></figure><h3>Conclusions</h3><p>Streamlit is much easier to use out of the box than something like Flask. I was able to build a simple application in a matter of minutes just with some help from the documentation. Therefore, I will keep exploring this tool and building real projects with it. I also enjoyed the fact that you can deploy Streamlit apps for free on the community page with just the click of a button. That’s how I deployed the example in this post.</p><p>As always, let me know if you have any questions or comments down below.</p><p>You can also subscribe to my YouTube channel for videos on Python projects, automation, and more:</p><ul><li><a href="https://www.youtube.com/andresberejnoi">https://www.youtube.com/andresberejnoi</a></li></ul><p>Finally, if you want to stay connected and up to date on what I post, you can join my <a href="https://andresberejnoi.com/newsletter-landing-page/">newsletter here</a>. I want this newsletter to be a useful resource of tips and tricks I learn and also a place to talk about new projects I might work on.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/blog/build-a-simple-data-science-app-with-streamlit/"><em>https://andresberejnoi.com</em></a><em> on January 26, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc56e21f9b13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization: Bar Chart Animations With Manim — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/data-visualization-bar-chart-animations-with-manim-andres-berejnoi-75ece91a2da4?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ece91a2da4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bar-chart-race]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[manim]]></category>
            <category><![CDATA[bar-chart]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 01:00:36 GMT</pubDate>
            <atom:updated>2023-09-20T01:19:33.799Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Visualization: Bar Chart Animations With Manim — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VUAJ_9ZrZPhrM8CK.png" /></figure><p>A few weeks ago, I covered how to install and get started <a href="https://andresberejnoi.com/using-manim-and-python-to-create-animations-like-3blue1brown/">with Manim and Python</a> in a blog post and also made a <a href="https://youtu.be/Q2D3LDJsfyA">YouTube video</a> about it:</p><p>In today’s post, I want to expand on Manim and show how we can use it to create bar chart animations.</p><p>Previously, I made a <a href="https://youtu.be/9hqGRehzEsI">YouTube video</a> about animating bar charts with Python and a library based on Matplotlib. I modified the library to place images on each bar chart but it always felt a bit hacky. As such, this is an opportunity to revisit that video and create more pleasing data visualization animations.</p><h3>Taking a Look At the Data</h3><p>As in my previous bar chart video, I’ll be using a puppy growth dataset I collected when our dog had eight puppies a few years ago. There is data for 10 dogs in total: 8 puppies, their mother, and another dog that was adopted several months after the puppies were born.</p><p>I collected their weight as often as possible. However, there were occasions when I could only weigh part of the litter, so there are missing values in some entries. Moreover, four of the puppies were adopted early on and their data stopped growing.</p><p>Here is a snippet of the data:</p><pre>from pathlib import Path<br> <br>file_name = Path(&#39;puppy_weights.csv&#39;)<br>root_folder = Path(&#39;data&#39;)<br>file_path = root_folder / file_name<br> <br>csv_df = pd.read_csv(file_path).set_index(&#39;Date&#39;)<br>csv_df /= 1000     #convert grams to kilograms<br>csv_df.head(7)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*ysWBOEhKIvzOpXGxTW0xEg.png" /><figcaption>First seven rows of the puppy weight dataset</figcaption></figure><h3>Interpolation of Missing Values</h3><p>I decided to deal with missing values and by using the interpolate function in pandas. It will fill-in missing values in a dataset based on parameters passed to it. I left it with its default behavior, which fills a missing entry with the average of the values immediately before and after the missing value. In case there isn’t a value after, it will just repeat the last value.</p><pre>csv_df.interpolate(axis=0,inplace=True)</pre><h3>Static Bar Charts With Manim’s BarChart Class</h3><p>Conveniently, Manim already has class that does most of what we want. As a start, here is how you would create a static bar chart with Manim. This is an example from the documentation page. We’ll look at how to animate it later.</p><pre>from manim import *<br> <br>class BarChartExample(Scene):<br>    def construct(self):<br>        chart = BarChart(<br>            values=[-5, 40, -10, 20, -3],<br>            bar_names=[&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;],<br>            y_range=[-20, 50, 10],<br>            y_length=6,<br>            x_length=10,<br>            x_axis_config={&quot;font_size&quot;: 36},<br>        )<br> <br>        c_bar_lbls = chart.get_bar_labels(font_size=48)<br> <br>        self.add(chart, c_bar_lbls)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*7kG6EOC5P6T6jHC1" /></figure><h3>Animation With Linear Progression</h3><p>We can also make simple animations by making use of BarChart’s built-in method change_bar_values. In this case, we provide the starting and final values and let Manim animate them. We can choose different animation rates from <a href="https://docs.manim.community/en/stable/reference/manim.utils.rate_functions.html">here</a>. I&#39;ll use the default linear progression for this example.</p><pre>class ChangeBarValuesExample(Scene):<br>    def construct(self):<br>        values=[28, 0, 0, 0, 0, 0, 0, 0, 0, 0]<br>        final_values = [33.1, 36, 29.25, 33.58, 4, 4.5, 5, 4.3, 7.2, 5.5]<br> <br>        chart = BarChart(<br>            values,<br>            y_range=[0, 40, 5],<br>            y_length=6.5,<br>            x_length=10,<br>            y_axis_config={&quot;font_size&quot;: 24},<br>        )<br>        self.play(Create(chart))<br>        self.wait(2)<br> <br>        self.play(chart.animate.change_bar_values(final_values), run_time=3)<br>        self.play(Create(chart.get_bar_labels(font_size=36))) <br> <br>        self.wait(3)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRjvReVCYO-w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRjvReVCYO-w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRjvReVCYO-w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24dae1fb0843966268a28e29a1edf315/href">https://medium.com/media/24dae1fb0843966268a28e29a1edf315/href</a></iframe><h3>Animation With Step-By-Step Values</h3><p>Since I want to animate the puppy dataset, I would like for the animation to go over all the data points I collected and not just the beginning and final ones. Unfortunately, I could not find an easy and built-in way to accomplish this with Manim.</p><p>The hacky solution I came up with involves using a for-loop that repeatedly calls chart.animate.change_bar_values on new values of data given by pandas&#39; itertuples method. Equally important is to select a linear rate function for the animation. If you select some other type of rate function, the animation will look strange and will seem to stop and start again at each data point.</p><p>Additionally, we are going to be using images on top of each bar. The images are pictures of each puppy were are tracking, and they are on a folder in the repository. Check the <a href="https://github.com/andresberejnoi/Manim-Bar-Chart-Race/blob/main/Bar%20Chart%20Race.ipynb">Jupyter notebook</a> to see how I got their paths.</p><p>Here is the Python code used and the resulting animation:</p><pre>%%manim -ql AnimatedBarChartWithImages<br> <br>class AnimatedBarChartWithImages(Scene):<br>    def construct(self):<br>        self.camera.background_color = WHITE<br> <br>        bar_names = csv_df.columns<br>         <br>        chart = BarChart(<br>            values = csv_df.iloc[0].to_list(),<br>            bar_names=bar_names,<br>            y_range=[0,40, 5],<br>            y_length=6.5,<br>            x_length=10, <br>            x_axis_config={<br>                &quot;font_size&quot;:20,<br>                &#39;label_direction&#39;:DOWN,<br>            },<br>            axis_config = {<br>                &#39;color&#39;:BLACK,<br>                &#39;tip_shape&#39;: StealthTip,<br>            }<br>        )<br> <br>        #==================================<br>        # Load images<br>        img_dic = {}    #the following nested for-loop seems very inefficient, but I&#39;m too tired to think<br>        for puppy_name in bar_names:<br>            for file in img_files:<br>                if puppy_name == file.stem:<br>                    img_dic[puppy_name] = file<br>                    break<br> <br>        images = []<br> <br>        dic_image_mobjects = {}<br>        for puppy_name, bar in zip(bar_names, chart.bars):<br>            img_path  = img_dic.get(puppy_name)<br>            img       = ImageMobject(img_path)<br>            img.width = chart.bars[0].width<br>            img.next_to(bar, UP)<br> <br>            images.append(img)<br> <br>            dic_image_mobjects[puppy_name] = img<br> <br>        #==================================<br>        # this section is to set the axis tick color. The best solution I found was the following for loops<br>        # from this reddit post:<br>        # &lt;https://www.reddit.com/r/manim/comments/x7iqzp/colors_of_axis_text_for_barchart/&gt;<br> <br>        for tick in chart.get_x_axis():<br>            tick.set_color(BLACK)<br> <br>        for tick in chart.get_y_axis():<br>            tick.set_color(BLACK)<br> <br>        #==================================<br>        # determine labels for the chart<br>        labels = chart.get_axis_labels(<br>            Tex(&quot;dogs&quot;, color=BLACK).scale(0.7), <br>                        Tex(&quot;weight (kg)&quot;, color=BLACK).scale(0.8)<br>        )<br> <br>        #==================================<br>        self.add(chart, labels)<br>        self.add(*[img.next_to(bar, UP) for img, bar in zip(images, chart.bars)])<br> <br>        date_text = Tex(csv_df.index[0], color=BLUE_E)<br>        date_text.move_to(UP*2 + RIGHT*3)<br>        self.play(Create(date_text))<br>         <br>        for i, row in enumerate(csv_df.itertuples()):<br>            date_str = row[0]<br>            new_date = Tex(date_str, color=BLUE_E)<br>            weights  = list(row[1:])  #first item is the date<br>             <br>            if i == 0:<br>                continue<br> <br>            elif i &gt; 10:  #comment out to render the full animation<br>                break<br> <br>            self.play(<br>                chart.animate.change_bar_values(weights), <br>                *[img.animate.next_to(bar, UP) for img, bar in zip(images, chart.bars)],<br>                date_text.animate.become(new_date, match_center=True, match_height=True,),<br>                rate_func=linear, <br>                run_time=0.2,<br>            )</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9hykkWQaj3Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9hykkWQaj3Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9hykkWQaj3Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a03114260a6a63313e4872c9b5238cd0/href">https://medium.com/media/a03114260a6a63313e4872c9b5238cd0/href</a></iframe><p>I’ll break down the code into the most relevant pieces so it is easier to follow.</p><h3>Creating the Initial BarChart Mobject</h3><p>In the first part of the code, we create a BarChart object with the initial values from the dataset:</p><pre>chart = BarChart(<br>    values = csv_df.iloc[0].to_list(),<br>    bar_names=bar_names,<br>    y_range=[0,40, 5],<br>    y_length=6.5,<br>    x_length=10, <br>    x_axis_config={<br>        &quot;font_size&quot;:20,<br>        &#39;label_direction&#39;:DOWN,<br>    },<br>    axis_config = {<br>        &#39;color&#39;:BLACK,<br>        &#39;tip_shape&#39;: StealthTip,<br>    }<br>)</pre><p>We are also extracting the column names from the dataset to use as bar names. Here is a short explanation of the other parameters:</p><ul><li>y_range: [min value of the y-axis, max value of the y-axis, tick frequency (5 means that there will be a tick at 5, 10, 15, 20, etc)</li><li>x_length/ y_length: Size of the y and x axes respectively on the canvas</li><li>x_axis_config / y_axis_config: A dictionary of parameters to pass to the underlying NumberPlane class to configure each axis individually.</li><li>axis_config: Here you can pass a dictionary with configuration parameters that will affect both axes at the same time</li></ul><h3>Loading Images And Placing Them Next To Each Bar</h3><p>The puppy images are stored under the folder images at the same level as the Jupyter notebook. To load the files, I used the Pathlib library:</p><pre>all_paths = Path(&#39;images&#39;).glob(&#39;**/*&#39;)<br> <br>img_files = [f for f in all_paths if f.is_file()]</pre><pre>[PosixPath(&#39;images/Tiny.png&#39;),<br> PosixPath(&#39;images/Simba.png&#39;),<br> PosixPath(&#39;images/Rolo.png&#39;),<br> PosixPath(&#39;images/Ragnar.png&#39;),<br> PosixPath(&#39;images/Luna.png&#39;),<br> PosixPath(&#39;images/Jucumari.png&#39;),<br> PosixPath(&#39;images/Emma.png&#39;),<br> PosixPath(&#39;images/Black2.png&#39;),<br> PosixPath(&#39;images/Black1.png&#39;),<br> PosixPath(&#39;images/Big Black.png&#39;)]</pre><p>Then, inside the main scene, we are creating ImageMobject objects with each image file.</p><pre>...<br> <br># Load images<br>img_dic = {}    #the following nested for-loop seems very inefficient, but I&#39;m too tired to think<br>for puppy_name in bar_names:<br>  for file in img_files:<br>    if puppy_name == file.stem:<br>        img_dic[puppy_name] = file<br>        break<br> <br>for puppy_name, bar in zip(bar_names, chart.bars):<br>    img_path  = img_dic.get(puppy_name)<br>    img       = ImageMobject(img_path)     # &lt;--- HERE WE CREATE IMAGEMOBJECTS<br>    img.width = chart.bars[0].width<br>    img.next_to(bar, UP)<br> <br>...</pre><p>ImageMobject is a way to display external images into manim. Additionally, you can pass any numpy array to represent an image instead of a file.</p><h3>Displaying The Chart</h3><pre>#==================================<br>...<br>self.add(chart, labels)<br>self.add(*[img.next_to(bar, UP) for img, bar in zip(images, chart.bars)])<br> <br>date_text = Tex(csv_df.index[0], color=BLUE_E)<br>date_text.move_to(UP*2 + RIGHT*3)<br>self.play(Create(date_text))</pre><p>In the snippet above, the first two lines add the chart, labels and puppy images directly on the canvas without animating them. The next three lines before the for-loop create a text object date_text which will keep track of the date of each row of data. We will update this object in the main loop.</p><h3>Running The Main Loop</h3><p>I’ll leave other parts of the code to the reader to go through, so we can give more time to the main loop at the bottom of the function:</p><pre>...<br>for i, row in enumerate(csv_df.itertuples()):<br>    date_str = row[0]<br>    new_date = Tex(date_str, color=BLUE_E)<br>    weights  = list(row[1:])  #first item is the date<br>     <br>    if i == 0:<br>        continue<br> <br>    elif i &gt; 10:  #comment out to render the full animation<br>        break<br> <br>    self.play(<br>        chart.animate.change_bar_values(weights), <br>        *[img.animate.next_to(bar, UP) for img, bar in zip(images, chart.bars)],<br>        date_text.animate.become(new_date, match_center=True, match_height=True,),<br>        rate_func=linear, <br>        run_time=0.2,<br>    )</pre><p>To animate the dataset, I’m getting each row of data from the pandas dataframe using itertuples(), while enumerating the result and keeping track of the index with variable i.</p><p>The first step inside the for-loop is to extract the weight and date data from the row given by the dataframe. We then create a new Tex object with the next date and use it to update the date on screen.</p><p>Next, the if statement there simply prevents the animation to use the first row of data, since it was already included with the initial chart. The elif statement helps me render part of the animation to test it.</p><p>Finally, we get to the self.play section. This is where the actual animation happens. The first line animates the bars with the new values coming from the pandas dataframe. The second animation is the one that updates the position of the puppy images to always stay on top of their respective bars. Next, the third line is the one that animates the Tex object to display an updated date. After that, I chose to use a linear rate function. As I explained before, we need a linear rate function for the animation to look smooth and continuous from data point to data point.</p><p>The run_time parameter is set to 0.2 seconds because that is how long it will take to animate each data point. If you set this parameter to 0.1 seconds, the animation will go twice as fast.</p><h3>Conclusion</h3><p>Hopefully you found this post useful and informative. Check the repository <a href="https://github.com/andresberejnoi/Manim-Bar-Chart-Race">here</a> to get access to the Jupyter notebook with the code. And, if you need a refresher on how to install and get started with Manim, read my <a href="https://andresberejnoi.com/using-manim-and-python-to-create-animations-like-3blue1brown/">last post about</a> it. Let me know in the comments if there are other topics of interest I could cover.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/bar-chart-race-with-manim/"><em>https://andresberejnoi.com</em></a><em> on September 18, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ece91a2da4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Gravity and Other Topics: August Reading List — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/quantum-gravity-and-other-topics-august-reading-list-andres-berejnoi-c5c84e335c8b?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5c84e335c8b</guid>
            <category><![CDATA[book-recommendations]]></category>
            <category><![CDATA[quantum-gravity]]></category>
            <category><![CDATA[astrophysics]]></category>
            <category><![CDATA[quantum-mechanics]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 17:41:40 GMT</pubDate>
            <atom:updated>2023-08-01T13:37:16.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quantum Gravity and Other Topics: August Reading List — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vz3Ike2DJ89dnRPx.jpeg" /></figure><p>In my previous <a href="https://andresberejnoi.com/category/reading-list/">reading lists</a>, I maintained a theme, such as for the <a href="https://andresberejnoi.com/reading-list-influenza-pandemics-and-their-relevance-today/">month of June</a>, when I recommended books about influenza pandemics and pandemics in general. For this month, I wanted to focus on other interests of mine: astrophysics, quantum physics and the universe. I won’t write detailed reviews since I read these books a while ago and unfortunately, I was not taking careful notes at the time. Maybe I’ll have to re-read them as well.</p><h3>Audible and Disclaimers</h3><p>I will include affiliate links to <a href="https://amzn.to/3KIjxCv">Audible</a> for all discussed books, and for ebook and physical formats when available. You will not be charged extra, and <a href="https://amzn.to/3KIjxCv">Audible</a> is likely to have the majority of books you want since it is the biggest audiobook platform.</p><p>When you buy a book from <a href="https://amzn.to/42O0s91">Au</a><a href="https://amzn.to/3KIjxCv">dible</a>, be sure to download and keep a local copy. That way, you own it like a physical book. If you only access it through the app, you rely on Audible for delivery. If they lose distribution rights for the book, you lose access. So, always download anything you purchase.</p><p>Sign up for a <a href="https://amzn.to/3KIjxCv">free Audible Premium Plus</a> membership trial and get one credit for a free audiobook. Even if you cancel the trial, you still get to keep the book you got from the promotion.</p><p>Another way to access the books I mention in this post is to check if they are available at your local library. This is certainly the cheapest option, but keep in mind that you may need to wait weeks to obtain them, and you will have a time limit to finish reading them (usually up to 14 days).</p><h3>Book Recommendations</h3><h4><a href="https://amzn.to/3Ydzh5U">Reality is Not What It Seems: The Journey to Quantum Gravity, By Carlo Rovelli</a></h4><figure><img alt="Cover of the book “Reality Is Not What It Seems” by Carlo Rovelli." src="https://cdn-images-1.medium.com/max/333/0*X3Am3ftCTQkT49xM.jpg" /></figure><p>One of my favorite books, Reality is Not What It Seems talks about quantum gravity and how humans have understood the nature of matter throughout ages. The author, Carlo Rovelli, is a physicist who studies quantum gravity. If I remember correctly, one of the most intriguing concepts that the author introduced in the book was the idea that spatial continuity may not be real. I think I remember some chapter talking about how space could also be divided down into indivisible quantum packets, and what we perceive as a continuous physical space could be the entanglement of those quantum space particles. It is definitely an interesting read for those of us interested in quantum physics.</p><p>Links:</p><ul><li><a href="https://amzn.to/3Ydzh5U">Audiobook</a></li><li><a href="https://amzn.to/3YgIx99">Ebook</a></li><li><a href="https://amzn.to/3YgyRf1">Hardcover</a></li></ul><h4><a href="https://amzn.to/3q4PxcT">The Order of Time, By Carlo Rovelli</a></h4><figure><img alt="Cover for the book “The Order of Time” by Carlo Rovelli and read by Benedict Cumberbatch." src="https://cdn-images-1.medium.com/max/500/0*uiXttynQTUXY_N5M.jpg" /></figure><p>My second recommendation for this month is another publication by Carlo Rovelli. In this book, the author discusses the nature of time, including past and the current understanding of it. I found it fascinating even though some things went over my head. I enjoyed the idea that at the most basic and quantum level, time may not even exist. It has definitely been a while since I read this book, so I don’t can’t describe this part very easily, but I recommend this book for those interested in time from a quantum physics perspective.</p><p>Links:</p><ul><li><a href="https://amzn.to/3q4PxcT">Audiobook</a></li><li><a href="https://amzn.to/3YeZpx4">Ebook</a></li><li><a href="https://amzn.to/3KgAMdS">Hardcover</a></li></ul><h4><a href="https://amzn.to/3q3qtTD">A Brief History of Nearly Everything, By Bill Bryson</a></h4><figure><img alt="Cover for the book “A Brief History of Nearly Everything” by Bill Bryson." src="https://cdn-images-1.medium.com/max/500/0*WFJlEgfOEZPScnA0.jpg" /></figure><p>I enjoyed reading this book for its coverage of many topics. The author focuses mainly on the history of science and the history of the universe. However, when it came to describing the history of modern humans (the last 4000 years or so), the book mainly covers western societies. I guess it could be due to the abundance of records about that time compared to other cultures.</p><p>This is my second book by Bill Bryson (the first one was “The Body”) and I like his writing style.</p><p>NOTE: Even though I liked the book, it could be outdated in terms of scientific understanding, since it was published over 20 years ago, in 2002.</p><p>Links:</p><ul><li><a href="https://amzn.to/3q3qtTD">Audiobook</a></li><li><a href="https://amzn.to/3qaaGSO">Ebook</a></li><li><a href="https://amzn.to/3Yfb4fq">Hardcover</a></li></ul><h3>Conclusion</h3><p>I hope you enjoy these books and I would greatly appreciate it if you could suggest other titles for me to read. Even though I have a bias for science, quantum physics, infectious diseases, and history, I’m open to any suggestions.</p><p>Let me know in the comments if you have any opinions on the books covered today.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/quantum-gravity-and-other-topics-august-reading-list/"><em>https://andresberejnoi.com</em></a><em> on July 31, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5c84e335c8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expanded Conda Environment Export Tool — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/expanded-conda-environment-export-tool-andres-berejnoi-2a5cf966fb3e?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a5cf966fb3e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[miniconda]]></category>
            <category><![CDATA[conda-environment]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 18:06:32 GMT</pubDate>
            <atom:updated>2023-07-14T18:16:05.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Expanded Conda Environment Export Tool — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FU94Ysiqn_StiRFM.png" /></figure><p>Here is a short post about conda environments and a conda script that adds a bit of extra functionality to the “ conda env export &quot; tool.</p><p>One minor annoyance I have with <strong>Conda</strong> is the limitation of its environment exporting tool ( conda env export) for my particular use. I decided to look for a solution that would solve the following pain-points:</p><ul><li>Not including pip installations when using flag “--from-history&quot;</li><li>When using flag “--from-history&quot;, package versions are often not included (depending on whether the user manually typed them)</li><li>When using “-from-history” flag, third-party channels are not included in the file</li></ul><p>Since I did not find something that addressed all the points above, I had to write a script for it, <a href="https://github.com/andresberejnoi/Conda-Tools">conda_export.py</a>.</p><p>The quick version of this post is that if you want an output like the one described above, just run the script like this (make sure PyYAML is installed in the environment, with “ pip install pyyaml &quot;):</p><pre>#run this script inside the conda environment you want to export <br>python conda_export.py --from-history --use-versions -o environment.py</pre><h3>Using The Conda Environment Export Script</h3><p>As I mentioned above, ideally, I would like to run the following conda command:</p><pre>conda env export --from-history &gt; environment.yml</pre><p>and generate a file that contains strictly the packages I installed (including those installed with pip). Additionally, those packages should indicate the specific version number that I installed.</p><p>The script should be run inside the conda environment you wish to export (you will need to install the PyYAML Python library: &quot; pip install pyyaml &quot;). Here are the flags to use if you want an output that includes only manually installed packages, including pip packages, as well as their versions:</p><pre>python conda_export.py --from-history --use-versions -o environment.yml</pre><p>The “--from-history&quot; flag will simply get the same output as using conda directly. However, in this case, I&#39;m also using &quot;--use-versions&quot;, which extracts version numbers by doing another call to &quot; conda env export&quot; and then joining the two results together. The &quot;-o&quot; flag is used to indicate the output file of the export. If &quot;-o &quot; flag is not provided, the output will be dumped to the terminal.</p><h3>Example Exporting a Conda Environment</h3><p>To showcase the expected output from this script, we will create a simple conda environment with some packages:</p><pre>conda create -n test_env python=3.9 numpy matplotlib</pre><p>Once the install is complete and the environment is activated, I want to also install a package from the “ conda-forge &quot; channel:</p><pre>#this is inside test_env environment <br>conda install -c conda-forge manim</pre><p>In case you are curious, manim is a mathematical animation engine originally developed by the creator of the YouTube channel <strong>3Blue1Brown</strong>. I wrote a blog post about <a href="https://andresberejnoi.com/using-manim-and-python-to-create-animations-like-3blue1brown/">how to use it</a> last week. Finally, we will also install a package with pip, such as the one I created a while ago: <a href="https://github.com/andresberejnoi/NetBuilder">netbuilder</a>.</p><p>With all that completed, here is the output of conda:</p><pre>conda env export --from-history</pre><pre>name: test_env<br>channels:<br>  - defaults<br>dependencies:<br>  - matplotlib<br>  - python=3.9<br>  - numpy<br>  - manim<br>prefix: /home/andres/miniconda3/envs/test_env</pre><p>As you can see, we lost information about the specific version numbers for all the packages unless we manually typed them. Also, we lost information about the channel “ conda-forge&quot; used to install the <a href="https://andresberejnoi.com/using-manim-and-python-to-create-animations-like-3blue1brown/">manim</a> library. And, there is no information about the packages installed with pip.</p><p>Now, if we run the conda_export.py script, we get the following:</p><pre>python conda_export.py --from-history --use-versions</pre><pre>channels:<br>- conda-forge<br>- defaults<br>dependencies:<br>- manim=0.17.3<br>- matplotlib=3.7.1<br>- numpy=1.25.0<br>- python=3.9.17<br>- pip:<br>  - netbuilder==0.2.3<br>name: test_env</pre><p>This output contains all the information needed to recreate the environment.</p><h3>How The Script Works</h3><p>You can check the script in the repository. Since I wrote it mostly for myself and very quickly, I think maybe some functions are a bit convoluted and messy, but they work.</p><p>Basically, if the “--from-history &quot; flag is used, the script will execute two commands:</p><pre>conda env export conda env export --from-history</pre><p>The output of each command is stored in a separate dictionary and a separate function merges them into a single dictionary only containing the common items.</p><p>Here is the part of the script that handles this condition:</p><pre>...<br> <br>elif from_history and use_versions:<br>        #-- Create merged list of dependencies<br>        full_env_output:dict = export_env(from_history=False, no_builds=False)<br>        hist_env_output:dict = export_env(from_history=True)<br>        _merged_dependencies:list = merge_dependencies(full_env_output, hist_env_output, use_versions)<br>         <br>        #-- setup final env dictionary<br>        final_env_dict = dict()<br>        final_env_dict[&#39;name&#39;]         = full_env_output[&#39;name&#39;]<br>        final_env_dict[&#39;channels&#39;]     = full_env_output[&#39;channels&#39;]<br>        final_env_dict[&#39;dependencies&#39;] = _merged_dependencies<br>         <br>        _pip_section = get_pip_section(full_env_output[&#39;dependencies&#39;])<br>        if len(_pip_section.values()) &gt; 0:  #this adds the pip part <br>            final_env_dict[&#39;dependencies&#39;].append(_pip_section)<br>         <br>        final_env_dict[&#39;prefix&#39;] = full_env_output[&#39;prefix&#39;]</pre><p>In the snippet above, “<strong>export_env</strong>&quot; is the function that runs a sub-process with the two conda commands. I borrowed that function from this GitHub <a href="https://gist.github.com/gwerbin/dab3cf5f8db07611c6e0aeec177916d8">gist</a>.</p><h3>Future Work</h3><p>Hopefully, conda implements some of these features as options natively in the future. But, in the mean time the script is useful to me. One thing I would like to do is rewrite it to be less verbose and to use only standard Python libraries. Currently, PyYAML needs to be installed in the environment the script is used in. If I want to export my environment, I need to install that package, polluting the environment with unwanted libraries.</p><p>Let me know if you have any questions or suggestions about this or anything Python related. You can also check my other Python posts <a href="https://andresberejnoi.com/category/programming/">here</a>, and let me know what you think.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/expanded-conda-environment-export-tool/"><em>https://andresberejnoi.com</em></a><em> on July 14, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a5cf966fb3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Manim and Python to Create Animations Like 3Blue1Brown — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/using-manim-and-python-to-create-animations-like-3blue1brown-andres-berejnoi-34f755606761?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/34f755606761</guid>
            <category><![CDATA[manim]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[3blue1brown]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 21:04:07 GMT</pubDate>
            <atom:updated>2023-06-30T22:22:02.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Manim and Python to Create Animations Like 3Blue1Brown — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JF8XqSFqNZWt92DB.png" /></figure><p>If you’ve ever been mesmerized by Grant Sanderson’s fluid and captivating animations on his YouTube channel, <a href="https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw">3Blue1Brown</a>, you might be wondering how he creates them. The answer lies in a homemade animation engine called <strong>Manim</strong>, built with Python. While Grant Sanderson’s <a href="https://github.com/3b1b/manim">original version</a> is available, he recommends beginners start with the <a href="https://github.com/ManimCommunity/manim">community edition</a>.</p><p>This version is actively maintained, updated, and perfect for those looking to dive into the world of animation. Personally, I discovered Manim while working on videos about neural networks for my <a href="https://www.youtube.com/andresberejnoi">YouTube channel</a>. Its powerful features made it an ideal tool to bring complex concepts to life. Take a look at my <a href="https://andresberejnoi.com/category/programming/neural-networks/">neural network blog posts</a> for more in-depth explanations.</p><p>The examples and descriptions in this post use Manim community edition.</p><h3>Objectives</h3><p>The <a href="https://docs.manim.community/en/stable/tutorials/quickstart.html">official Manim documentation pages</a> contain large numbers of examples, so I will instead focus on building more complicated animations to show how they can work together. One of the great things about Manim is that you can easily automate several parts of the animation process.</p><p>To start, we need to install the package.</p><h3>Manim Installation With Conda</h3><p>Look at <a href="https://docs.manim.community/en/stable/installation.html">this link</a> for instructions on different installation methods. I prefer the simplicity of conda, so I’m using the appropriate instructions in <a href="https://docs.manim.community/en/stable/installation/conda.html">this page</a>.</p><p>Basically, you just need to create a new conda environment and install manim from the conda-forge conda channel. Another benefit of using conda is that you will get ffmpeg and other dependencies installed automatically as well.</p><pre>conda create -n my-manim-environment<br>conda activate my-manim-environment<br>conda install -c conda-forge manim</pre><p>If you want to animate equations, you need to have LaTex packages installed. If you happen to be on Fedora 38, you can install LaTex libraries with any of the following commands:</p><pre>sudo dnf install texlive-scheme-basic<br>sudo dnf install texlive-scheme-medium<br>sudo dnf install texlive-scheme-full</pre><p>I would suggest to install the full package. It is about 5 GB after installation. I tried installing the medium package to save some space and my animations kept failing, so it seems Manim uses a good amount of LaTex packages.</p><h3>Animating With Manim</h3><p>The easiest way to practice with Manim is to use Jupyter notebooks, in my opinion. You can write code and see the resulting animation right there on the cell. Therefore, you can install Jupyter notebooks inside your conda environment like this:</p><pre> <br>conda install jupyter</pre><p>Once installed, launch a new notebook from the terminal or you can create a notebook file from inside VSCode.</p><p>I’ll leave a link to the full <a href="https://github.com/andresberejnoi/PublicNotebooks/blob/master/Manim%20Notebooks/manim_examples.ipynb">Jupyter notebook</a> I’m using for these examples. Let’s start with a simple example with some text and shape transformations:</p><pre>from manim import *<br> <br>config.media_width = &quot;75%&quot;<br>config.verbosity = &quot;WARNING&quot;</pre><pre>%%manim -qh ShapeAndTextScene<br> <br>class ShapeAndTextScene(Scene):<br>    def construct(self):<br>        text = Tex(&quot;Example Scene With Some Shapes&quot;)<br> <br>        circle = Circle()<br>        circle.set_fill(BLUE, opacity=0.8)<br> <br>        hexagon = RegularPolygon(n=6)<br>        hexagon.set_fill(GREEN, opacity=0.5)<br> <br>        self.play(Write(text))<br>        self.play(text.animate.shift(UP*3))<br>        self.wait(0.3)<br>        self.play(DrawBorderThenFill(circle))<br>        self.wait()<br> <br>        self.play(Transform(circle, hexagon), run_time=1.5)<br>        self.wait(0.5)<br> <br>        self.play(hexagon.copy().animate.shift(LEFT * 3))<br>        self.wait(0.35)<br>        self.play(hexagon.copy().animate.shift(RIGHT * 3))<br>        self.wait()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHzE0PISsHV4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHzE0PISsHV4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHzE0PISsHV4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7edd50203f6f0b82ab164224a07d3ee9/href">https://medium.com/media/7edd50203f6f0b82ab164224a07d3ee9/href</a></iframe><h3>Explaining the Code</h3><p>For starters, the first line above: %%manim -qm ShapeAndTextScene is a magic command for Jupyter. It renders the scene right under the cell. Here, ShapeAndTextScene is the name of the class we want to render. The qh flag indicates the render quality ( <strong>h</strong> for high), and here are the other options you can select:</p><pre>-q, --quality [l|m|h|p|k]      Render quality at the following resolution<br>                                 framerates, respectively: 854x480 15FPS,<br>                                 1280x720 30FPS, 1920x1080 60FPS, 2560x1440<br>                                 60FPS, 3840x2160 60FPS</pre><p>You could of course just write your animation scenes in a regular Python script and render the scene from the terminal with the following syntax ( <a href="https://docs.manim.community/en/stable/tutorials/output_and_config.html?highlight=last%20frame">more info on that here</a>):</p><pre>manim -qh YOUR_PYTHON_SCRIPT.py YourSceneClassName</pre><p>The next part is defining the scene class. We normally inherit from Manim’s Scene, although there are <a href="https://docs.manim.community/en/stable/reference_index/scenes.html">other options</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*IZrKBn3jtvKSPtnV" /><figcaption>Rendered portion of the code for the previous animation. This image was also generated using Manim’s Code class.</figcaption></figure><p>After defining the class, you will program your scene inside the class function construct. Here is where all the animations will take place. Notice in the snippet above that I&#39;m simply defining the objects that will appear in the scene. However, if I were to run the cell like that, nothing would show up. You need to animate or add those object into the scene:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E9NsBVMmM9rDv79g" /><figcaption>Animation portion of the first Manim animation example.</figcaption></figure><p>Whenever you want to animate something into the scene, you can use <a href="http://self.play/">self.play</a> and combine it with <a href="https://docs.manim.community/en/stable/reference/manim.animation.creation.html">different animation methods</a>: Write, Create, DrawBoarderThenFill, Transform, <a href="https://docs.manim.community/en/stable/reference/manim.animation.creation.html">etc</a>. You can also set the run_time parameter (in seconds) to control how long it takes for that particular animation to complete.</p><p>If you wanted to add objects to the scene instantly without animating their creation, you can simply use self.add(...).</p><p>When moving Mobjects from one place to another, you can use the built-in vectors: LEFT, RIGHT, UP, DOWN, etc. to tell Manim where to place them. These are numpy arrays of shape 1×3 (for x,y,z dimensions). Moreover, as the example shows, you can multiply them by other vectors or scalar to scale their impact. In this case, I used LEFT * 3 and RIGHT * 3, which means the first hexagon will shift to the left by 3 left units, and the other one will shift to the right by three right units.</p><h3>More Manim Examples</h3><p>I feel that Manim offers almost unlimited options to achieve your animation goals. Maybe “unlimited” is not the right word, but I can certainly create everything I want to visualize using it. Since I’m working on a neural network video to complement <a href="https://andresberejnoi.com/category/programming/neural-networks/">my posts</a>, I wanted to showcase examples of matrix animations on Manim:</p><pre>%%manim -qh MatrixExample<br> <br>class MatrixExample(Scene):<br>    def construct(self):<br> <br>        elements1 = [<br>            [0.158, &#39;\\\\pi&#39;, -4.325],<br>            [11   ,    0  , 3.876],<br>        ]<br> <br>        #create Matrix Mobject<br>        mat1 = Matrix(<br>            elements1,<br>            left_bracket = &#39;\\\\{&#39;,<br>            right_bracket = &#39;\\\\}&#39;,<br>            v_buff=1.3,<br>            h_buff=2.5,<br>        )<br> <br>        #create column rectangles ahead of time (they will added to the scene later)<br>        col0 = SurroundingRectangle(mat1.get_columns()[0])<br>        col1 = SurroundingRectangle(mat1.get_columns()[1]) <br>        col2 = SurroundingRectangle(mat1.get_columns()[2])<br> <br>        #animate creation of the matrix<br>        self.play(Create(mat1), run_time=2)<br>        self.wait()<br> <br>        # animate surrounding rectangles for each column<br>        self.play(Create(col0))<br>        self.wait()<br> <br>        self.play(Transform(col0, col1, replace_mobject_with_target_in_scene=True))<br>        self.wait()      <br> <br>        self.play(Transform(col1, col2, replace_mobject_with_target_in_scene=True))<br>        self.wait()<br>        self.play(Uncreate(col2))<br> <br>        # change size of the entire matrix and shift its position<br>        self.play(mat1.animate.scale(0.7).shift(LEFT*3.5 + UP*2))<br>        self.wait()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FADD0jyK4HIk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DADD0jyK4HIk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FADD0jyK4HIk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/52818620babbbfeb3d0ecf73737955fa/href">https://medium.com/media/52818620babbbfeb3d0ecf73737955fa/href</a></iframe><h3>Grouping Mobjects</h3><p>One very useful class of Manim is VGroup. It is a container class where you can group many different objects. It makes animating easier because you can apply transformations, shifts and effects to the entire group instead of doing it for each element individually.</p><p>This post is getting a bit long for now, so I’ll explain <a href="https://github.com/andresberejnoi/PublicNotebooks/blob/master/Manim%20Notebooks/manim_examples.ipynb">the code</a> for the following animation next week. For now, simply note how each layer in the following neural network is a VGroup that contains the node shapes, node labels, and layer label on top. That’s why they can move together with a single command.</p><pre>class TestNetwork(Scene):<br>    def construct(self,):<br> <br>        #--Constants and Stuff<br>        _shift_val = 4<br>        _run_time  = 1<br> <br>        #--Create the layers<br>        input_layer = generate_network_layer(<br>            num_nodes       = 2,<br>            include_bias    = True, <br>            layer_type      = &#39;input&#39;, <br>            layer_idx       = 0,<br>        )<br> <br>        hidden_layer = generate_network_layer(<br>            num_nodes       = 3,<br>            include_bias    = True, <br>            layer_type      = &#39;hidden&#39;, <br>            layer_idx       = 1,<br>        )<br> <br>        output_layer = generate_network_layer(<br>            num_nodes       = 1,<br>            include_bias    = False, <br>            layer_type      = &#39;output&#39;, <br>            layer_idx       = 2,<br>        )<br> <br>        #-- Draw the layers<br>        self.play(*[Create(item, run_time=1) for item in input_layer]) <br>        self.play(input_layer.animate.shift(LEFT * _shift_val))    <br>        self.wait(0.5)<br> <br>        self.play(*[Create(item, run_time=_run_time) for item in hidden_layer]) <br>        self.wait(0.5) <br> <br>        output_layer.shift(RIGHT * _shift_val).shift(UP * 0.75) <br>        self.play(*[Create(item, run_time=_run_time) for item in output_layer])    <br>        self.wait(0.5)<br> <br>        #----------------------------<br>        #-- Create arrows <br>        input_hidden_arrows  = generate_layer_connections(input_layer[0], hidden_layer[0])<br>        hidden_output_arrows = generate_layer_connections(hidden_layer[0], output_layer[0])<br> <br>        self.play(*[GrowArrow(arrow) for arrow in input_hidden_arrows])<br>        self.wait()<br> <br>        self.play(*[GrowArrow(arrow) for arrow in hidden_output_arrows])<br>        self.wait(2)<br> <br>        #------------------------------<br>        #-- add labels to connections<br>        self.play(Uncreate(input_hidden_arrows), Uncreate(hidden_output_arrows))<br>        self.wait()<br> <br>        labeled_input_hidden_arrows = generate_random_labeled_layer_connections(input_layer[0], hidden_layer[0], font_size=15, add_frame=True,)<br>        self.play(*[GrowArrow(arrow) for arrow in labeled_input_hidden_arrows])<br>        self.wait(0.4)<br> <br>        labeled_hidden_output_arrows = generate_random_labeled_layer_connections(hidden_layer[0], output_layer[0], font_size=15, add_frame=True,)<br>        self.play(*[GrowArrow(arrow) for arrow in labeled_hidden_output_arrows])<br>        self.wait()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_kMDgdRlw1U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_kMDgdRlw1U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_kMDgdRlw1U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d787abc3fd7b163b04a6899125762ba3/href">https://medium.com/media/d787abc3fd7b163b04a6899125762ba3/href</a></iframe><p>The code above does not show the helper functions generate_network_layer, generate_layer_connections, or generate_random_labeled_layer_connections. Those classes automate the process of grouping several shapes so I then shift the entire layer to the side. Check the notebook at <a href="https://github.com/andresberejnoi/PublicNotebooks/blob/master/Manim%20Notebooks/manim_examples.ipynb">this link</a> to study the code. I will go into more detail in my next post.</p><h3>Conclusion</h3><p>This was a pretty quick and simple introduction to Manim Community edition. My main goal was to show some examples that make use of different features in the engine. However, I realize that I haven’t covered the basic building blocks and basic functions. I think the official documentations do a pretty good job at explaining those aspects.</p><p>If you have any questions or recommendations, don’t hesitate to leave a comment and stay tuned for my next posts about animating with Manim.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/using-manim-and-python-to-create-animations-like-3blue1brown/"><em>https://andresberejnoi.com</em></a><em> on June 30, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34f755606761" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading List: Influenza Pandemics and Their Relevance Today — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/reading-list-influenza-pandemics-and-their-relevance-today-andres-berejnoi-2722f36d43f1?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/2722f36d43f1</guid>
            <category><![CDATA[pandemic]]></category>
            <category><![CDATA[influenza]]></category>
            <category><![CDATA[readinglist]]></category>
            <category><![CDATA[1918-spanish-flu]]></category>
            <category><![CDATA[1918-influenza-epidemic]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 22:11:05 GMT</pubDate>
            <atom:updated>2023-07-06T19:19:44.524Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reading List: Influenza Pandemics and Their Relevance Today — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TwrZUMSAK1eNrBD6.jpg" /></figure><p>Last year, I got very interested in the topic of diseases. In particular, influenza pandemics such as infamous “Spanish Flu” from 1918. As such, I searched for books that talked about it and here is a list of some of them. If you want to see list of previous books I wrote about, you can find them <a href="https://andresberejnoi.com/category/reading-list/">here</a>.</p><p><a href="https://andresberejnoi.com/category/reading-list/">Reading List Archives — Andres Berejnoi</a></p><p>Today’s post is short because I have not been taking many notes on these books while listening to them. However, the books in this list are very good, specially if you are interested in disease history. I was able to draw many parallels from the pandemics covered and the current covid-19 pandemic.</p><h3>Audible and Disclaimers</h3><p>I will include affiliate links to <a href="https://amzn.to/3XIjbRC">Audible</a> for all discussed books, and for ebook and physical formats when available. You will not be charged extra, and <a href="https://amzn.to/3XIjbRC">Audible</a> is likely to have the majority of books you want since it is the biggest audiobook platform.</p><p>When you buy a book from <a href="https://amzn.to/42O0s91">Au</a><a href="https://amzn.to/42O0s91">dible</a>, be sure to download and keep a local copy. That way, you own it like a physical book. If you only access it through the app, you rely on Audible for delivery. If they lose distribution rights for the book, you lose access. So, always download anything you purchase.</p><p>Sign up for a <a href="https://amzn.to/3XIjbRC">free Audible Premium Plus</a> membership trial and get one credit for a free audiobook. Even if you cancel the trial, you still get to keep the book you got from the promotion.</p><p>Another way to access the books I mention in this post is to check if they are available at your local library. This is certainly the cheapest option, but keep in mind that you may need to wait weeks to obtain them, and you will have a time limit to finish reading them (usually up to 14 days).</p><h3>Book Recommendations</h3><ul><li><a href="https://amzn.to/46DBZoX">“The Great Influenza: The Story of the Deadliest Pandemic in History” by John M. Barry</a></li><li><a href="https://amzn.to/3JNBf74">“The Fatal Strain: On The Trail of Avian Flu And The Coming Pandemic” by Alan Sipress</a></li><li><a href="https://amzn.to/3PH4CM3">“Pale Rider — The Spanish Flu of 1918 And How It Changed The World” by Laura Spinney</a></li></ul><h4><a href="https://amzn.to/46DBZoX">“The Great Influenza: The Story of the Deadliest Pandemic in History” by John M. Barry</a></h4><p>The book outlines the poor state of medicine in the US before the 1918 pandemic. The field was largely unregulated and accreditation was plagued with conflicts of interest. There were few requirements for students to earn their degrees, with many schools owned by professors who had an incentive to accept as many paying students as possible.</p><p>Europe had a strong culture of research and science, while the US initially had an anti-scientific approach to medicine. The book tells the story of how the US transformed to become a leading research center in the world before the pandemic broke out, thanks to a few influential individuals who adopted European standards. We also learn about the key scientists and figures who played a crucial role in fighting the great influenza.</p><p>The book discusses the influenza pandemic’s origins in a Kansas military base that then spread to allied countries in Europe. The book covers the disease’s devastation in the most affected US cities and estimates the global death toll, which may have reached 100 million people due to influenza or its complications. The pandemic lasted over 2 years with at least 3 waves, but most casualties occurred in just a few weeks.</p><p>One shocking number from this book was the estimated death toll on the Indian subcontinent alone from the pandemic. It is believed that as many as 19–20 million people died as a result of the outbreak. To put it in perspective, that number is higher than the entire death toll of the first world war.</p><p>It was interesting to learn how the US and many other countries involved in the war suppressed information about the outbreak.</p><p>Make sure to check it out. The audiobook version is almost 20 hours long and it was worth every minute.</p><ul><li><a href="https://amzn.to/46DBZoX">Audible Version</a></li><li><a href="https://amzn.to/43d6kI6">Ebook version</a></li><li><a href="https://amzn.to/3NEDACg">Hardcover version</a></li></ul><h4><a href="https://amzn.to/3JNBf74">“The Fatal Strain: On The Trail of Avian Flu And The Coming Pandemic” by Alan Sipress</a></h4><p>Unlike the previous book, this one follows a much more recent story. It covers the influenza outbreaks during the 2000’s that affected Asia. It tells the story of the efforts by the World Health Organization (WHO), its officers and government officials to contain different outbreaks.</p><p>The author also explains the unique conditions that make South East Asia ripe for influenza outbreaks. The sub-region presents many challenges for organizations such as the WHO when it comes to preventing or containing a pandemic.</p><p>The book also highlights weak points in our supply chain and how a pandemic on the level of the one in 1918 would paralyze several industries. Global trade would collapse at a time when many countries do not produce their own medicine and vaccines.</p><p>The author mentions that at the time of writing, more than half of the vaccines used in the US were produced in the UK. That means a supply chain disruption would leave the country potentially unable to fight an outbreak. Additionally, there are not enough respirators in the US to supply all the people who would likely need them during another influenza pandemic. It would be interesting to see what these figures look like now, after the covid-19 pandemic.</p><ul><li><a href="https://amzn.to/3JNBf74">Audible Version</a></li><li><a href="https://amzn.to/3JJjKo8">Ebook version</a></li><li><a href="https://amzn.to/3PLIJLw">Hardcover version</a></li></ul><h4><a href="https://amzn.to/3PH4CM3">“Pale Rider — The Spanish Flu of 1918 And How It Changed The World” by Laura Spinney</a></h4><p>This book covers the same time period as the first one on the list, but while the first one covers the story from the point of view of the scientists trying to stop the outbreak, in this book there is more emphasis on the effects on people and governments. Even though this book is very similar to the first one, it covers non-overlapping topics and both of them are valuable.</p><ul><li><a href="https://amzn.to/3PH4CM3">Audible version</a></li><li><a href="https://amzn.to/3NF63Ie">Ebook version</a></li><li><a href="https://amzn.to/3D4JEPH">Hardcover version</a></li></ul><h3>Conclusions</h3><p>There are many things to learn from all the books here, if I were to choose only one, I would go with <a href="https://amzn.to/46DBZoX">“The Great Influenza: The Story of the Deadliest Pandemic in History”</a>. I enjoy reading about history and this book provides a very comprehensive account of what happened. On the other hand, if you are more interested in learning how influenza is still a danger today, then <a href="https://amzn.to/3JNBf74">“The Fatal Strain</a>” would be the book to read.</p><p>One thing all three books mention is that we should not be comfortable about influenza. The nature of the virus is such that it mutates rapidly and eventually, another strain like the one in 1918 or even worse will appear. It is not a matter of “if” but “when” it happens. Things that help during a pandemic is for officials to tell the truth and keep the public informed.</p><p>Let me know if you have any comments on these books, or if you have a recommendation. Any topic is welcome, but currently, I am interested in good books about pandemics, plagues, or potentially AI and its repercussions.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/reading-list-influenza-pandemics-and-their-relevance-today/"><em>https://andresberejnoi.com</em></a><em> on June 2, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2722f36d43f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[May Must-Reads: 3 Books to Add to Your Monthly Reading List — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/may-must-reads-3-books-to-add-to-your-monthly-reading-list-andres-berejnoi-d27038f4d922?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27038f4d922</guid>
            <category><![CDATA[yuval-noah-harari]]></category>
            <category><![CDATA[readinglist]]></category>
            <category><![CDATA[sapiens]]></category>
            <category><![CDATA[book-recommendations]]></category>
            <category><![CDATA[reading]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Tue, 02 May 2023 13:30:51 GMT</pubDate>
            <atom:updated>2023-07-06T19:22:38.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>May Must-Reads: 3 Books to Add to Your Monthly Reading List — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K7-AQV97UW2A-BGB.jpeg" /></figure><p>This is my second monthly reading list; a place where I share books I have recently read or listened to and some notes about them. If you want to start the month with some interesting topics, make sure to check out my recommendations below. Here are <a href="https://andresberejnoi.com/3-great-books-to-read-this-april/">the books I recommended last month</a> in the first entry to this series. I’m sharing only three books per month because it seems to be a manageable number of options to choose from.</p><h3>Audible and Disclaimers</h3><p>I will include affiliate links to <a href="https://amzn.to/3XIjbRC">Audible</a> for all discussed books, and for ebook and physical formats when available. You will not be charged extra, and <a href="https://amzn.to/3XIjbRC">Audible</a> is likely to have the majority of books you want since it is the biggest audiobook platform.</p><p>When you buy a book from <a href="https://amzn.to/3XIjbRC">Audible</a>, be sure to download and keep a local copy. That way, you own it like a physical book. If you only access it through the app, you rely on Audible for delivery. If they lose distribution rights for the book, you lose access. So, always download anything you purchase.</p><p>Sign up for a <a href="https://amzn.to/3XIjbRC">free Audible Premium Plus</a> membership trial and get one credit for a free audiobook. Even if you cancel the trial, you still get to keep the book you got from the promotion.</p><p>Another way to access the books I mention in this post is to check if they are available at your local library. This is certainly the cheapest option, but keep in mind that you may need to wait weeks to obtain them, and you will have a time limit to finish reading them (usually up to 14 days).</p><h3>Book Recommendations</h3><p>For this month, I decided to go for some books about human nature, history and progress. If you just want the titles, here are the links. Keep reading below if you would like to read through some of my notes:</p><ul><li><a href="https://amzn.to/44pR77K">“Humankind — A Hopeful History” by Rutger Bregman</a></li><li><a href="https://amzn.to/3NGfYgz">“Sapiens: A Brief History of Humankind” by Yuval Noah Harari</a></li><li><a href="https://amzn.to/3PKWbiT">“The Dawn of Everything — A New History of Humanity” by David Graeber &amp; David Wengrow</a></li></ul><h4><a href="https://amzn.to/44pR77K">“Humankind — A Hopeful History” By Rutger Bregman</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*ymbarTcsM-Lc7VOU" /></figure><p>This book has quickly become one of my favorites and I can’t recommend it enough. The author challenges the idea that humans are inherently selfish, arguing that most people believe others are selfish and untrustworthy, and treat them accordingly. As a result, this belief becomes a nocebo (the opposite of a placebo), becoming a self-fulfilling prophecy; a vicious cycle.</p><p>The author presents a data-filled view of different psychological experiments conducted during the last century, casting doubts on their conclusions based on the researchers’ bias. These experiments include the infamous Stanford prison experiment and the electroshock experiment.</p><p>The author also covers a famous New York City case where a young woman was killed on the street of her neighborhood while allegedly 27 people just watched without calling the police. After studying the evidence, it becomes clear that the true story is nothing like what the newspapers and the media portrayed.</p><p>The book also addresses difficult topics that seem to go against its main premise, such as war and the holocaust, and provides possible explanations for this apparent discrepancy.</p><p>At the end of the book, the author includes a few tips on how to live, using this new view of humanity. One of my favorite parts is where the author encourages the reader to be more trusting. According to him, getting taken advantage of from time to time is a small price to pay to see the world in a more realistic way.</p><p>Some points:</p><ul><li>Cynics are usually regarded as “realistic”. This book argues that it is the opposite. Cynics and those who believe humans are always acting in self-interest have a warped and unrealistic understanding of human nature.</li><li>It is best to avoid the news, especially stories that focus on sensational events. The news does not reflect real life, and the media tends to highlight the most unusual events, leading people to believe that the world is much darker than it actually is.</li><li><a href="https://amzn.to/44pR77K">Audible version</a></li><li><a href="https://amzn.to/3O3U60e">Ebook version</a></li><li><a href="https://amzn.to/3O1I47r">Hardcover version</a></li></ul><h4><a href="https://amzn.to/3NGfYgz">“Sapiens: A Brief History of Humankind” by Yuval Noah Harari</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*LzVpcYr0qZUv__8I" /></figure><p>In “ <a href="https://amzn.to/40UGtnb">Sapiens</a> “, Yuval Noah Harari covers the history of humanity from around 70,000 years ago until the present. Among the most interesting points for me was the description of how inequality was born and spread with the advent of agriculture.</p><p>Another important point the book makes is that one of the main characteristics that makes us human is our ability to imagine. For instance, the book points out that most of us believe in countries, religions, corporations, money, etc. However, all those are just abstract entities created by our collective imagination. They don’t exist in the real sense of the word, and yet, we empower them through our joint beliefs.</p><p>The author maintains that this ability of humans is one of the qualities that allows us to build large societies. Other animals can’t do that. I think the book also gives a hopeful message regarding these imaginary entities. Since they are not a product of natural or physical laws, but of culture and human laws. That means we humans have the power to change them to fit our needs. For instance, if corporations are destroying the planet, we can change our laws to remedy this.</p><p>Finally, the book touches a bit on what is ahead for humanity with the advent of gene manipulation techniques and improvements in machine learning. However, these topics are better covered in Yuval Noah’s next book: “<a href="https://amzn.to/4451r57">Homo Deus: A Brief History of Tomorrow</a>”. I will probably write a review/ recommendation about it in the near future.</p><ul><li><a href="https://amzn.to/3NGfYgz">Audible version</a></li><li><a href="https://amzn.to/43eT1XH">Ebook version</a></li><li><a href="https://amzn.to/43g4g2b">Hardcover version</a></li></ul><h4><a href="https://amzn.to/3PKWbiT">“The Dawn of Everything — A New History of Humanity” by David Graeber &amp; David Wengrow</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*6m91ksHikXhXqSZa" /></figure><p>The authors of this book try to dispel the preconceived notions about how societies evolve always from egalitarian to unequal. They maintain that most anthropologists and historians assume that a society of inequality like most modern ones (where some people have more than others) is inevitable, without really looking at the actual evidence.</p><p>In the book, the authors present evidence that humans have known about unequal arrangements of societies but that pre-historic civilizations categorically chose to move away from that type of organization.</p><p>The book paints a picture of early civilizations as having more agency than traditional western understanding grants them. The authors also emphasize several times throughout the chapters that they are using actual evidence to back up their claims, unlike the conventional and unquestioned notions that most archeologists and the general public hold.</p><p>Civilizations moved fluidly from centralized power to egalitarian arrangements when the need suited them. Many early civilizations of hunter-gatherers chose to remain so, instead of transitioning to agrarian societies. So, even though they knew about the existence of agriculture, they decided to remain hunter-gatherers because of their beliefs about how humans should behave towards others and the kinds of activities that are inherently human.</p><p>The authors also challenge traditional popular historians at some points. They specifically challenge Yuval Noah Harari’s book “<a href="https://amzn.to/3NGfYgz">Sapiens</a>” for several reasons. One of the reasons is Harari’s portrayal of wheat as an entity with agency. They also challenge the notion that agricultural societies are unavoidable.</p><p>I’m doing a poor job of explaining it here, but the book is very interesting and I recommend it highly. It is a bit long (24 hours for the audiobook), but the story is engaging so it went by very quickly for me.</p><blockquote><em>Yuval Noah Harari Responds To This Book’s Criticism:</em></blockquote><p>To complement this book, I suggest watching this <a href="https://www.youtube.com/watch?v=Li57H_bI_YU&amp;ab_channel=AdamConover">interview of Yuval Noah by Adam Conover</a> on YouTube. It is a bit long but at some points, the interviewer asks Yuval Noah directly about his opinion of this book (The Dawn of Everything: A New History of Humanity).</p><p>The part of the interview that directly addresses this book is at around the <a href="https://youtu.be/Li57H_bI_YU?t=3720">1:02:00 mark</a>. I still recommend watching the whole thing,but if you are only interested in that part, then you can go to that point.</p><ul><li><a href="https://amzn.to/3PKWbiT">Audible version</a></li><li><a href="https://amzn.to/3PL6Dqp">Ebook version</a></li><li><a href="https://amzn.to/3rekcoa">Hardcover version</a></li></ul><h3>Discussion and Conclusion</h3><p>Hopefully, you will enjoy these books as I have done. I would say they are must-read because the topics can have wide implications for how we see life. Let me know if you have read any of them and what you thought about it. Also, feel free to recommend other books so I can add them to my to-read list.</p><p>You can subscribe to my newsletter to get notified next time I post a new list of books to read. I think I’ll be doing this once a month.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/may-must-reads-3-books-to-add-to-your-monthly-reading-list/"><em>https://andresberejnoi.com</em></a><em> on May 2, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27038f4d922" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Backpropagation With Numpy — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/how-to-implement-backpropagation-with-numpy-andres-berejnoi-e7c14f2e683a?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7c14f2e683a</guid>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 13:45:26 GMT</pubDate>
            <atom:updated>2023-07-06T19:28:03.675Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Backpropagation in Python: Building a Neural Network from Scratch — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B-vCOjR0xm1_I209.png" /></figure><p>In today’s post, we will implement a matrix-based backpropagation algorithm with gradient descent in Python. For this purpose, we’ll only use the Numpy library to explain a bit of the mathematics behind the process (mainly multivariate calculus). To better cement the concept, we’ll build an XOR neural network (a network that learns to behave like an XOR logic gate).</p><p>Consider this post as part 2 of my series on neural networks, starting with “ <a href="https://andresberejnoi.com/how-to-build-a-feedforward-neural-network-in-python/">How to Build a Feedforward Neural Network in Python</a>”.</p><h3>Resources</h3><p>If you are looking for a great resource on machine learning, I recommend the third edition of Aurélien Géron’s O’Reilly book: “<a href="https://amzn.to/3Lpcak7">Hands-On Machine Learning With Scikit-Learn, Keras &amp; Tensorflow</a>”.</p><p>The new edition came out in October of 2022 and has more up-to-date information on transformers and diffusion models. It also covers topics such as supervised and unsupervised learning, random forests, deep learning, natural language processing, and training and deploying Tensorflow models, among many more topics.</p><p>So, if you are interested, you can <a href="https://amzn.to/3Lpcak7">get it here</a> using my referral link. The price is the same to you, but I might get a commission.</p><p>One other thing I like about the book is that it includes an end-to-end machine learning project to learn the entire pipeline of a data scientist.</p><h3>XOR Neural Network</h3><p>I mentioned that we’ll be using an XOR neural network as an example. It should make things easier to follow. Below you can find a graphical representation of this network.</p><p>An <a href="https://en.wikipedia.org/wiki/XOR_gate">XOR logic gate</a> takes two inputs and returns a single output. Here is the truth table for this gate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*C49P9uLVE7cAqrYtubjTHA.png" /><figcaption>Truth table for an XOR logic gate</figcaption></figure><p>Therefore, we need a neural network with an input layer of two nodes and an output layer of one node. The hidden layer in between can technically be of any size, and there are different methods to decide on the best topology. For this example, we’ll just have three nodes in the hidden layer. Here is what the network looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JdhMxaEEoldJhqB6" /><figcaption>Fig. 1. Simple neural network with one hidden layer. The input layer has two nodes and the output layer has one. A network like this can be used to represent a logic gate, such as XOR. This diagram does not include bias nodes. The arrows represent data and the shapes represent operations.</figcaption></figure><p>The Python code to create this network, using our NeuralNet class from the previous post is:</p><pre>nnet = NeuralNet(topology=[2,3,1])</pre><p>You can find the new jupyter notebook for this post <a href="https://github.com/andresberejnoi/PublicNotebooks/blob/master/Neural%20Networks/Neural%20Network%20With%20Backpropagation.ipynb">here</a>.</p><h3>What Is Backpropagation?</h3><p>First of all, remember that I’m not a mathematician, so terms and fundamental concepts might get fuzzy here. The goal of backpropagation is to figure out the error throughout the network during the training phase and update the network weights to reduce that error.</p><p>First, we perform a feedforward propagation of inputs, which is when the network gives us a prediction. Check <a href="https://andresberejnoi.com/how-to-build-a-feedforward-neural-network-in-python/">my previous pos</a> t on how to implement that part. With the prediction in hand, we can compare the result we got to the true value, or target, that we want the network to return.</p><p>To train a network, we need a way to correct the parameters (weights) based on their error, so we can fine-tune them. For a simple network like in our example, we have 2*3 + 3*1 = 9 total parameters to adjust or &quot;train&quot;. Actually, once we account for bias nodes and their weights, the total number of parameters will be 3*3 + 4*1 = 13. I will explain bias nodes in more detail below.</p><p>Backpropagation allows us to assign blame to each of the weights by using the method of gradient descent.</p><h3>Gradient Descent</h3><p>The concept of gradient descent is based on the “gradient” from multivariate calculus. The gradient is a vector of the partial derivatives of a function. Gradient descent is an optimization method where we try to find the local minima of a function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*ESovxAtiSKJN_WaD" /><figcaption>Animation of the gradient descent algorithm from three different starting points as they converge to a local minima. Source: <a href="https://commons.wikimedia.org/wiki/File:Gradient_descent.gif">Wikimedia commons file by Jacopo Bertolotti</a>.</figcaption></figure><p>In calculus, we find the slope of a function by taking its derivative. The slope is the direction of the highest ascent for the function. So, the gradient is basically the slope of a function in higher dimensions.</p><p>Since we are trying to minimize the error between what our network predicted and the real values, we need to travel in the opposite direction to the gradient.</p><p>By the way, with NumPy, if you have a vector <strong>A</strong>, you can flip its direction by changing its sign:</p><pre>&gt;&gt;&gt; import numpy as np <br><br>&gt;&gt;&gt; A = np.array([-2,4.5,3]) <br><br>&gt;&gt;&gt; A <br>array([-2. , 4.5, 3. ]) <br><br>&gt;&gt;&gt; -A <br>array([ 2. , -4.5, -3. ])</pre><h3>Differentiable Activation Functions</h3><p>As I was saying above, gradient descent relies on taking the derivative of our activation function, so it makes it much easier when that function is differentiable. I talked about activation functions a bit more in my <a href="https://andresberejnoi.com/how-to-build-a-feedforward-neural-network-in-python/">previous post</a>. In this case, I will implement two custom functions that can return their own derivative.</p><h3>Hyperbolic Tangent or Tanh</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*X5eTxIzRJKDTrG38" /><figcaption>Fig. 2. This is an example of the hyperbolic tangent function with a range of x inputs from [-5, 5) to give an idea of its sigmoidal shape.</figcaption></figure><p>Fig. 2. shows the general shape of a tanh function centered at 0. The implementation in my notebook basically uses NumPy&#39;s np.tanh method but adds the option to compute the derivative:</p><pre>def tanh(x, derivative=False):<br>    if derivative:<br>        tanh_not_derivative = tanh(x)<br>        return 1.0 - tanh_not_derivative**2<br>    else:<br>        return np.tanh(x)</pre><p>When derivative=False, this custom tanh uses Numpy&#39;s np.tanh. However, when derivative=True, the function will return the derivative of tanh(x), which is simply 1 minus tanh(x) raised to the power of two:</p><pre>\frac{d}{dx}\tanh(\vec{x}) = 1 - \tanh^2(\vec{x})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*9D4NgKBWwMaaVqSRZrOLDg.jpeg" /></figure><h3>ReLU Activation Function</h3><p>A very popular activation function at this moment is the Rectified Linear Unit, or ReLU because of its computational simplicity. It is a composite function that returns 0 for any x &lt;= 0 and returns x for any x &gt; 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*wMZFfINovQOFyFUZ" /><figcaption>Fig. 3. Example of the shape for a ReLU activation function for inputs in the range [-5, 5). Notice how there is a break at x=0.</figcaption></figure><p>Numpy has a useful method, np.maximum to compare matrices element-wise against another matrix or scalar. We can use it to implement our vectorized ReLU function in Python:</p><pre>def relu(x, derivative=False):<br>    if derivative:<br>        return 1 * (x &gt; 0)  #returns 1 for any x &gt; 0, and 0 otherwise<br>     <br>    return np.maximum(0, x)</pre><p>When given an array and a scalar, np.maximum will compare each item in the array individually against the scalar, and return the bigger value.</p><p>The derivative for ReLU is easy to compute for the most part:</p><p>However, you may notice that ReLU is not differentiable when x = 0, so we need to handle that special case. We can either choose to give it a value of 0 or 1, and it seems the most common way is to assign 0 when x = 0 so that&#39;s what I did here.</p><p>Here is an example using it:</p><pre>&gt;&gt;&gt; import numpy as np <br><br>&gt;&gt;&gt; x = np.array([2, 4, 1, -0.3]) <br><br>&gt;&gt;&gt; x <br>array([ 2. , 4. , 1. , -0.3]) <br><br>&gt;&gt;&gt; relu(x) <br>array([2., 4., 1., 0.]) <br><br>&gt;&gt;&gt; relu([2, -1, 0.4, 0], derivative=True) <br>array([1, 0, 1, 0])</pre><h3>Adding Bias Nodes To The Neural Network</h3><p>One important component of neural networks, which I omitted in my last post is the concept of a bias node.</p><p>In neural networks, bias nodes are positioned at each layer but they are not affected by the nodes in the previous layer. They always output 1 and have their own weights, which need to be updated during backpropagation. Here is another diagram showing our example neural network, including bias nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F26tP_8RBPRNLG78" /><figcaption>Fig. 4. Enhanced diagram of a neural network showing bias nodes at the bottom. This diagram also breaks down the insides of individual neurons (the sketched colored circles) by showing two different operations on the data: aggregation of the inputs from the previous layer, and then a pass through the activation function. I made this diagram with <a href="https://www.diagrams.net/">diagrams.net</a>.</figcaption></figure><h3>Implementing Backpropagation in Python</h3><p>To implement this algorithm, I repurposed some old code I wrote for a Python package called <a href="https://github.com/andresberejnoi/NetBuilder">netbuilder</a> and adapted it for this post. There are four main new functions in the NeuralNet class: <strong>_gradient_descent()</strong>, <strong>backprop()</strong>, <strong>train()</strong>, and <strong>_train_helper()</strong>. I also had to modify a few things in <strong>feedforward()</strong> and <strong>__init__()</strong> so that everything works smoothly.</p><p>As mentioned earlier, backpropagation works by taking the derivatives of the error function to compute the gradients. Since the error function depends on all the network’s layers, we need to apply the chain rule and get the derivatives of the activation functions in each layer, going from the last to the first. Take a look at <a href="http://neuralnetworksanddeeplearning.com/chap2.html">this online resource</a> if you want some more theory on the different stages of the calculations. Alternatively, take a look at the <a href="https://amzn.to/3LsPNKg">O’Reilly book on machine learning</a> mentioned above for a hands-on implementation of different network types.</p><p>The basic steps for training the network are the following:</p><ul><li>Compute the derivative of the error function</li><li>Compute the derivative of the activation function for the final layer with respect to the layer inputs</li><li>Compute the delta for this layer by multiplying the derivative of the error function with the derivative of the activation function</li><li>Compute the gradient for the weight matrix by performing a dot product between the transpose of the inputs to the layer and the delta vector computed above.</li><li>Apply gradient descent:</li></ul><p>The change in weights is computed by the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*7ci3iEiJ7RyI4xqaq5H2nA.jpeg" /></figure><p>Similarly, the update to the bias weight matrices is computed like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*aAQV-E8fW469-CSai7Zkyw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*C73lVJIpoYq1j9wzUIyUgw.jpeg" /></figure><p>The term containing the momentum factor can be omitted.</p><p>Now, with the change in weights, we can update the original weight matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Kmye-i7T1q3A6ZeNQ0PBzg.jpeg" /></figure><p>The equations described above are implemented in the function <strong>_gradient_descent()</strong>. Check it out to follow along.</p><h3>The Backpropagation Code</h3><pre>class NeuralNet(...):<br>...<br>...<br>    def backprop(self, target, output, error_func,):<br>        #Compute gradients and deltas<br>        for i in range(self.size):<br>            back_index =self.size-1 -i                  # This will be used for the items to be accessed backwards<br> <br>            if i == 0:   #final layer<br>                d_activ = self.output_activation(self.netIns[back_index], derivative=True)<br>                d_error = error_func(target,output,derivative=True)<br>                delta   = d_error * d_activ<br>                #delta  = np.multiply(d_error, d_activ)<br> <br>                gradient_mat  = np.dot(self.netOuts[back_index].T , delta)<br>                bias_grad_mat = 1 * delta<br> <br>                #-- Apply gradient descent<br>                self._gradient_descent(layer_idx     = back_index, <br>                                       gradient_mat  = gradient_mat, <br>                                       bias_gradient = bias_grad_mat)</pre><p>The previous bullet points and the code above show how to compute the gradients for the output layer. For the rest of the layers, the process is not too different:</p><ul><li>Compute the derivative of the hidden activation function with respect to the layer inputs</li><li>The derivative for the error in this layer will be given by the dot product between the delta vector from the previous layer (a higher layer since we are going backward) and the transpose of the weight matrix for this layer</li><li>The new delta is the multiplication between the derivative of the activation function and the error computed above.</li><li>Compute the gradient matrix similarly to the step described for the output layer</li></ul><p>Here is that part of the code:</p><pre>...<br>else:     #hidden layers<br>    W_trans = self.weight_mats[back_index+1].T        #we use the transpose of the weights in the current layer<br>    d_activ = self.hidden_activation(self.netIns[back_index],derivative=True)  #δl=((wl+1)Tδl+1)⊙σ′(zl)<br>    d_error = np.dot(delta, W_trans)<br>    delta = d_error * d_activ   #this should be the hadamard product, <br> <br>    gradient_mat = np.dot(self.netOuts[back_index].T , delta)<br>    bias_grad_mat = 1 * delta<br> <br>    #-- Apply gradient descent<br>    self._gradient_descent(layer_idx     = back_index, <br>                           gradient_mat  = gradient_mat, <br>                           bias_gradient = bias_grad_mat)</pre><p>I separated the actual gradient descent code into its own function to keep the code easier to read. Here is <strong>_gradient_descent()</strong> and you can see how the equations above are implemented:</p><pre>def _gradient_descent(self, layer_idx, gradient_mat, bias_gradient):<br>         <br>    #-- Calculate the changes in weights for all nodes and bias weights<br>    delta_weight =   (self.momentum * self.last_change[layer_idx]) <br>                               - (self.learning_rate * gradient_mat[layer_idx])<br>     <br>    delta_bias_weights =  (self.momentum * self.last_bias_change[layer_idx]) \<br>                        - (self.learning_rate * bias_gradient)<br>     <br>    #-- Update Weights<br>    self.weight_mats[layer_idx] += delta_weight    #the negative of the gradient is above<br>    self.bias_mats[layer_idx]   += delta_bias_weights<br>     <br>    #-- Keep track of latest delta weights for next iteration/epoch to compute momentum term<br>    self.last_change[layer_idx]      = 1 * delta_weight<br>    self.last_bias_change[layer_idx] = 1 * delta_bias_weights</pre><h3>Training the Network</h3><p>The process to train the network is relatively simple once we have backpropagation implemented. It is just a matter of repeating the process over and over for a given number of iterations (epochs) or until the error is low enough. The full code can be found on the <a href="https://github.com/andresberejnoi/PublicNotebooks/blob/master/Neural%20Networks/Neural%20Network%20With%20Backpropagation.ipynb">notebook companion for this post</a>. I will just write the general pseudo-code here:</p><pre>def train(epochs, inputs, targets, error_threshold, ...):<br>    for i in range(epochs):<br>        network_output = feedforward(inputs)<br>        error = error_function(targets, network_output)<br>        backpropagation(targets, network_output, error_function)<br> <br>        if error &lt;= error_threshold:<br>            break</pre><p>The jupyter notebook includes training sets for other logic gates as well, but here is an example of network parameters that I tried for an XOR gate:</p><pre>#-Network parameters<br>m           = 0.9            #momentum<br>a           = 0.01           #learning rate<br>init_method = &#39;xavier&#39;       #weight initialization method<br>hidden_f    = tanh           #activation function for hidden layers<br>output_f    = tanh           #activation function for output layer<br>epochs      = 1000<br>batch_size  = 0<br>e_threshold = 1E-5           #error threshold to stop training<br> <br>network_topology = [2, 3, 1] #shape of the network and its layers<br> <br>input_data = np.array([[0,0], <br>                       [0,1], <br>                       [1,0], <br>                       [1,1]]) <br> <br>target_data = np.array([[0],<br>                        [1],<br>                        [1],<br>                        [0]])</pre><p>Now we create and train the neural network using the parameters we defined above:</p><pre>#-- create a new network for each set so they are independent of each other<br>nnet = NeuralNet(network_topology, hidden_activation_func=hidden_f, output_activation_func=output_f, init_method=init_method, momentum=m, learning_rate=a)<br>error = nnet.train(input_data, target_data, epochs=epochs, error_func=mean_squared_error, batch_size=batch_size, error_threshold=e_threshold)<br> <br># Test different inputs<br>print(f&quot;\n\n{&#39;=&#39;*40}\nTraining XOR gate:\n{&#39;=&#39;*40}\n&quot;)<br> <br>for i, sample in enumerate(input_data):<br>    output = nnet.feedforward(sample)<br>    sample_error = mean_squared_error(target_data[i:i+1], output)<br>    print(f&quot;Testing Network:\n\tinput vector    : {sample}\n\toutput vector   : {output}\n\texpected output : {target_data[i]}&quot;)<br>    print(f&quot;\tNetwork error   : {sample_error:.3e}\n&quot;)</pre><p>and the output after 1000 epochs is:</p><pre>========================================<br>Training XOR gate:<br>========================================<br> <br>Testing Network:<br>    input vector    : [0 0]<br>    output vector   : [[0.00094011]]<br>    expected output : [0]<br>    Network error   : 4.419e-07<br> <br>Testing Network:<br>    input vector    : [0 1]<br>    output vector   : [[0.96421877]]<br>    expected output : [1]<br>    Network error   : 6.401e-04<br> <br>Testing Network:<br>    input vector    : [1 0]<br>    output vector   : [[0.98864499]]<br>    expected output : [1]<br>    Network error   : 6.447e-05<br> <br>Testing Network:<br>    input vector    : [1 1]<br>    output vector   : [[0.00078335]]<br>    expected output : [0]<br>    Network error   : 3.068e-07</pre><h3>Wrapping Up</h3><p>Try to run the <a href="https://github.com/andresberejnoi/PublicNotebooks/blob/master/Neural%20Networks/Neural%20Network%20With%20Backpropagation.ipynb">example network in the notebook</a> and see what you get. The results won’t always be as good as the ones I got here. If you are getting far-off outputs, maybe try running the training method again, or increasing the number of epochs. You could also experiment with changing the network topology.</p><p>Let me know what you thought of this post and if there are any issues you find.</p><p>You can also subscribe to my YouTube channel for videos on Python projects, automation, and crypto:</p><p>Finally, if you want to stay connected and up to date on what I post, you can join my <a href="https://andresberejnoi.com/newsletter-landing-page/">newsletter here</a>. I want this newsletter to be a useful resource of tips and tricks I learn and also a place to talk about new projects I might work on.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/how-to-implement-backpropagation-with-numpy/"><em>https://andresberejnoi.com</em></a><em> on April 25, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7c14f2e683a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Great Books To Read This April — Andres Berejnoi]]></title>
            <link>https://medium.com/@andresberejnoi/3-great-books-to-read-this-april-andres-berejnoi-fa6b9842d30d?source=rss-70883f107800------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa6b9842d30d</guid>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[audiobooks]]></category>
            <category><![CDATA[book-recommendations]]></category>
            <category><![CDATA[readinglist]]></category>
            <category><![CDATA[reading]]></category>
            <dc:creator><![CDATA[Andrés Berejnoi]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 20:20:42 GMT</pubDate>
            <atom:updated>2023-07-06T19:24:53.945Z</atom:updated>
            <content:encoded><![CDATA[<h3>3 Great Books To Read This April — Andres Berejnoi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GqcdqZLiFFKjqfW_.jpeg" /></figure><p>In my last <a href="https://andresberejnoi.com/how-to-stop-procrastinating-and-become-productive/">life and productivity post</a>, I mentioned that I got into audiobooks.</p><p>I thought it would be a good to start a monthly list of books I have read or plan to read. Normally, after finishing a book, I write some notes about the main points I took away and things that I found interesting. I will share some of those notes here as well, as a way to provide an introduction to each book.</p><p>Please note that I mostly consume books in the form of audiobooks. Initially, I was not a fan of audiobooks, but as I mentioned in <a href="https://andresberejnoi.com/how-to-stop-procrastinating-and-become-productive/">my post</a>, they provide a good way to consume content faster, while allowing me to rest my eyes.</p><h3>Audible and Disclaimers</h3><p>I will include affiliate links to <a href="https://amzn.to/3XIjbRC">Audible</a> for all discussed books, and for ebook and physical formats when available. You will not be charged extra, and <a href="https://amzn.to/3XIjbRC">Audible</a> is likely to have the majority of books you want since it is the biggest audiobook platform.</p><p>When you buy a book from <a href="https://amzn.to/42O0s91">Au</a><a href="https://amzn.to/42O0s91">dible</a>, be sure to download and keep a local copy. That way, you own it like a physical book. If you only access it through the app, you rely on Audible for delivery. If they lose distribution rights for the book, you lose access. So, always download anything you purchase.</p><p>Sign up for a <a href="https://amzn.to/3XIjbRC">free Audible Premium Plus</a> membership trial and get one credit for a free audiobook. Even if you cancel the trial, you still get to keep the book you got from the promotion.</p><p>Another way to access the books I mention in this post is to check if they are available at your local library. This is certainly the cheapest option, but keep in mind that you may need to wait weeks to obtain them, and you will have a time limit to finish reading them (usually up to 14 days).</p><p>So, here are the books I want to share this month:</p><h4>“<a href="https://amzn.to/44cX1cx">When — The Scientific Secrets of Perfect Timing</a>” By Daniel H. Pink</h4><figure><img alt="Cover of the book: “When — The Scientific Secrets of Perfect Timing”" src="https://cdn-images-1.medium.com/max/500/0*Fi0v_TBqF7eb4iaN.jpg" /><figcaption>The audiobook is <a href="https://amzn.to/3U0KgNW">here</a>.</figcaption></figure><p>This book is full of useful life advice. Its main goal is to show how timing plays a crucial role in our lives. Timing is important at small scales, such as considering the best time of day to exercise, the best time to eat, or to take a break from work. The book also discusses studies that showed kids at schools perform and learn better when their classes start later in the day.</p><p>At the same time, the author also talks about the importance of timing for life decisions and career moves. For instance, people who graduate college during a recession tend to trail other professionals who graduated during bull markets in terms of salary and positions. The gap can be significant (I think I remember something like a 10-year gap). This difference can be due to less job switching during recessions because of fear.</p><p>The book has many examples that opened my mind, and even though I cannot explain them well here, it is a book I enjoyed very much.</p><p>Links:</p><ul><li><a href="https://amzn.to/3U0KgNW">Audiobo</a><a href="https://amzn.to/3U0KgNW">ok ver</a><a href="https://amzn.to/44cX1cx">sion</a></li><li><a href="https://amzn.to/3O1OZ0n">Ebook version</a></li><li><a href="https://amzn.to/44zX1mu">Hardcover version</a></li></ul><h4>“<a href="https://amzn.to/3NIFPEA">The Story of The Human Body: Evolution, Health, and Disease</a>” By Daniel E. Lieberman</h4><figure><img alt="Cover for the book: “The Story of the Human Body: Evolution, Health, and Disease”. The cover shows a human footprint across the title." src="https://cdn-images-1.medium.com/max/500/0*Rtw_mlgxU2Aitfbx.jpg" /><figcaption>One of my favorite books so far. Here is an <a href="https://amzn.to/3NIFPEA">Audible link</a> for it.</figcaption></figure><p>This has become one of my favorite books so far. The author tries to explain many of the diseases that are becoming prevalent in the modern era from an evolutionary perspective. It seems that our current lifestyle (especially modern western lifestyles) brings about all sorts of problems that our ancestors did not encounter.</p><p>The first part of the book explains how humans ended up having the bodies we have through evolution. This is a tale of the first Australopithecus groups and their evolution through time to the original hunter-gatherers. Evolution has forced our bodies to adapt to an environment where calories are hard to get, and there is a need to be physically active for longer.</p><p>For most of our history, humans did not have a surplus of energy. However, with modern highly-processed diets, common in western societies, most people have an overabundance of calories which leads to obesity and many health-related issues.</p><p>I think one of the book’s main goals is to show that a lot of the health issues we face today are preventable and come from our culture and lifestyle instead of evolution since for most of our existence as a species, we have been hunter-gatherers and not couch potatoes.</p><p>Random and interesting notes:</p><ul><li>There have been only approximately 600 generations of humans since agriculture became widespread. Humans have been hunter-gatherers for much longer. In fact, it is estimated that modern humans have been around for 10,000 generations. Moreover, the human genus as a whole has been around for about 100,000 generations.</li><li>Humans evolved to be generally active, so our bodies still expect that there won’t be much food around all the time. That’s the reason our bodies are so good at storing fat. It was a necessary trait to survive during times when food was scarce when hunting or gathering fruits and vegetables.</li><li>We cannot change our bone mass significantly once we are done growing. With exercise, we can maybe slow down the bone loss that occurs after 30 years of age. That’s why it is important that kids have active lifestyles. This will force their bodies to grow strong and thicker bones. Then, once they reach adulthood, they have a better starting point. The phrase used by the author is “no stress, no gain”.</li></ul><p>I have written longer notes on this book since I liked it so much. However, I don’t want to overextend this synopsis. In the coming days, I will create a separate page on this website for all the book notes I take.</p><p>Links:</p><ul><li><a href="https://amzn.to/3NIFPEA">Audiobook version</a></li><li><a href="https://amzn.to/3PSMrTs">Ebook version</a></li><li><a href="https://amzn.to/3O1kDuO">Hardcover version</a></li></ul><h4>“<a href="https://amzn.to/3D2KTij">Invisible Women — Data Bias in a World Designed for Men</a>” By Caroline Criado Perez</h4><figure><img alt="Cover for the book: “Invisible Women — Data Bias in a World Designed For Men”. The cover shows two rows of male and female stick figures standing side by side. However, the women figures are faded out while the male figures are in full bold color." src="https://cdn-images-1.medium.com/max/500/0*FqvBWHxT2buZf-xF.jpg" /><figcaption>You can find the audiobook <a href="https://amzn.to/3Gd4kXw">here</a>.</figcaption></figure><p>This was a very eye-opening book about the way women are often overlooked in design decisions, be it company decisions, or even urban planning.</p><p>The book shows that many decisions taken by those in power (often men) don’t take women’s perspectives into account. Those men in positions of power are often ignorant of women’s needs.</p><p>For those reasons, women need to become more prominent in all aspects of decision-making: high management positions, government, etc.</p><p>The book uses a data-driven approach to show examples of detrimental policies when women’s voices are not part of the decision-making process. The author also talks about the importance of collecting gender-segregated data for policy-making. For instance, many drugs and medical training are based on the average male body. There have been many cases in modern medicine when not accounting for the difference in women’s biology led to fatal consequences when using drugs designed for men. This book covers those issues as well.</p><p>Some important (and random) points I took from the book:</p><ul><li>Cities and companies need to start gathering gender-segregated data related to their policies. This will allow them to analyze their impact and effectiveness.</li><li>Investment in public transportation childcare is very beneficial to women</li><li>Women work more hours on average than men. However, this work is in many cases unpaid labor.</li><li>Separate bathrooms for men and women reduce the likelihood of rape (this especially applies to third-world countries and disaster-relief zones)</li></ul><p>The links are here:</p><ul><li><a href="https://amzn.to/3D2KTij">Audiobook version</a></li><li><a href="https://amzn.to/3NNthvY">Ebook version</a></li><li><a href="https://amzn.to/3XN5vEL">Hardcover version</a></li></ul><h3>Discussion and Conclusion</h3><p>Hopefully, you will enjoy these books as I have done. Let me know if you have read any of them and what you thought about them. Also, feel free to recommend other books so I can add them to my to-read list.</p><p>You can also subscribe to my YouTube channel for videos on Python projects, automation, and crypto:</p><ul><li><a href="https://www.youtube.com/andresberejnoi">https://www.youtube.com/andresberejnoi</a></li></ul><p>Finally, if you want to stay connected and up to date on what I post, you can join my <a href="https://andresberejnoi.com/newsletter-landing-page/">newsletter here</a>. I want this newsletter to be a useful resource of tips and tricks I learn and also a place to talk about new projects I might work on.</p><p><em>Originally published at </em><a href="https://andresberejnoi.com/3-great-books-to-read-this-april/"><em>https://andresberejnoi.com</em></a><em> on April 3, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa6b9842d30d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>