<?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 Dmytro Nikolaiev (Dimid) on Medium]]></title>
        <description><![CDATA[Stories by Dmytro Nikolaiev (Dimid) on Medium]]></description>
        <link>https://medium.com/@andimid?source=rss-97b5279dad26------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t5qnRU5yuGZWTfX18sOd8g.jpeg</url>
            <title>Stories by Dmytro Nikolaiev (Dimid) on Medium</title>
            <link>https://medium.com/@andimid?source=rss-97b5279dad26------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 15:55:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andimid/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[Using ChatGPT for Efficient Debugging]]></title>
            <link>https://medium.com/data-science/using-chatgpt-for-efficient-debugging-fc9e065b7856?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc9e065b7856</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 20:46:33 GMT</pubDate>
            <atom:updated>2023-06-22T20:46:33.959Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhance your debugging experience and learn faster with the power of Large Language Models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozBUD_OsH1dKkV1zivwYyg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/photo/elderly-man-thinking-while-looking-at-a-chessboard-8438918/">Pavel Danilyuk</a> on <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><p>It’s hard to deny that Large Language Models (LLMs) are making a profound impact on various industries and applications, revolutionizing the way we work and interact. Even though the initial hype around ChatGPT has calmed down since its release about six months ago (in November 2022), its influence remains significant. It seems that autoregressive LLMs will continue to be a part of our lives in the near future, and <strong>it is worth developing skills to interact with them</strong>, both as a developer and a user.</p><p>As <a href="https://huyenchip.com/2023/04/11/llm-engineering.html">Chip Huyen stated in her blog post</a>, <em>it is relatively easy to achieve something impressive with LLMs, but it is quite challenging to build something production-ready</em> considering the <a href="https://www.honeycomb.io/blog/hard-stuff-nobody-talks-about-llm">limitations and potential issues that LLMs currently have</a>. However, while the research and engineering community is actively working to address these challenges, it is worth acknowledging the fact that <strong>individuals can already benefit greatly from LLMs</strong>, at least using them as personal assistants for everyday non-critical tasks or as collaborators for brainstorming.</p><p>In my previous article, I discussed the <a href="https://towardsdatascience.com/summarising-best-practices-for-prompt-engineering-c5e86c483af4">best practices of prompt engineering</a>, providing insights to help you develop local LLMs-based applications. In this post, I will share a set of techniques that enable you to utilize models such as ChatGPT for <strong>effective code debugging</strong> and <strong>accelerated learning of programming</strong>. We will also take a look at the example prompts for writing and explaining code. These techniques will be valuable not only when interacting with ChatGPT but also when seeking assistance from your colleagues or even tackling programming challenges independently.</p><p>This article is primarily targeted toward beginners, so I tried to provide illustrative examples and explanations. I hope these techniques will assist you in understanding and troubleshooting code more efficiently.</p><h3>General Framework for Code Debugging</h3><p>In fact, ChatGPT has not made <strong>significant </strong>changes to the debugging process. The great thing is, now you can easily connect with a <em>virtual colleague</em> without worrying about being a bother or feeling hesitant to ask stupid questions! But the techniques that we will consider <strong>exist as long as software engineering exists</strong>, and therefore will be useful not only when interacting with LLMs, but also for a better understanding of the process and more effective interaction with coworkers.</p><p>To find a bug in your code, you only need two essential steps (there’s three actually):</p><ol><li><em>Isolate the bug and demonstrate it with the minimum amount of code</em>;</li><li><em>Make an assumption </em>about your error and test it;</li><li><em>Iterate </em>with more assumptions until you find a fix.</li></ol><p>While you can start using ChatGPT right away, it’s actually a better idea to begin by reproducing the error for a few reasons. First of all, it might be challenging to include all the related points and explain exactly what you’re trying to achieve within the context of the language model. Secondly, it will allow you to gain a better understanding of the issue and possibly find the error yourself. Let’s see.</p><blockquote>By the way, in this post I am using the vanilla version of ChatGPT (GPT-3.5), but for coding tasks, GPT-4 is typically more proficient.</blockquote><h4>Step 1: Isolate and Reproduce the Problem with the Minimum Amount of Code</h4><p>The first step is to reproduce the problem. As we know, the majority of issues can still be resolved with the classic <strong>“turn it off and on again”</strong>. It’s possible that you might have become tangled up with the code execution order in Jupyter Notebook.</p><p>If possible (and it typically is), it’s recommended to <strong>write new code that throws the same error and keep it as simple as possible</strong>.</p><p>Let’s consider the example of a TypeError: ‘int&#39; object is not iterable, which occurs when you try to iterate over some_integer instead of using the range(some_integer) construct.</p><p>Bad example: a function calls another function that then invokes a method of a class. At first glance, it may require some time to determine where the actual computation occurs, despite this being a relatively simple example. Similarly, for models, it becomes more challenging to <em>locate the relevant information among unrelated details</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fe06b4ece3b62b79fe69abef41ae5d3/href">https://medium.com/media/7fe06b4ece3b62b79fe69abef41ae5d3/href</a></iframe><p>Better example: get rid of the class by moving the functionality of do_some_work() function (which is causing the error) directly into the function we are calling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af71aa340d44a9557931c72e1072b2fc/href">https://medium.com/media/af71aa340d44a9557931c72e1072b2fc/href</a></iframe><p>Besides the fact that we still do a terrible job with the variable naming conventions (remember, <strong>variable names should be descriptive and meaningful!</strong>), this code is still easier to debug and understand.</p><p>Even better example: we can get rid of some_function() as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b87a00fd59868658b9e8ce894437f5/href">https://medium.com/media/b5b87a00fd59868658b9e8ce894437f5/href</a></iframe><p>Overall, we have shortened the code by more than half. Compare how much easier it is to find a bug in it.</p><p>In the context of pandas, for example, this principle can mean not using the original dataframe. Let’s consider a situation where we want to calculate the average salary for each position using our data and encounter a KeyError. Here is a bad example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff884460cc5311283d9ba260089160a2/href">https://medium.com/media/ff884460cc5311283d9ba260089160a2/href</a></iframe><p>First, we can’t be sure that the dataframe contains the data provided in the comments. Indeed, we only need two columns from it, and if we create a similar mini version, it will be much easier to understand that we simply misspelled the salary column (Salary vs salary).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8ea6ca9274bcae26335800226fcb376/href">https://medium.com/media/e8ea6ca9274bcae26335800226fcb376/href</a></iframe><blockquote>By the way, ChatGPT is quite good at <strong>generating dummy data</strong>, so it can be helpful here too!</blockquote><p>There are countless types of errors, and it’s impossible to list them all, of course. Overall, try to modify the code in such a way that <strong>it produces the same error</strong> as you encountered, but <strong>make it as easy as possible to understand quickly</strong>.</p><p>Due to the so-called “<a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging">rubber duck debugging</a>,” this step often helps you understand the cause of the problem on your own, without seeking external assistance. For example, if your mini-code doesn’t generate the same error, you’re already halfway toward finding a solution. However, even if it does, it’s still a positive outcome. :)</p><h4>Step 2: <em>Make an Assumption, Test It, and Iterate</em></h4><p>If you still can’t find a way to fix the error, it’s worth seeking assistance. But it’s helpful to have your own assumptions about what could be wrong.</p><h4>Find the Exact Line</h4><p>First, <strong>find the</strong> <strong>expression and the exact line of code</strong> that are causing the problem. You probably already know that it is inside the last line of the mini-code you wrote earlier.</p><p>Remember that <a href="https://realpython.com/python-traceback/#how-do-you-read-a-python-traceback">Python traceback</a> displays the <strong>error message</strong> <em>at the bottom</em> and the corresponding <strong>executed code</strong> <em>at the top</em> with internal functions’ calls in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1lJZ5DMK-e-vzincKsrWw.png" /><figcaption>Python traceback. Image by Author</figcaption></figure><p>This can be quite easy for straightforward bugs, but it can be more challenging when dealing with <em>logical errors</em> that don’t generate any error messages but result in unexpected outputs due to logical mistakes. In such cases, it’s helpful to observe the values step by step with a <em>debugger </em>or simple print() statements and define the line of code that doesn’t align with your expectations.</p><p>If the error is caused by a complex expression, such as df.groupby(‘Occupation’)[‘Address’].apply(lambda x: ‘, ‘.join(x)), you can first break it into parts and explore the output step by step, e.g. first run df.groupby(‘Occupation’), then df.groupby(‘Occupation’)[‘Address’], and so on.</p><h4>Think about Common Reasons</h4><p>After that, consider some common reasons for the error:</p><ul><li>Could it be that the necessary <strong>library is not installed</strong> or installed with the wrong version?</li><li>Maybe there’s a simple <strong>typo</strong> or <strong>syntax error</strong> somewhere?</li><li>Might it be that the error is related to <strong>data types</strong>, e.g. you sum a string and a number?</li><li>And so forth.</li></ul><h4>Ask ChatGPT</h4><p>If nothing comes to mind, it’s time to ask ChatGPT for assistance. Simple issues can often be resolved by simply pasting your code and asking <em>what’s wrong</em>. However, for more complex problems, you may need to provide additional relevant information. For instance, if you’re encountering a system error, it might be helpful to include the version of Python you’re using. Overall, try to always include the <strong>error message</strong> and <strong>describe what you’re trying to achieve</strong>. You may have to try several wordings, so don’t be afraid to experiment.</p><p>Situations can vary greatly, so let’s move on to some examples. First, let’s take a look at the pandas KeyError we encountered earlier.</p><p>Sample prompt:</p><pre>This Python code results in &lt;error&gt; in &lt;this line&gt;.<br><br>```<br>Insert your code here<br>```<br><br>Tell me how to debug the code to solve the given error.</pre><p>Example:</p><pre>This Python code results in KeyError: &#39;Column not found: salary&#39; <br>in the last line.<br><br>```<br>import pandas as pd<br><br>df = pd.DataFrame({<br>    &#39;Occupation&#39;: [&#39;Engineer&#39;, &#39;Doctor&#39;, &#39;Engineer&#39;],<br>    &#39;Salary&#39;: [56056, 61304, 86850],<br>})<br><br>average_salary_per_occupation = df.groupby(&#39;Occupation&#39;)[&#39;salary&#39;].mean()<br>```<br><br>Tell me how to debug the code to solve the given error.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*8WJg6JP8oBxAa_ESM9UBWw.jpeg" /><figcaption>Output for a debugging pandas example. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>Looks good! Let’s see a more challenging example with a logical error.</p><p>Sample prompt:</p><pre>This Python code &lt;does this, but I want it to do this&gt;.<br><br>```<br>Insert your code here<br>```<br><br>Tell me how to fix the code to solve the problem.</pre><p>Example:</p><pre>This Python code trains a random forest classifier on the Iris dataset.<br>As far as I know, the dataset is relatively simple and I expect <br>the classifier to make the perfect predictions,<br>however, I am getting about 95% accuracy even with 100 trees in the forest.<br>Are these results reasonable for this situation?<br><br>```<br>from sklearn.datasets import load_iris<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score<br>from sklearn.model_selection import train_test_split, GridSearchCV<br><br># load the Iris dataset<br>iris = load_iris()<br>X = iris.data<br>y = iris.target<br><br># split the data<br>X_test, X_train, y_test, y_train = train_test_split(<br>    X, y, test_size=0.2, random_state=42)<br>X_train, X_val, y_train, y_val = train_test_split(<br>    X_train, y_train, test_size=0.2, random_state=42)<br><br>param_grid = {<br>    &#39;n_estimators&#39;: [3, 7, 15, 25, 50, 100]<br>}<br><br># create a random forest classifier and <br># use grid search to find the best number of trees<br>rf_classifier = RandomForestClassifier()<br>grid_search = GridSearchCV(estimator=rf_classifier, <br>                           param_grid=param_grid, cv=5)<br>grid_search.fit(X_train, y_train)<br><br># get the best estimator from grid search and test it<br>best_rf = grid_search.best_estimator_<br>y_pred = best_rf.predict(X_test)<br>test_accuracy = accuracy_score(y_test, y_pred)<br>print(&quot;Test accuracy:&quot;, test_accuracy)<br><br># get the best number of trees from the grid search<br>best_n_estimators = grid_search.best_params_[&#39;n_estimators&#39;]<br>print(&quot;Best number of trees:&quot;, best_n_estimators)<br>```<br><br>Tell me how to fix the code to solve the problem if there is a problem.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBMDbZl-HD4hxK2acV7OVQ.jpeg" /><figcaption>Output for a debugging sklearn example. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>The model was able to find the hidden problem and fix it. Great!</p><p>Since ChatGPT remembers your previous messages, the <em>possibilities opening here are endless</em>. You can ask it to explain some concepts you’re having trouble understanding, suggest alternative solutions, translate code from one language to another, and so on.</p><p>Moreover, since ChatGPT can understand the code, it can also write it.</p><h3>Use ChatGPT to Write and Explain Code</h3><p>In this section, we will explore a couple of tricks that can be used when coding with ChatGPT. But first, I think it is important to remember that before the emergence of ChatGPT, <strong>Google </strong>was the primary tool for software developers.</p><p>And I think it’s important to <em>not forget how to use Google</em>, for various reasons. In the end, with Google you can probably do everything you can do with ChatGPT (in coding settings), it just might be slower. Although, when it comes to specific tasks like creating a diagonal matrix with numpy, I would likely do it faster using Google.</p><blockquote>I think the fitting analogy is the process of learning a foreign language (although one can say that you are doing exactly that by learning a <strong>programming </strong>language :). Using Google is translating <strong>individual words</strong> using a vocabulary while utilizing ChatGPT is akin to <strong>translating entire sentences and paragraphs of text</strong> using online translators. While ChatGPT can be incredibly powerful, you may face challenges in identifying hidden errors or understanding certain code blocks, especially as a beginner.</blockquote><blockquote>Given the immense capabilities of ChatGPT, it can be employed in various ways. I advise you to use it for <strong>generating short code snippets</strong> — acting as a dictionary for idioms or stable expressions. Making sure you have a solid understanding of the generated code is essential because it can help prevent future troubles and complications.</blockquote><blockquote>So, use ChatGPT, but remember to google things as well! <br><a href="https://codeeasy.io/blog/how-to-effectively-google-as-a-software-devel">This article</a> offers some valuable tips on effective googling for software developers.</blockquote><h4>Write</h4><p>One technique that is helpful in these situations is called <a href="https://learnprompting.org/docs/basics/roles">role prompting</a>. Instead of simply asking the model to generate code, you can ask it to write code <em>by being a junior developer</em>, for instance. By assuming this role, the model is more likely to produce code comprehensible to beginners and avoid overly complex constructs.</p><p>Sample prompt:</p><pre>Act like a junior Python developer.<br>Write code with comments explaining what is going on.<br>When providing the solution, ensure the output is well-formatted<br>and the code is well-documented.<br>Include example usage and explanations.<br><br>&lt;Describe your problem here&gt;</pre><p>Example:</p><pre>Act like a junior Python developer.<br>Write code with comments explaining what is going on.<br>When providing the solution, ensure the output is well-formatted<br>and the code is well-documented.<br>Include example usage and explanations.<br><br>Write a program to find common values between two numpy arrays.<br>It is a function that takes two numpy arrays as inputs and<br>output a numpy array.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1okNIm52EokEIvlv0wF6g.jpeg" /><figcaption>Output for a code generation prompt. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>In this example, ChatGPT did a pretty good job following all of our instructions, including examples and detailed explanations.</p><p>Don’t forget to compare the code with your initial assumptions and draw conclusions that will allow you not to make such a request in the future.</p><p>In general, remember that LLMs have no prior knowledge about you or the specific problem you’re facing, so the more information you provide, the better output you’ll get:</p><ul><li><strong>Describe your task</strong>;</li><li><strong>Define code structure</strong>: e.g. it is full script, class, or function;</li><li><strong>Specify inputs and outputs</strong>: e.g. the function takes two integer arguments and outputs float;</li><li><strong>Mention tools/libraries</strong> you want to use, such as numpy or pandas, as well as a programming language;</li><li>If feasible, <strong>add your suggestions</strong> on what the solution might look like: e.g. I suggest using the pandas.DataFrame.groupby function to calculate the average salary by position.</li></ul><h4>Optimize</h4><p>If we previously asked the model to behave like a junior developer, we want it to be stronger in programming for tasks such as code optimization.</p><blockquote>By the way, you can use the same role prompting trick for debugging as well.</blockquote><p>Sample prompt:</p><pre>Act like an experienced Python developer mentoring a junior developer.<br>Provide explanations and comments about the concepts that can be<br>hard for beginners. Use Python best practices and write docstrings.<br><br>Rewrite the above Python code and optimize it.<br><br>```<br>Insert your code here<br>```</pre><p>Example:</p><pre>Act like an experienced Python developer mentoring a junior developer.<br>Provide explanations and comments about the concepts that can be<br>hard for beginners. Use Python best practices and write docstrings.<br><br>Rewrite the above Python code and optimize it.<br><br>```<br>def unique_list(l):<br>    # Get a list of distinct elements from the given list<br><br>    x = []<br>    for a in l:<br>        if a not in x:<br>            x.append(a)<br>    return x<br>```</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCnYTw41X9T_HEVbfYLezA.jpeg" /><figcaption>Output for a code optimization prompt. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>Here, to extract unique elements from the list, ChatGPT suggests using the set datatype (that does not allow duplicate values by definition), instead of a for loop. A good choice, since it’s basically a one-line solution.</p><h4>Explain</h4><p>We can use the same notation requesting comments and code explanations. Often this tends to output redundant comments, like import numpy as np # importing numpy library. However, this can still be useful at the start of your journey, and help the model to <em>express its internal thoughts</em> as discussed in the <a href="https://learnprompting.org/docs/intermediate/chain_of_thought">Chain-of-Thought reasoning</a> section in <a href="https://towardsdatascience.com/summarising-best-practices-for-prompt-engineering-c5e86c483af4">my previous article</a>.</p><p>Sample prompt:</p><pre>Act like an experienced Python developer mentoring a junior developer.<br>Provide explanations and comments about the concepts that can be<br>hard for beginners. <br><br>Explain and comment the following code.<br><br>```<br>Insert your code here<br>```</pre><p>Example:</p><pre>Act like an experienced Python developer mentoring a junior developer.<br>Provide explanations and comments about the concepts that can be<br>hard for beginners. <br><br>Explain and comment the following code.<br><br>```<br>def func(n):<br>    trow = [1]<br>    y = [0]<br>    for x in range(max(n, 0)):<br>        print(trow)<br>        trow = [l + r for l, r in zip(trow + y, y + trow)]<br>    return n &gt;= 1<br><br>func(6)<br>```</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uII3vBoGt4e4AY-verh-BQ.jpeg" /><figcaption>Output for a code explanation prompt. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>Here, the model was able to identify the task behind this code: generate rows of <a href="https://en.wikipedia.org/wiki/Pascal%27s_triangle">Pascal’s triangle</a>. Good job!</p><p>While there are numerous useful applications for ChatGPT you can come up with, it’s important to note that it may not always be able to solve every problem you encounter. It’s worth discussing this aspect further.</p><h3>Few Notes about Potential Pitfalls</h3><p>While ChatGPT can be very useful and perform various tasks, it is important to keep in mind the potential drawbacks which can be tricky.</p><h4>As Autoregressive LLM, ChatGPT is not Deterministic …</h4><p>ChatGPT is an example of a Large Language Model, and current Large Language Models are <strong>autoregressive</strong>, meaning that <em>they are trained to predict the next token in a sequence</em>. The output of a model is a probability distribution across all possible tokens, and we sample the final text from this distribution token by token. As a result, the sampling process is <strong>non-deterministic</strong>, meaning that <em>you can have different outputs for the same input </em>due to probabilistic reasons.</p><p>To illustrate this, we can imagine the sampling process as a tree. Here the initial sentence is shown in blue, selected tokens are shown in green, and non-selected ones are represented in red (without their further evolution). The probabilities are picked randomly just for illustration reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1U08HejXsNtyQ6aRlvMpiQ.png" /><figcaption>Simplified visualization of the sampling process for LLM. Image by Author</figcaption></figure><p>The input sequence is: “<em>My name is</em>” and ChatGPT completes it with “<em>ChatGPT, pleased to assist you!</em>”. This is an example from <a href="https://towardsdatascience.com/behind-the-millions-estimating-the-scale-of-large-language-models-97bd7287fb6b">my previous article</a>, where I discuss the basics of LLMs.</p><h4>… and That’s Why ChatGPT can be Wrong</h4><p>In practice, this means that you can get suboptimal output just because you got some rare unlikely tokens at the start. As a result, <strong>you may need several runs of the same input</strong> to examine the different outputs and select the most suitable one or even <em>combine different parts from different outputs</em>.</p><p>Additionally, it’s important to highlight that modern language models, especially GPT-4, possess impressive <em>self-correction capabilities</em>. If the generated code contains errors, you can simply return it and indicate that it is not functioning correctly. GPT-4 is adept at <strong>debugging its own code</strong> and offering relevant suggestions. You’ll often be able to obtain the correct code after a couple of iterations.</p><h4>Overconfidence</h4><p>Despite the fact that LLMs can sometimes provide incorrect outputs, they have been trained to prioritize accuracy. This can make their <strong>output appear very convincing, even when it is incorrect</strong>. As a result, identifying hidden errors can be challenging because the model often cannot explicitly say <em>“I need more information”</em>, although ongoing research is actively exploring ways to address this limitation.</p><p>In this sense, using ChatGPT for generating <strong>small snippets of code</strong> to solve specific tasks, as I mentioned earlier when referring to Googling, can be safer. It is essential to ensure that you have a solid understanding of the code you receive which allow you to navigate potential pitfalls effectively.</p><h3>Conclusion</h3><p>In this article, we have explored methods that can assist you in debugging, not only with ChatGPT but also with yourself.</p><p>By <strong>isolating</strong> the problem and <strong>rewriting it in minimal lines of code</strong>, you are likely to gain insights into the underlying issue. Or let ChatGPT help you by providing <strong>complete information about what is happening</strong>, making assumptions, and experimenting.</p><p>You can also utilize ChatGPT for tasks such as writing, optimizing, or explaining code, as we discussed in the example of role prompting. The other code-related applications are endless and include creating dummy data, writing tests, generating documentation, and more.</p><p>But remember the limitations of LLMs, as they can introduce hidden problems. Due to their autoregressive nature, LLMs <strong>can be wrong while appearing confident</strong>, which may require asking more questions or running multiple iterations to select the best output.</p><p>Wishing you the best of luck on your learning journey!</p><h3>Resources</h3><blockquote>Check out <a href="https://realpython.com/chatgpt-coding-mentor-python/">this article</a> for a broader guide of making ChatGPT your personal coding mentor.</blockquote><p>Here are my other articles about LLMs that may be useful to you. I have already covered:</p><ul><li><a href="https://towardsdatascience.com/behind-the-millions-estimating-the-scale-of-large-language-models-97bd7287fb6b">Estimating the Scale of Large Language Models</a>: what are LLMs, how are they trained, and how much data and compute do they need;</li><li><a href="https://towardsdatascience.com/summarising-best-practices-for-prompt-engineering-c5e86c483af4">Best Practices for Prompt Engineering</a>: how to apply prompt engineering techniques to interact with LLMs effectively and how to build local LLM-based applications with OpenAI API and Streamlit.</li></ul><p>You can be also interested in:</p><ul><li>Free <a href="https://learnprompting.org/">Learn Prompting course</a> to gain a deeper understanding of prompting and various techniques associated with it;</li><li>Recently released <a href="https://www.deeplearning.ai/short-courses/">short courses by DeepLearning.AI</a> to build applications with OpenAI API.</li></ul><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc9e065b7856" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-chatgpt-for-efficient-debugging-fc9e065b7856">Using ChatGPT for Efficient Debugging</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summarising Best Practices for Prompt Engineering]]></title>
            <link>https://medium.com/data-science/summarising-best-practices-for-prompt-engineering-c5e86c483af4?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5e86c483af4</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Mon, 29 May 2023 00:48:51 GMT</pubDate>
            <atom:updated>2023-06-22T21:57:38.017Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to build your own LLM-based application using OpenAI API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*jtQT-m5tMZJgAEWq" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/photos/RLw-UC03Gwc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Prompt engineering refers to the process of creating instructions called <em>prompts </em>for Large Language Models (LLMs), such as OpenAI’s ChatGPT. With the immense potential of LLMs to solve a wide range of tasks, leveraging prompt engineering can empower us to save significant time and facilitate the development of impressive applications. It holds the key to <strong>unleashing the full capabilities</strong> of these huge models, transforming how we interact and benefit from them.</p><p>In this article, I tried to summarize the best practices of prompt engineering to help you build LLM-based applications faster. While the field is developing very rapidly, the following “time-tested” :) techniques tend to work well and allow you to achieve fantastic results. In particular, we will cover:</p><ul><li>The concept of <strong>iterative prompt development</strong>, using separators and structural output;</li><li><strong>Chain-of-Thoughts</strong> reasoning;</li><li><strong>Few-shot learning</strong>.</li></ul><p>Together with intuitive explanations, I’ll share both hands-on examples and resources for future investigation.</p><p>Then we’ll explore how you can build a simple LLM-based application for local use using <a href="https://platform.openai.com/docs/introduction">OpenAI API</a> for free. We will use Python to describe the logic and <a href="https://streamlit.io/">Streamlit library</a> to build the web interface.</p><p>Let’s start!</p><h3>Best Practices for Prompt Engineering</h3><p>In this article, I will interact with ChatGPT through both the web interface and API. The gpt-3.5-turbo model I’ll use is the one behind ChatGPT, so you can experiment with your prompts right in the browser.</p><blockquote>One important thing to note here is that ChatGPT is not only LLM; as you probably know, it’s also a SFT (Supervised Fine-Tuning) model that was further finetuned with <a href="https://huyenchip.com/2023/05/02/rlhf.html">Reinforcement Learning from Human Feedback (RLHF)</a>. While many developers currently utilize OpenAI’s models for experimental projects and personal exploration, there are other models that may be more appropriate for deployment in production settings within large corporations due to privacy and other reasons.</blockquote><blockquote>If you want to know why base models (such as <a href="https://en.wikipedia.org/wiki/GPT-3">GPT-3</a>, <a href="https://arxiv.org/abs/2203.15556">Chinchilla</a>, <a href="https://ai.facebook.com/blog/large-language-model-llama-meta-ai/">LLaMA</a>) do not function in the same way as fine-tuned and RLHF-trained assistants (e.g., <a href="https://openai.com/blog/chatgpt">ChatGPT</a>, <a href="https://bair.berkeley.edu/blog/2023/04/03/koala/">Koala</a>, <a href="https://crfm.stanford.edu/2023/03/13/alpaca.html">Alpaca</a>), there is <a href="https://build.microsoft.com/en-US/sessions/db3f4859-cd30-4445-a0cd-553c3304f8e2">a talk by Andrej Karpathy about training and using GPT-like models</a>. I highly recommend checking it out for a deeper understanding, and it is just 40 minutes long. For a summary, take a look at <a href="https://threadreaderapp.com/thread/1661236778458832896.html">this Twitter thread</a>.</blockquote><p>Now let’s dive into best practices for prompting instruction-tuned LLMs!</p><h4>Iterative Prompt Development</h4><p>Just as any machine learning model is built through an <em>iterative process</em>, effective prompts are also constructed through a similar iterative approach. Even the most talented developer may not create the perfect prompt on their first attempt, so be prepared for the reality that you may need <em>dozens </em>of attempts to achieve the desired goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*4_nu0NojaqGGK93p" /><figcaption>Building data-based applications is always an iterative process. <a href="https://commons.wikimedia.org/wiki/File:CRISP-DM_Process_Diagram.png">Public domain</a></figcaption></figure><p>It’s always better to understand things through examples. Let’s start building a <strong>system to extract information from a job description</strong>. The sample job description we’ll be using in the examples is the following Machine Learning Engineer job posting from LinkedIn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*ehVX6aTCrA2L3acBJA1LjA.jpeg" /><figcaption>Sample job description. Screenshot of the <a href="https://www.linkedin.com/jobs/">LinkedIn job page</a></figcaption></figure><p>The initial prompt can be as simple as asking the model to extract specific information. Additionally, I’ll use delimiters (you can learn more about it in the <a href="https://www.deeplearning.ai/short-courses/chatgpt-prompt-engineering-for-developers/">ChatGPT Prompt Engineering for Developers course</a> I will mention later). While it’s unlikely that a local application would be susceptible to <a href="https://learnprompting.org/docs/prompt_hacking/injection">prompt injection attacks</a>, it’s just good practice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b0d44673b7f1ad7b8e637e2dab79386/href">https://medium.com/media/7b0d44673b7f1ad7b8e637e2dab79386/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*qm0i3MfCjRnZdMGFVoBsFA.jpeg" /><figcaption>Output for a prompt v1. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>Hmm, that’s not very helpful. We need to be more specific about what we want from the model. Let’s ask it to extract the job title, company name, key skills required, and a summarized job description.</p><blockquote>Remember that this is just an example, and you can design your prompts to extract as much information as you want: degree, years of experience required, location, etc.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac34056f660949ab7483b67f19064122/href">https://medium.com/media/ac34056f660949ab7483b67f19064122/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*8vN87onK5p4USA0UEgoHlw.jpeg" /><figcaption>Output for a prompt v2. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>Looking better! To make the output more compact and concise, let’s ask the model to output skills as a list and a more brief summary of the job description.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f10ef7b2cba58b4fd19c126572a3c7cb/href">https://medium.com/media/f10ef7b2cba58b4fd19c126572a3c7cb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*q4NzU3MM5VT6lvDSZcwxJQ.jpeg" /><figcaption>Output for a prompt v3. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>It’s a significant improvement from our initial attempt, isn’t it? And we accomplish this in just two iterations! So, don’t lose hope when things don’t go smoothly initially. Keep guiding the model, experiment, and you’ll certainly achieve success.</p><h4>Asking for a Structural Output</h4><p>The second point I would like to discuss is asking the model to output results in some expected structural format. While it may not be as critical for interacting with LLM through the web interface (e.g. as we do with ChatGPT), it becomes <strong>extremely useful for LLM-based applications</strong> since the process of parsing the results is much easier.</p><p>One common practice is to use formats like JSON or XML and define specific keys to organize output data. Let’s modify our prompt to show the model expected JSON structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71f654a137293c45d127ade09f094356/href">https://medium.com/media/71f654a137293c45d127ade09f094356/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*nGadBkrTyMq5kA6nhyg1aw.jpeg" /><figcaption>Output for a prompt v4, asking for JSON output. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>Such output is much easier to parse and process in the following logic of your application.</p><p>It’s worth saying a few words about the development of this direction. Some tools are aiming to strictly fit the model’s output into a given format, which can be extremely useful for some tasks. Just look at the examples below!</p><p>One of the possible applications is the generation of a large amount of content in a specific format (e.g. game characters information using <a href="https://github.com/microsoft/guidance">guidance</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kg15x9jv5IDXo-n-7YsA4A.gif" /><figcaption>Generating game character info in JSON. Gif from <a href="https://github.com/microsoft/guidance">guidance GitHub repo</a></figcaption></figure><p>Languages like <a href="https://lmql.ai/">LMQL</a> bring a programming-like approach to prompting language models. As these tools continue to evolve and improve, they have the potential to revolutionize how we interact with LLMs, resulting in more accurate and structured responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9yIH9ZHsTVsE7EGpk2vGA.jpeg" /><figcaption>LMQL query example. Screenshot of the <a href="https://lmql.ai/">LMQL webpage, see more examples here</a></figcaption></figure><h4>Chain-of-Thought Reasoning</h4><p>Chain-of-Thought (CoT) reasoning was discovered to be very helpful for tasks that require… well, reasoning. So if you have the opportunity to solve the task by breaking it into multiple simpler steps that can be a great approach for LLM.</p><p>Take a look at the example from the original paper. By splitting the problem into smaller steps and providing explicit instructions, we can assist the model in producing correct outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2svep4ve9BTZd57YmKBSRg.jpeg" /><figcaption>Introducing CoT prompting. Figure 1 from the <a href="https://arxiv.org/pdf/2201.11903.pdf">Chain-of-Thought Prompting Elicits Reasoning in LLMs paper</a></figcaption></figure><p>Interestingly, it emerges later that appending a straightforward and <em>magic </em><strong>“let’s think step by step”</strong> at the end of a prompt can improve results — this technique is known as <em>zero-shot CoT</em>. So, compose prompts that allow the model to “think out loud” since it does not have any other ability to express thoughts other than generate tokens.</p><p>The best zero-shot CoT prompt so far is “<strong>Let’s work this out in a step by step way to be sure we have the right answer</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5vo13xeAIYXH-BKCRMeaw.jpeg" /><figcaption>Best zero-shot prompts. Table 7 from the <a href="https://arxiv.org/pdf/2211.01910.pdf">LLMs Are Human-Level Prompt Engineers paper</a></figcaption></figure><p>More sophisticated approaches to solving even more complex tasks are now being actively developed. While they significantly outperform in some scenarios, their practical usage remains somewhat limited. I will mention two such techniques: <em>self-consistency</em> and the <em>Tree of Thoughts</em>.</p><p>The authors of the <a href="https://arxiv.org/pdf/2203.11171.pdf">self-consistency paper</a> offered the following approach. Instead of just relying on the initial model output, they suggested sampling multiple times and aggregating the results through majority voting. By relying on both intuition and the success of <a href="https://en.wikipedia.org/wiki/Ensemble_learning">ensembles</a> in classical machine learning, this technique enhances the model’s robustness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-dli4UWNDVQorKurMjtLg.png" /><figcaption>Self-consistency. Figure 1 from the <a href="https://arxiv.org/pdf/2203.11171.pdf">Self-Consistency Improves CoT Reasoning in Language Models paper</a></figcaption></figure><p>You can also apply self-consistency without implementing the aggregation step. For tasks with short outputs ask the model to <strong>suggest several options</strong> and choose the best one.</p><p>Tree of Thoughts (ToT) takes this concept a stride further. It puts forward the idea of applying tree-search algorithms for the model’s “reasoning thoughts”, essentially backtracking when it stumbles upon poor assumptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxnKEx0jSbGHxDUXPGH9RQ.png" /><figcaption>Tree of Thoughts. Figure 1 from the <a href="https://arxiv.org/pdf/2305.10601.pdf">Tree of Thoughts: Deliberate Problem Solving with LLMs paper</a></figcaption></figure><blockquote>If you are interested, check out <a href="https://www.youtube.com/watch?v=ut5kp56wW_4">Yannic Kilcher’s video with a ToT paper review</a>.</blockquote><p>For our particular scenario, utilizing Chain-of-Thought reasoning is not necessary, yet we can prompt the model to tackle the summarization task in two phases. Initially, it can condense the entire job description, and then summarize the derived summary with a focus on job responsibilities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/224cb693b7f0d8cdc102019fc75239b2/href">https://medium.com/media/224cb693b7f0d8cdc102019fc75239b2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*Tu9_m5lG6SXCzd91xLOAuQ.jpeg" /><figcaption>Output for a prompt v5, containing step-by-step instructions. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>In this particular example, the results did not show significant changes, but this approach works very well for most tasks.</p><h4>Few-shot Learning</h4><p>The last technique we will cover is called <em>few-shot learning</em>, also known as <em>in-context learning</em>. It’s as simple as incorporating several examples into your prompt to provide the model with a clearer picture of your task.</p><p>These examples should not only be <strong>relevant </strong>to your task but also <strong>diverse </strong>to encapsulate the variety in your data. “Labeling” data for few-shot learning might be a bit more challenging when you’re using CoT, particularly if your pipeline has many steps or your inputs are long. However, typically, the results make it worth the effort. Also, keep in mind that labeling a few examples is far less expensive than labeling an entire training/testing set as in traditional ML model development.</p><p>If we add an example to our prompt, it will understand the requirements even better. For instance, if we demonstrate that we’d prefer the final summary in bullet-point format, the model will mirror our template.</p><p>This prompt is quite overwhelming, but don’t be afraid: it is just a previous prompt (v5) and one labeled example with another job description in the For example: &#39;input description&#39; -&gt; &#39;output JSON&#39; format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83da9d216664cb185e18add912815689/href">https://medium.com/media/83da9d216664cb185e18add912815689/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*7_iJmQMAYlfxLkO-dzEY-g.jpeg" /><figcaption>Output for a prompt v6, containing an example. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><h4>Summarizing Best Practices</h4><p>To summarize the best practices for prompt engineering, consider the following:</p><ul><li><strong>Don’t be afraid to experiment</strong>. Try different approaches and iterate gradually, correcting the model and taking small steps at a time;</li><li><strong>Use separators</strong> in input (e.g. &lt;&gt;) and ask for a <strong>structured output</strong> (e.g. JSON);</li><li><strong>Provide a list of actions to complete the task</strong>. Whenever feasible, offer the model a set of actions and let it output its “internal thoughts”;</li><li>In case of short outputs <strong>ask for multiple suggestions</strong>;</li><li><strong>Provide examples</strong>. If possible, show the model several diverse examples that represent your data with the desired output.</li></ul><p>I would say that this framework offers a sufficient basis for automating a wide range of day-to-day tasks, like information extraction, summarization, text generation such as emails, etc. However, in a production environment, it is still possible to further optimize models by <a href="https://magazine.sebastianraschka.com/p/finetuning-large-language-models">fine-tuning them</a> on specific datasets to further enhance performance. Additionally, there is rapid development in the <a href="https://openai.com/blog/chatgpt-plugins">plugins</a> and <a href="https://www.pinecone.io/learn/langchain-agents/">agents</a>, but that’s a whole different story altogether.</p><h4>Prompt Engineering Course by DeepLearning.AI and OpenAI</h4><p>Along with the earlier-mentioned <a href="https://build.microsoft.com/en-US/sessions/db3f4859-cd30-4445-a0cd-553c3304f8e2">talk by Andrej Karpathy</a>, this blog post draws its inspiration from the <a href="https://www.deeplearning.ai/short-courses/chatgpt-prompt-engineering-for-developers/">ChatGPT Prompt Engineering for Developers course by DeepLearning.AI and OpenAI</a>. It’s absolutely free, takes just a couple of hours to complete, and, my personal favorite, it enables you to experiment with the OpenAI API without even signing up!</p><p>That’s a great playground for experimenting, so definitely check it out.</p><h3>Building the LLM-based Application with OpenAI API and Streamlit</h3><p>Wow, we covered quite a lot of information! Now, let’s move forward and start building the application using the knowledge we have gained.</p><h4>Generating OpenAI Key</h4><p>To get started, you’ll need to register an OpenAI account and create your API key. <a href="https://openai.com/pricing#:~:text=Simple%20and%20flexible-,Start%20for%20free,-Start%20experimenting%20with">OpenAI currently offers <strong>$5 of free credit for 3 months</strong></a> to every individual. Follow the <a href="https://platform.openai.com/docs/api-reference/introduction">introduction to the OpenAI API</a> page to register your account and <a href="https://platform.openai.com/docs/api-reference/introduction">generate your API key</a>.</p><p>Once you have a key, create an OPENAI_API_KEY <a href="https://www.twilio.com/blog/how-to-set-environment-variables-html">environment variable</a> to access it in the code with os.getenv(&#39;OPENAI_API_KEY&#39;).</p><h4>Estimating the Costs with Tokenizer Playground</h4><p>At this stage, you might be curious about how much you can do with just a free trial and what options are available after the initial three months. It’s a pretty good question to ask, especially when you consider that <a href="https://medium.com/towards-data-science/behind-the-millions-estimating-the-scale-of-large-language-models-97bd7287fb6b">LLMs cost millions of dollars</a>!</p><p>Of course, these millions are about training. It turns out that the inference requests are quite affordable. While GPT-4 may be perceived as expensive (although the price is likely to decrease), gpt-3.5-turbo (the model behind default ChatGPT) is still sufficient for the majority of tasks. In fact, OpenAI has done an incredible engineering job, given how inexpensive and fast these models are now, considering their original size in billions of parameters.</p><p>The gpt-3.5-turbo model comes at a cost of $0.002 per 1,000 tokens.</p><p>But how much is it? Let’s see. First, we need to know what is a token. In simple terms, a token refers to a part of a word. In the context of the English language, you can expect <strong>around 14 tokens for every 10 words</strong>.</p><p>To get a more accurate estimation of the number of tokens for your specific task and prompt, the best approach is to give it a try! Luckily, OpenAI provides a <a href="https://platform.openai.com/tokenizer">tokenizer playground</a> that can help you with this.</p><h4>Side note: Tokenization for Different Languages</h4><p>Due to the widespread use of English on the Internet, this language benefits from the most optimal tokenization. As highlighted in the <a href="https://blog.yenniejun.com/p/all-languages-are-not-created-tokenized">“All languages are not tokenized equal”</a> blog post, tokenization is not a uniform process across languages, and certain languages may require a greater number of tokens for representation. Keep this in mind if you want to build an application that involves prompts in multiple languages, e.g. for translation.</p><p>To illustrate this point, let’s take a look at the tokenization of <a href="https://clagnut.com/blog/2380">pangrams</a> in different languages. In this toy example, English required 9 tokens, French — 12, Bulgarian — 59, Japanese — 72, and Russian — 73.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HygZhqr5MlHwL69ywjrfnQ.png" /><figcaption>Tokenization for different languages. Screenshot of the <a href="https://platform.openai.com/tokenizer">OpenAI tokenizer playground</a></figcaption></figure><h4>Cost vs Performance</h4><p>As you may have noticed, prompts can become quite lengthy, especially when incorporating examples. By increasing the length of the prompt, we potentially enhance the quality, but the cost grows at the same time as we use more tokens.</p><p>Our latest prompt (v6) consists of approximately 1.5k tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*aX04KoOj2nM1Qno36Q5a9g.jpeg" /><figcaption>Tokenization of the prompt v6. Screenshot of the <a href="https://platform.openai.com/tokenizer">OpenAI tokenizer playground</a></figcaption></figure><p>Considering that the output length is typically the same range as the input length, we can estimate an average of around 3k tokens per request (<em>input tokens + output tokens</em>). By multiplying this number by the initial cost, we find that <strong>each request is about $0.006 or 0.6 cents</strong>, which is quite affordable.</p><p>Even if we consider a slightly higher cost of 1 cent per request (equivalent to roughly 5k tokens), you would still be able to make <strong>100 requests for just $1</strong>. Additionally, OpenAI offers the flexibility <a href="https://openai.com/pricing#:~:text=How%20can%20I%20manage%20my%20spending%3F">to set both soft and hard limits</a>. With soft limits, you receive notifications when you approach your defined limit, while hard limits restrict you from exceeding the specified threshold.</p><blockquote>For local use of your LLM application, you can comfortably configure a hard limit of $1 per month, ensuring that you remain within budget while enjoying the benefits of the model.</blockquote><h4>Streamlit App Template</h4><p>Now, let’s build a web interface to interact with the model programmatically eliminating the need to manually copy prompts each time. We will do this with <a href="https://streamlit.io/">Streamlit</a>.</p><p>Streamlit is a Python library that allows you to create simple web interfaces without the need for HTML, CSS, and JavaScript. It is beginner-friendly and enables the creation of browser-based applications using minimal Python knowledge. Let’s now create a simple template for our LLM-based application.</p><p>Firstly, we need the logic that will handle the communication with the OpenAI API. In the example below, I consider generate_prompt()function to be defined and return the prompt for a given input text (e.g. similar to what you saw before).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35bca9ce68ef526732ab905b427d36c2/href">https://medium.com/media/35bca9ce68ef526732ab905b427d36c2/href</a></iframe><p>And that’s it! Know more about different parameters in <a href="https://platform.openai.com/docs/api-reference/chat/create#:~:text=given%20chat%20conversation.-,Request%20body,-model">OpenAI’s documentation</a>, but things work well just out of the box.</p><p>Having this code, we can design a simple web app. We need a field to enter some text, a button to process it, and a couple of output widgets. I prefer to have access to both the full model prompt and output for debugging and exploring reasons.</p><p>The code for the entire application will look something like this and can be found in <a href="https://github.com/Winston-503/streamlit_app_template">this GitHub repository</a>. I have added a placeholder function called toy_ask_chatgpt() since sharing the OpenAI key is not a good idea. Currently, this application simply copies the prompt into the output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a5d1ba980bb034356f626670d5126ee/href">https://medium.com/media/3a5d1ba980bb034356f626670d5126ee/href</a></iframe><p>Without defining functions and placeholders, it is only about 50 lines of code!</p><p>And thanks to a <a href="https://docs.streamlit.io/streamlit-community-cloud/get-started/embed-your-app">recent update in Streamlit it now allows embed it</a> right in this article! So you should be able to see it right below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwinston-503-streamlit-app-template-app-uaisy6.streamlit.app%2F%3Fembed%3Dtrue&amp;display_name=Streamlit&amp;url=https%3A%2F%2Fwinston-503-streamlit-app-template-app-uaisy6.streamlit.app&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fs4a-prod-share-preview%2Fdefault%2Fst_app_screenshot_image%2F95f47a5a-4710-4adb-8baa-7dc432e84462%2FHome_Page.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=streamlit" width="560" height="630" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b49f378ab487262e16678fe19ada907/href">https://medium.com/media/8b49f378ab487262e16678fe19ada907/href</a></iframe><p>Now you see how easy it is. If you wish, you can <a href="https://docs.streamlit.io/streamlit-community-cloud/get-started/deploy-an-app">deploy your app with Streamlit Cloud</a>. But be careful, since every request costs you money if you put your API key there!</p><h3>Conclusion</h3><p>In this blog post, I listed several best practices for prompt engineering. We discussed iterative prompt development, the use of separators, requesting structural output, Chain-of-Thought reasoning, and few-shot learning. I also provided you with a template to build a simple web app using Streamlit in under 100 lines of code. Now, it’s your turn to come up with an exciting project idea and turn it into reality!</p><p>It’s truly amazing how modern tools allow us to create complex applications in just a few hours. Even without extensive programming knowledge, proficiency in Python, or a deep understanding of machine learning, you can quickly build something useful and automate some tasks.</p><p>Don’t hesitate to ask me questions if you’re a beginner and want to create a similar project. I’ll be more than happy to assist you and respond as soon as possible. Best of luck with your projects!</p><h3>Resources</h3><p>Here are my other articles about LLMs that may be useful to you. I have already covered:</p><ul><li><a href="https://towardsdatascience.com/behind-the-millions-estimating-the-scale-of-large-language-models-97bd7287fb6b">Estimating the Scale of Large Language Models</a>: what are LLMs, how are they trained, and how much data and compute do they need;</li><li><a href="https://towardsdatascience.com/using-chatgpt-for-efficient-debugging-fc9e065b7856#da94-27cac6b3f550">Using ChatGPT for Debugging</a>: how to use LLMs for debugging and code generation.</li></ul><p>You can be also interested in:</p><ul><li>Free <a href="https://learnprompting.org/">Learn Prompting course</a> to gain a deeper understanding of prompting and various techniques associated with it;</li><li>Recently released <a href="https://www.deeplearning.ai/short-courses/">short courses by DeepLearning.AI</a> to build applications with OpenAI API</li></ul><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5e86c483af4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/summarising-best-practices-for-prompt-engineering-c5e86c483af4">Summarising Best Practices for Prompt Engineering</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Millions: Estimating the Scale of Large Language Models]]></title>
            <link>https://medium.com/data-science/behind-the-millions-estimating-the-scale-of-large-language-models-97bd7287fb6b?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/97bd7287fb6b</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 16:08:52 GMT</pubDate>
            <atom:updated>2023-06-22T21:56:19.095Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discussing LLMs like ChatGPT, the underlying costs, and inference optimization approaches</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4h0NMUMPrlEhTY7eB6yww.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/photo/hard-cash-on-a-briefcase-259027/">Pixabay</a></figcaption></figure><blockquote>Thanks to <a href="https://medium.com/u/84ea27feb7de">Regan Yue</a>, you can read the Chinese version of this article at <a href="https://mp.weixin.qq.com/s/ek9Z9E-T04BBP7g7rl2Eqw">mp.weixin.qq.com</a>, <a href="https://juejin.cn/post/7225058326575693884">juejin.cn</a>, <a href="https://segmentfault.com/a/1190000043715456">segmentfault.com</a> and <a href="https://xie.infoq.cn/article/e6d832cc0db3203e661647960">xie.infoq.cn</a>!</blockquote><p>In the recent past, machine learning was considered a complex, niche technology that only a select few could comprehend. However, as ML applications become more powerful, the public’s interest has surged, leading to a vast amount of content surrounding Artificial Intelligence. The culmination of this happened in <a href="https://openai.com/blog/chatgpt">November 2022, when we saw ChatGPT</a>, and continued in <a href="https://openai.com/research/gpt-4">March 2023 with the release of GPT-4</a>, when even the most skeptical person was surprised at what modern neural networks can do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*vaWiX1juc7SikCkmQmjwBQ.jpeg" /><figcaption>Asking ChatGPT about its capabilities. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>While some of this content is undoubtedly valuable, a significant portion of it perpetuates <strong>fear </strong>and <strong>misinformation</strong>, such as the <em>spread of the idea that robots will replace all human jobs</em> or <em>discovering secret ways to make huge sums of money on neural networks</em>. As a result, it has become increasingly important to dispel misconceptions about machine learning and <strong>large language models </strong>and provide informative content to help people understand these technologies better.</p><p>This article aims to discuss the crucial aspect of modern machine learning that is often overlooked or misunderstood — the cost of training large language models. At the same time, we will briefly take a look at what LLM is and some possible techniques to optimize its inference. By providing comprehensive examples, I hope to convince you that these technologies <em>do not come out of the air.</em> By getting an idea about the <strong>scale of the data and the underlying calculations</strong> you will better understand these powerful tools.</p><p>Mostly, I will rely on the recent <a href="https://ai.facebook.com/blog/large-language-model-llama-meta-ai/">LLaMA paper by Meta AI</a> because of its clarity in the sense of the amount of data and compute the team used to train these models. The post will be divided into the following sections:</p><ol><li>First, we’ll briefly look at <strong>what modern LLMs are</strong>;</li><li>Then, we discuss <strong>how much it costs to train such models</strong>;</li><li>In the end, we briefly consider some <strong>popular techniques to optimize language models for inference</strong>.</li></ol><p>Stay tuned as we delve deeper into the world of large language models and you will see that everything is <em>very simple</em> and <em>very complicated</em> at the same time.</p><h3>Introduction to Large Language Models</h3><p>Before we explore the costs associated with training Large Language Models (LLMs), let’s first briefly define what a language model is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*DHX3xYWF6Wy1EoRcmtigVA.jpeg" /><figcaption>Parameter counts of several language models released in 2018–2019. Modern LLMs usually have tens to hundreds of billions of parameters. Figure 1 from <a href="https://arxiv.org/pdf/1910.01108.pdf">DistilBERT paper</a></figcaption></figure><p>In simple terms, a language model is a type of machine learning algorithm designed to understand or generate human language. Recently, exactly <strong>generative models</strong> have become more and more popular — the <strong>GPT model family</strong><em> </em>developed by OpenAI: ChatGPT, GPT-4, etc (stands for <em>Generative Pre-trained Transformer</em>, honoring the <a href="https://huggingface.co/course/chapter1/4"><em>Transformer </em>architecture</a> on which it is based).</p><p>Less popular, but still important examples include <a href="https://en.wikipedia.org/wiki/GPT-3">GPT-3 (175B)</a>, <a href="https://bigscience.huggingface.co/blog/bloom">BLOOM (176B)</a>, <a href="https://www.deepmind.com/blog/language-modelling-at-scale-gopher-ethical-considerations-and-retrieval">Gopher (280B)</a>, <a href="https://arxiv.org/abs/2203.15556">Chinchilla (70B)</a>, and <a href="https://ai.facebook.com/blog/large-language-model-llama-meta-ai/">LLaMA (65B)</a>, where <em>B</em> refers to <em>billions </em>of parameters, although many of these models also have smaller versions.</p><blockquote>Nothing is known about the number of ChatGPT and especially GPT-4 parameters, but it looks like these are about the same numbers.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8M_aOoBHRcuNRCL1v2-xQw.png" /><figcaption>Some of the popular LLMs architectures. Image by Author</figcaption></figure><p>These models are “trained” using vast amounts of text data, enabling them to learn the complex patterns and structures of natural language. However, the task they solve during training is very simple: they just predict the next word (or <em>token) </em>in a sequence.</p><p>You may have heard such a model called <strong>autoregressive, </strong>which means it <em>uses its past outputs as input for future predictions</em> and <em>generate output step by step</em>. This can be seen, among other things, in the example of ChatGPT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6-jk9ePRu53Qo2PYZ2AgQ.gif" /><figcaption>GhatGPT generates a response. Gif by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><p>You can notice that the model generates the answer <em>gradually </em>and <em>in chunks</em> that are sometimes less than one word. These chunks are called <em>tokens </em>and <a href="https://neptune.ai/blog/tokenization-in-nlp">they are very useful in NLP</a>, although not so important for us now.</p><p>At each time step, the model concatenates the previous output to the current input and keeps generating. It does so until it reaches the special <em>End of Sequence (EOS) </em>token. Omitting the prompt task and taking words as tokens for simplicity, the process can be illustrated as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ovTTy8w1ptp4wkVn3-f_w.png" /><figcaption>Illustrating text generation for autoregressive models. Image by Author</figcaption></figure><p>This simple mechanism together with a <strong>huge<em> </em>amount</strong> of data (<em>more than any person could read in several lifetimes</em>) allows the model to generate coherent and contextually appropriate text, mimicking human-like writing.</p><blockquote>Note, that here we are talking about generative models only. Why if there are other model families?</blockquote><blockquote>The reason is quite simple — the text generation task is one of the most <strong>difficult </strong>to solve and at the same time one of the most <strong>impressive</strong>. <a href="https://twitter.com/gdb/status/1599683104142430208">ChatGPT gained 1 million users in just 5 days</a> — faster than any other application before, and <a href="https://www.reuters.com/technology/chatgpt-sets-record-fastest-growing-user-base-analyst-note-2023-02-01/">continues in the same spirit</a>.</blockquote><blockquote>So-called <a href="https://huggingface.co/course/chapter1/5"><strong>encoders</strong></a><strong> </strong>(<strong>BERT </strong>model family) can be much less exciting, but they can also solve various problems with human-level performance and help you with tasks like <a href="https://paperswithcode.com/task/text-classification">text classification</a> or <a href="https://paperswithcode.com/task/named-entity-recognition-ner">Named Entity Recognition (NER)</a>.</blockquote><p>I will not provide particular examples of what LLMs can do — the Internet is already full of them. The best way to get an idea is to <a href="https://chat.openai.com/chat">try ChatGPT yourself</a>, but you can also find plenty of exciting resources like the <a href="https://github.com/f/awesome-chatgpt-prompts">Awesome ChatGPT prompts repo</a>. Despite their impressive capabilities, current large language models have some limitations. The most popular and significant of them include:</p><ol><li><strong>Bias and staticity</strong>: Since LLMs are trained on data from various sources, they inadvertently learn and reproduce biases present in those sources. They are also static in the sense that they cannot adapt to new data or update their knowledge in real time without re-training.</li><li><strong>Comprehension and disinformation</strong>: Although LLMs can generate human-like text, they may not always fully understand the context of the input. Also, the autoregressive way of generating output text does not prohibit the model from generating lies or nonsense.</li><li><strong>Resource-intensive</strong>: Training LLMs requires substantial computing resources, which translates to high costs and energy consumption. This factor can limit the accessibility of LLMs for smaller organizations or individual researchers.</li></ol><p>These and other drawbacks are active topics for the research community. It is worthwhile to note that the field is growing so fast that it is impossible to predict what limitations will be overcome in just a few months — but without a doubt, new ones will arise.</p><blockquote>One possible example is the fact that earlier models simply grew in the number of parameters, but now it is considered that it is better to train smaller models for a longer time and give them more data. This reduces the model size and the cost of the model’s further use during inference.</blockquote><blockquote>In that way, the LLaMA release freed the hands of enthusiasts and these models were already run locally on <a href="https://mobile.twitter.com/ggerganov/status/1640022482307502085">computers</a>, <a href="https://twitter.com/miolini/status/1634982361757790209">Raspberry Pi</a>, and even <a href="https://twitter.com/thiteanish/status/1635188333705043969">phones</a>!</blockquote><p>Having a big picture of what LLM is, let’s move on to the main section of this article — estimating the cost of training large language models.</p><h3>Estimating the Cost of Machine Learning Models in General and LLMs in Particular</h3><p>To estimate the cost of training large language models, it is essential to consider three key factors that any machine learning algorithm consists of:</p><ul><li><strong>Data</strong>,</li><li><strong>Compute resources</strong>, and</li><li><strong>Architecture </strong>(or the algorithm itself).</li></ul><p>Let’s delve deeper into each of these aspects to better understand their impact on training costs.</p><h4>Data</h4><p>LLMs require massive amounts of data to learn the patterns and structures of natural language. Estimating the cost of data can be challenging since companies often use data accumulated over time through their business operations together with open-sourced datasets.</p><p>Additionally, data needs to be <em>cleaned</em>, <em>labeled</em>, <em>organized</em>, and <em>stored </em>efficiently, considering the scale of LLMs. Data management and processing costs can add up quickly, especially when factoring in the infrastructure, tools, and data engineers required for these tasks.</p><p>To make a particular example, it is known that LLaMA used a training dataset containing <strong>1.4 trillion tokens</strong> with a total size of <strong>4.6 terabytes</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*Wt2uISUxggMui2A0BMCC1g.jpeg" /><figcaption>Training dataset of LLaMA models. Table 1 from <a href="https://arxiv.org/pdf/2302.13971.pdf">LLaMA paper</a></figcaption></figure><p>Smaller models (7B and 13B) were trained on 1T tokens, while larger ones (33B and 65B) used the full dataset of 1.4T tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1z0hU_Jw_OHgeK0amUvYw.jpeg" /><figcaption>Training loss over tokens for LLaMA models. Figure 1 from <a href="https://arxiv.org/pdf/2302.13971.pdf">LLaMA paper</a></figcaption></figure><p>I think now you understand that no one is overstating when calling these datasets <strong>huge </strong>and why it wasn’t technically possible ten years ago. But things are even more interesting with computing resources.</p><h4>Compute</h4><p>The actual training process accounts for a significant portion of the LLM budget. Training large language models is resource-intensive and is done on powerful Graphics Processing Units (GPUs), due to significant parallel processing capabilities. <a href="https://www.crn.com/news/components-peripherals/8-big-announcements-at-nvidia-s-gtc-2023-from-generative-ai-services-to-new-gpus">NVIDIA releases new GPUs every year</a>, the cost of which hits hundreds of thousands of dollars.</p><p>The cost of cloud computing services for training these models can be huge and reach <strong>several million dollars</strong>, especially considering iterating through various configurations.</p><p>Returning to the LLaMA paper, the authors report that they train the biggest 65B model for <strong>21 days on two thousand GPUs with 80 GB of RAM each</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JE7zlf6NS1d8vgLI78A0lA.jpeg" /><figcaption>Amount of computing resources for training the LLaMA model. Image from <a href="https://arxiv.org/pdf/2302.13971.pdf">LLaMA paper</a></figcaption></figure><p><a href="https://www.nvidia.com/en-us/data-center/a100/">NVIDIA A100 GPU</a> authors used is a popular choice for modern neural network training. <a href="https://cloud.google.com/compute/gpus-pricing">Google Could Platform offers such GPUs</a> for <strong>$3.93 per hour</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*M545y37iTvJuUTrXCA1UQQ.jpeg" /><figcaption>Price of NVIDIA A100 GPU. Screenshot of a <a href="https://cloud.google.com/compute/gpus-pricing">public GCP pricing page</a></figcaption></figure><p>So let’s do some quick calculations:</p><blockquote>2048 GPUs x $3.93 GPU per hour x 24 hours x 21 days =</blockquote><blockquote>4.05 million dollars</blockquote><p>Four million dollars is a budget that not every researcher can afford, huh? And it is a single run! To give you another example, <a href="https://lambdalabs.com/blog/demystifying-gpt-3">this article estimates the cost of training GPT-3</a>, and the authors got <strong>355 GPU-years and 4.6 million dollars</strong>.</p><blockquote>You may have heard that “neural networks train very quickly on GPU”, but no one says relative to what.</blockquote><blockquote>They’re really training fast taking into account the <strong>enormous </strong>amount of calculations, and without these GPUs, they would have been training for decades. So yeah, 21 days is pretty fast for LLMs.</blockquote><h4>Architecture (and Infrastructure)</h4><p>The development of state-of-the-art LLMs also depends on the work of skilled researchers and engineers to develop the architecture and configure the training process properly. The architecture is the foundation of the model, dictating how it learns and generates text.</p><p>Expertise in various computer science areas is required for designing, implementing, and controlling these architectures. Engineers and researchers responsible for publishing and delivering cutting-edge results can command salaries reaching <strong>hundreds of thousands of dollars</strong>. It is worth noting that the skill set required for LLM development may differ significantly from the skill set of a “classic” machine learning engineer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFhDhi__wi9XiiHxZFsmJA.jpeg" /><figcaption>Machine learning system infrastructure. Figure 1 from <a href="https://proceedings.neurips.cc/paper_files/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf">Hidden Technical Debt in Machine Learning Systems paper</a></figcaption></figure><p>I think now you do not doubt that training LLMs is a <em>very hard</em> and <em>resource-intensive</em> engineering problem.</p><p>Now let’s briefly discuss some methods for making the process of LLM inference more efficient and cost-effective.</p><h3>Optimizing Language Models for Inference</h3><h4>Do we actually need optimization?</h4><p>Inference refers to the process of using a trained language model to generate predictions or responses, usually as an API or web service. Given the resource-intensive nature of LLMs, it is essential to optimize them for efficient inference.</p><blockquote>For example, GPT-3 model has 175 billion parameters, which is <strong>700 GB</strong> of float32 numbers. Approximately the same amount of memory will be taken up by activations, and remember that we are talking about RAM.</blockquote><blockquote>To serve predictions without any optimization technique, we will need 16 A100 GPUs with 80 GB of memory each!</blockquote><p>Several popular techniques can help reduce memory requirements and model latency, including <em>model parallelism</em>, <em>quantization</em>, and others.</p><h4>Model Parallelism</h4><p><a href="https://colossalai.org/docs/concepts/paradigms_of_parallelism/">Parallelism</a> is a technique that distributes the computation of a single model across multiple GPUs and can be used both during training and inference.</p><p>Splitting the model’s layers or parameters across multiple devices can dramatically improve the overall inference speed and is very often used in practice.</p><h4>Quantization</h4><p><a href="https://huggingface.co/docs/optimum/concept_guides/quantization">Quantization</a> involves reducing the precision of the model’s numerical values (such as weights). By converting floating-point numbers to lower-precision integers, quantization can result in significant memory savings and faster computation without a substantial loss in model performance.</p><p>The simple idea that arises quite quickly is to use <em>float16</em> numbers instead of <em>float32 </em>and reduce the amount of memory by half<em>.</em> It turns out that it is possible to convert model weights even to <em>int8 </em>almost without accuracy loss due to the fact that they are located close to each other on the number line.</p><h4>Other Techniques</h4><p>Finding ways to optimize LLMs is an active area of research, and other techniques include:</p><ul><li><a href="https://neptune.ai/blog/knowledge-distillation">Knowledge distillation</a> — training a smaller <em>student </em>model to mimic the behavior of a larger <em>teacher;</em></li><li><a href="https://analyticsindiamag.com/a-beginners-guide-to-neural-network-pruning/">Parameter pruning</a> — removing redundant or less important parameters from the model to reduce its size and computational requirements;</li><li>And using frameworks like <a href="https://onnxruntime.ai/">ORT (ONNX Runtime)</a> to optimize calculation graphs with techniques like <em>operator fusion</em> and <em>constant folding.</em></li></ul><p>Overall, optimizing large language models for inference is a critical aspect of their deployment. By applying various optimization techniques, developers can ensure that their LLMs are not only powerful and accurate but also cost-effective and scalable.</p><h3>Why did OpenAI Open Access to ChatGPT?</h3><p>After all the above, one might wonder why OpenAI decided to open access to ChatGPT, given the high costs associated with training and inference. While we cannot be certain of the company’s exact motivations, we can analyze the benefits and potential strategic reasons behind this decision.</p><p>First and foremost, OpenAI has gained <em>significant popularity</em> by making state-of-the-art LLMs more accessible to the broader public (see <a href="https://medium.com/@kozyrkov/whats-different-about-today-s-ai-380569e3b0cd">AI revolution is more of a UX revolution</a>). By demonstrating the practical applications of large language models, the company has captured the attention of investors, customers, and the tech community at large. Moreover, this allowed OpenAI to <strong>collect huge amounts of feedback and data</strong> to improve their models.</p><p>Secondly, OpenAI’s mission revolves around the creation and advancement of AI. By opening access to ChatGPT, the company is arguably moving closer to fulfilling its mission and preparing society for unavoidable changes. Providing access to powerful AI tools encourages innovation, driving the field of AI research forward. This progress can lead to the development of more efficient models, more extensive applications, and novel solutions to various challenges. It’s worth noting here that the <strong>architecture of ChatGPT and GPT-4 is closed</strong>, but that’s another discussion.</p><p>While the costs associated with training and maintaining large language models are undoubtedly significant, the benefits and strategic advantages that come with opening access to these tools can outweigh the expenses for <em>some </em>organizations. In the case of OpenAI, opening access to ChatGPT has not only increased their popularity and proved to be a leader in the AI field, but also allowed them to collect more data to train more powerful models. This strategy has allowed them to advance their mission and contribute (<em>in some sense</em>) to the broader development of AI and LLM technologies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*0M8lbIi9w4wMGwh2kpgyPw.jpeg" /><figcaption>Asking ChatGPT why OpenAI is giving free access to ChatGPT. Image by Author created using <a href="https://chat.openai.com/chat">ChatGPT</a></figcaption></figure><h3>Conclusion</h3><p>As we have seen, the cost of training large language models is influenced by various factors, including <em>not only</em> expensive computing resources but also big data management and the expertise required to develop cutting-edge architectures.</p><blockquote>Modern LLMs have <strong>billions </strong>of parameters, are trained on <strong>trillions </strong>of tokens, and cost <strong>millions </strong>of dollars.</blockquote><p>I hope you now better understand the scale of training and inferencing large language models, as well as their limitations and pitfalls.</p><p>The field of NLP has been experiencing its <a href="https://thegradient.pub/nlp-imagenet/">ImageNet moment</a> for several years, and now it’s the turn of <strong>generative models</strong>. The widespread application and adoption of generative language models have the potential to <em>revolutionize various industries and aspects of our lives</em>. While it is difficult to predict exactly how these changes will unfold, we can be certain that LLMs will have some impact on the world.</p><p>Personally, I like the recent tendency of training “smarter”, not just “larger” models. By exploring more elegant ways to develop and deploy LLMs, we can push the boundaries of AI and NLP, opening the door to innovative solutions and a brighter future for the field.</p><h3>Resources</h3><p>Here are my other articles about LLMs that may be useful to you. I have already covered:</p><ul><li><a href="https://towardsdatascience.com/summarising-best-practices-for-prompt-engineering-c5e86c483af4">Best Practices for Prompt Engineering</a>: how to apply prompt engineering techniques to interact with LLMs effectively and how to build local LLM-based applications with OpenAI API and Streamlit;</li><li><a href="https://towardsdatascience.com/using-chatgpt-for-efficient-debugging-fc9e065b7856#da94-27cac6b3f550">Using ChatGPT for Debugging</a>: how to use LLMs for debugging and code generation.</li></ul><p>If you become interested in LLMs and want to learn more about them, here are some resources that can help you with that:</p><ul><li><a href="https://jalammar.github.io/illustrated-transformer/">Illustrated Transformer</a> is a great introduction to Transformer architecture which started the NLP big bang by Jay Alammar;</li><li><a href="https://jalammar.github.io/how-gpt3-works-visualizations-animations/">How GPT-3 Works — Visualizations and Animations</a> is a visualization of an autoregressive decoding process by the same author;</li><li><a href="https://jaykmody.com/blog/gpt-from-scratch/">GPT in 60 Lines of NumPy</a> is a great article by Jay Mody where the author builds his own simple GPT;</li><li><a href="https://www.youtube.com/watch?v=kCc8FmEb1nY">Let’s build GPT: from scratch, in code, spelled out</a> is an awesome video by famous Andrej Karpathy, who worked on <a href="https://www.tesla.com/autopilot">Tesla Autopilot</a> as Sr. Director of AI at Tesla;</li><li>To get a more in-depth idea of the field, check out the <a href="https://github.com/Hannibal046/Awesome-LLM">Awesome-LLM GitHub repo</a> for a more detailed list of resources. Take a look at <a href="https://arxiv.org/abs/2203.15556">Chinchilla</a> and <a href="https://arxiv.org/abs/2302.13971">LLaMA</a> as one of the most influential papers of recent times.</li></ul><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97bd7287fb6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/behind-the-millions-estimating-the-scale-of-large-language-models-97bd7287fb6b">Behind the Millions: Estimating the Scale of Large Language Models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Much Can You Earn Blogging about Machine Learning in One Year]]></title>
            <link>https://medium.com/@andimid/how-much-can-you-earn-blogging-about-machine-learning-in-one-year-e70e01aacc22?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/e70e01aacc22</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 15:29:23 GMT</pubDate>
            <atom:updated>2024-02-18T20:01:14.624Z</atom:updated>
            <content:encoded><![CDATA[<h4>Publishing your articles on Medium and Towards Data Science</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmrsVsm7Qtpfbsy4uAtUww.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/photo/twenty-dollar-bills-on-top-of-a-wooden-desk-5224945/">Joslyn Pickens</a> on <a href="https://www.pexels.com/">Pexes</a></figcaption></figure><p>I started blogging on Medium and publishing articles on <a href="https://towardsdatascience.com/">Towards Data Science</a> about one year ago. In this article, I would like to summarize my writer’s achievements so far and tell you how much money I have earned through <a href="https://help.medium.com/hc/en-us/articles/115011694187-Getting-started-with-the-Partner-Program">Medium Partner Program</a> during this time.</p><p>You might consider Medium as your data science/machine learning <em>blog platform</em>, or perhaps you are thinking about <em>monetizing </em>your writing talent, I hope my story will be interesting for you.</p><h4>TL;DR</h4><p>Respecting your time, the final number is about <strong>830 USD</strong> <em>without any investments</em>. On average, this is about <strong>$70</strong> per month.</p><p>For those who stay, we will explore not only earnings. I will show you <em>detailed statistics</em> for my articles and followers, and we will find out how to estimate the earnings of any Medium article! Using machine learning, of course. :)</p><h4>Before We Start</h4><p>My blogging journey actually starts on September 2021, not January 2022. So why I am reporting to you from January 2022 to January 2023?</p><p>As you probably know, the <a href="https://help.medium.com/hc/en-us/articles/115011694187-Getting-started-with-the-Partner-Program">Medium Partner Program</a> requires you to have <strong>at least one hundred followers</strong> to earn money from your articles.</p><blockquote>Note: if you wish to earn money using the Medium Partner Progam, first carefully read its <a href="https://help.medium.com/hc/en-us/categories/360000842234-Partner-Program">terms and conditions</a>, including <a href="https://help.medium.com/hc/en-us/articles/115011694187-Getting-started-with-the-Partner-Program#:~:text=Desktop-,Countries%20supported%20in%20the%20Program,-Currently%2C%20enrollment%20in">the list of countries that support it</a>.</blockquote><p>These 5 months (from September 2021 to January 2022) actually took me to gain my first 100 followers. The reads my article collected during this time are thus non-monetized (free).</p><p>I also <strong>didn&#39;t invest any money</strong> to promote my articles and my Medium profile. All I did was publishing articles on LinkedIn and Twitter, as well as on a couple of public data science communities, like <a href="https://www.linkedin.com/groups/961087/">this</a> or <a href="https://www.linkedin.com/groups/3990648/">this</a>. There are two main reasons why I haven’t put any money into my writing yet:</p><ul><li>Curiosity— to understand how far I can go from scratch;</li><li>Unnecessity— I don’t actually need this, at least for now.</li></ul><p>Don’t get me wrong, but I am not primarily a writer and I am not as productive as one of them. I am just sharing my projects and thoughts that I think can be useful for other people. One day my position may change, but for now, it is what it is.</p><h3>Initial Dataset</h3><p>During these 17 months (from September 2021 to January 2023), I have written 24 articles. This is 1.4 articles per month on average, although the distribution is not so uniform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*h5lhPcGZYXqMxmVSoa3h9w.png" /><figcaption>The number of articles per month. Image by Author</figcaption></figure><p>Using the Medium platform, I collect the following article data for analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*vnIRt-QbgTMgQ0WwscwKAQ.jpeg" /><figcaption>Article stats dataset. Image by Author</figcaption></figure><p>To avoid displaying the full title of the article on the plots, which would look inconvenient, I came up with shortcodes. If you are interested in the characteristics of a certain article, you can get its full name from the table below and find it in <a href="https://medium.com/@andimid">my profile</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*TS9yqrnVS3y9OEXPCD_gAw.jpeg" /><figcaption>Shortcodes and full article titles. Image by Author</figcaption></figure><p>In addition to the titles, the dataset includes the following columns:</p><ul><li><strong>date </strong>— article publication date;</li><li><strong>category </strong>— the article category: <em>cheat sheet</em>, <em>tutorial</em>, <em>review</em>, or <em>project</em>;</li><li><strong>n_views </strong>— number of users who started reading the article (thousands);</li><li><strong>external_views </strong>— the percentage of views from non-Medium sources (social media, search results, etc.);</li><li><strong>n_reads </strong>— number of users who reached the end of the article (thousands);</li><li><strong>n_fans </strong>— number of unique users who clapped for the article (can be interpreted as the number of <em>likes</em>);</li><li><strong>member_reading_time </strong>— the total amount of time Medium members spent reading the article (minutes);</li><li><strong>earnings </strong>— the total amount of money the story earned from the moment of publication to today (US dollars).</li></ul><blockquote>It will be more accurate to say that earnings are collected from the moment of <strong>metering </strong>your story to today. Since some of my reads are free (for the time when I didn’t have a hundred followers), we cannot observe a <strong>direct correlation</strong> between earnings and, for example, the number of views. But we’ll talk about this a little later.</blockquote><blockquote>By the way, after gaining access to the partner program, of course, you can meter those stories that were written before receiving it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*oEbTD9z5qivWjwuIdMT8tw.jpeg" /><figcaption>To meter your story, go to “Edit story” — “Manage meter settings” — “Meter your story”. Image by Author</figcaption></figure><p>Let’s finally build a couple of visualizations.</p><h3><strong>Values per Article</strong></h3><h4>Number of Views and Reads</h4><p>First, let’s look at the views and reads. Here and further, I sort articles by a certain value and calculate how many of the most successful articles take 80% and 95% of the value.</p><p>For <strong>views </strong>and <strong>reads</strong>, these numbers are 10 and 17 respectively (out of 24). The <em>dashed line</em> on the plot represents a simple average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAhCNKIz3BitI44TWCI3jw.png" /><figcaption>The number of views per article. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BRPVpzb_8FRbHpTciHNLg.png" /><figcaption>The number of reads per article. Image by Author</figcaption></figure><p>As you can see, the spread between the maximum and minimum values is very large (about x100 times!) — <strong>48k views </strong>and <strong>6k reads </strong>for the <a href="https://towardsdatascience.com/overfitting-and-underfitting-principles-ea8964d9c45c">overfitting principles</a> vs only <strong>300 views</strong><em> </em>and about <strong>100 reads</strong><em> </em>for the <a href="https://towardsdatascience.com/what-does-your-favorite-movie-look-like-8c7b4a13ee94">movie color analysis</a>.</p><p>The same information can be shown more compactly using a single <em>stacked bar plot</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMFKZ4bIbqoAAuKvuL3pew.png" /><figcaption>The number of views and reads per article. Image by Author</figcaption></figure><h4>Number of Fans, Member Reading Time, and Article Earnings</h4><p>As we will see later, the <strong>number of fans</strong> and <strong>member reading time</strong> are better correlated to final <strong>earnings </strong>than views and reads.</p><p>80 and 95 percent of <strong>fans </strong>were collected by 12 and 19 articles. For the <strong>member reading time</strong> and <strong>earnings</strong>, these numbers are 11 and 17 respectively — that is, about the same as for views/reads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3uWGYclhjCYFS8JyZXtSA.png" /><figcaption>The number of fans per article. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3vrEhP66rVQ0_5HoXufCA.png" /><figcaption>Member reading time per article. Image by Author</figcaption></figure><p>The least popular article for these indicators is the same — <a href="https://towardsdatascience.com/what-does-your-favorite-movie-look-like-8c7b4a13ee94">movie color analysis</a> with <strong>3 fans</strong><em> </em>and <strong>26 minutes of member reading time</strong><em>.</em> But the favorite has changed — now it is the <a href="https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c">top ML resources</a> with <strong>105 fans</strong><em> </em>(x35) and <strong>63 hours of member reading time</strong> (x150).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BNFPMzont91-QQFIVZ5Ww.png" /><figcaption>Earnings per article. Image by Author</figcaption></figure><p>As well as for <strong>member reading time</strong>, 80 and 95 percent of <strong>earnings </strong>were collected by 11 and 17 articles. The most and least popular articles remain the same: <strong>$233.82</strong> for <a href="https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c">top ML resources</a> and <strong>$1.36</strong> for <a href="https://towardsdatascience.com/what-does-your-favorite-movie-look-like-8c7b4a13ee94">movie color analysis</a> with an average value of about <strong>$35</strong> per article.</p><h3>Values per Category</h3><p>To dive in a little deeper, I decided to cluster the articles into categories, using the following:</p><ul><li><strong>Cheat sheet</strong> — 6 articles: a short summary on a specific topic, which can be used to refresh your knowledge or as a little learning path;</li><li><strong>Tutorial</strong> — 7 articles: articles where I explain some concepts in my own words, usually (but not always) reinforcing them with code. Also, here I’m just telling things— e.g. <a href="https://towardsdatascience.com/the-resume-with-which-i-got-my-first-ml-internship-in-canada-d1cd833cc452">about my resume writing experience</a> or <a href="https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c">interesting machine learning applications</a>;</li><li><strong>Review</strong> — 3 articles: my opinions, which can be useful to others, usually about learning resources: courses and exams;</li><li><strong>Project </strong>— 8 articles: various project descriptions. They require the most time due to hatching an idea and writing more code and documentation.</li></ul><p>Let’s look at the same indicators, grouping the data <em>by category</em>. I will report the <strong>average </strong>because the sum does not make much sense: the number of articles in the various categories is different. The <em>dashed line</em> indicates the <em>average among the four categories</em>. Under the average values graph, I also bring a <a href="https://chartio.com/learn/charts/violin-plot-complete-guide/">violin plot</a> to get an idea of the distribution form.</p><h4>Number of Views and Reads</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAM6IqStz7rvhs_E9mIFBw.png" /><figcaption>The number of views per category. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axkQGNlSMcQ5itU_fmTa-Q.png" /><figcaption>The number of reads per category. Image by Author</figcaption></figure><p><strong>Tutorials </strong>have the highest number of views on average, and <strong>projects </strong>have the least.</p><p>The situation remains the same for <em>reads</em>, but the value spread (deviation from the mean) here is much smaller. We can say that on average, readers read my articles about the same way.</p><h4>Number of Fans, Member Reading Time, and Article Earnings</h4><p>The ranking of categories in relation to the <em>number of fans</em>, <em>reading time</em>, and <em>earnings </em>is the same: <strong>tutorial </strong>(the most successful), <strong>cheat sheet</strong>, <strong>review</strong>, and <strong>project </strong>(the least successful).</p><p>The least popular category gets only <strong>15 fans</strong>, <strong>6 hours of reading time</strong><em>,</em> and <strong>$15</strong> on average, while the most popular one gets <strong>40 fans</strong> (x2.5), <strong>20 hours of reading time</strong> (x3), and <strong>$60</strong> (x4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7tljFjrR7WwGSU01wfrDg.png" /><figcaption>The number of fans per category. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zn5KJUW16qdCtLklnIfyRA.png" /><figcaption>Member reading time per category. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftKz5RAB3aZReKhF0jcjKg.png" /><figcaption>Earnings per category. Image by Author</figcaption></figure><p>It turns out that by all the values, the <strong>Tutorial </strong>is the most popular category, and the <strong>Project </strong>is the most unpopular. Meanwhile, projects require much more time for creating and describing.</p><p>If we imagine such indicator as <strong>the ratio of time spent to expected profit </strong>tutorials will clearly win, and not only because they are easier to get ideas and write (although not always). Given the same time, you can just write more of them, and some will definitely attract the attention of your audience.</p><p>I do not attempt to determine which topics are most profitable to write on — I am not writing for this. After all, I have already seen that my projects are not so popular: there is no need to plot any charts for this. But an approach that maximizes profit seems to minimize creativity — write a lot of short articles on various topics and some will clearly bring you profit.</p><blockquote>Important disclaimer</blockquote><blockquote>Indeed, the tutorials show the best averages, but look at how stretched their distribution is. This is because the three most successful articles (<a href="https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c">top ML resources</a>, <a href="https://towardsdatascience.com/overfitting-and-underfitting-principles-ea8964d9c45c">overfitting</a> and <a href="https://towardsdatascience.com/graphs-with-python-overview-and-best-libraries-a92aa485c2f8">graphs</a>) are <strong>tutorials. </strong>At the same time, they are far of the average values and can even be considered as outliers or anomailes.</blockquote><blockquote>It’s a toy analysis, but estimating a distribution based on 10 data points is clearly not a good idea.</blockquote><h3>Predicting Earnings</h3><p>What if we train the model to predict earnings based on the values discussed above? After all, <em>we have the dataset</em>. Yes, pretty small, <strong>extremely </strong>small, but we can at least see what happens. Thus, we will also be able to visually monitor the degree of correlation between the article&#39;s stats and the final earnings.</p><p>Let’s take a <em>linear regression</em>, assuming that the relationship will be simple and linear. I will also use <strong>only one value at a time</strong> and <strong>remove the bias</strong> suggesting that there is no initial “boost”. Thus we get the simplest equation from the first chapter of any machine learning book: y=a*x. In our case, y is earnings, x is feature (<em>n_views</em>, <em>n_fans</em>, etc.) and a is the only learnable parameter.</p><h4>Filtering Data</h4><p>The first thing to do is to correct the data. As I said earlier, some reads were free, and for the purity of the experiment, we need to minimize their impact. I will use <strong>those articles that began to earn instantly</strong>, that is, articles that were written after receiving the partner program in early January 2022.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrzK7KaJG0P-T8pB-R-M2A.jpeg" /><figcaption>Filtered dataset. Image by Author</figcaption></figure><p>I use the entire dataset for training and do not put aside the test set because:</p><ul><li>there is too little data and a test set containing only several data points will give a biased estimate, and <strong>more importantly</strong></li><li>we can evaluate the relationship <em>visually </em>since we use only one variable.</li></ul><blockquote>Don’t forget that splitting the test set and putting it aside <strong>at the very beginning</strong> is the first thing you should do in a real task.</blockquote><h4>Predicting Earnings Based on Views/Reads</h4><p>It turns out that the number of <strong>views </strong>and <strong>reads </strong>is not a good feature for predicting the earnings of an article. Although it may seem that the <em>Root Mean Square Error</em> is not so bad, it is visually clear that we are far from a simple relationship and there is a lot of noise in the data.</p><p>This can be explained by the fact that most of the views on my articles (about 75–80% on average) are from external sources (social media, Internet search, etc.) and thus most likely from unregistered users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwUYZMJmObH77wRkD7aAqA.png" /><figcaption>Predicting earnings based on the number of views/reads. Image by Author</figcaption></figure><h4>Predicting Earnings Based on Fans/Member Reading Time</h4><p>Intuitively, <strong>member reading time</strong> — the time Medium members spent reading the article — is the best feature for predicting the article’s earnings.</p><p>And it really is! Based on my data, I can expect <strong><em>6 cents for every minute of Medium member reading</em></strong>, which is <em>$3.6 per hour</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*lMHBDj9u_B3qvW1Kx9THZQ.png" /><figcaption>Predicting earnings based on the member reading time. Image by Author</figcaption></figure><p>Obviously, this is the best possible feature, but it is private and available only to the author. Can we use some public article characteristics to evaluate earnings? It turns out — yes, and this is the <strong>number of fans</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ExJL1nn844v-fe6Ca2qB6w.png" /><figcaption>Predicting earnings based on the number of fans. Image by Author</figcaption></figure><p>The trained model says that we can expect <strong>$2.2 for every fan</strong>. Look at the chart — it’s almost as accurate as the previous one! The intuition can be explained by at least two facts:</p><ul><li>First: only registered users can be fans;</li><li>And second: if a person clapped, then he liked the article, which means he spent some time reading it. If it’s a Medium member, then you’ve earned some part of his membership.</li></ul><p>The interesting fact is that the number of fans is <strong>publicly available</strong> and now you know how to <em>estimate the earnings of any Medium article</em>, provided that it has been metered since the beginning of the publication. Just <strong>multiply the number of fans by 2.2</strong> and get approximate earnings in USD!</p><p>Note that the number of claps and fans are different things. The number of fans is the number of <em>unique users</em> who have clapped for an article, <strong>regardless</strong> of the number of claps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*lZBRa7d4NYGO2h8nMYwMQQ.jpeg" /><figcaption>To see the number of claps and fans click on the number on right from the “clap” icon. <a href="https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c">Public domain</a></figcaption></figure><p>In the example below, Igor clapped <strong>50 times</strong> but increased the number of fans <strong>just by one</strong>. But it looks like you really enjoyed the article, Igor!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZreadXyN-ky_pZB8Bij5wQ.png" /><figcaption>The number of fans vs the number of claps. <a href="https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c">Public domain</a></figcaption></figure><p>Well. Do not forget that the final earnings consist not only of the article&#39;s earnings but also of your paid subscribers — <em>referred members</em>. Let’s take a look at them and at subscribers&#39; stats in general.</p><h3>Followers Monthly Growth</h3><p>Here are my followers&#39; stats for these 17 months.</p><p>Basically, on average they grow by <strong>30 followers per month</strong>, that is, one person subscribes to me per day. Also on average, I get <strong>2 email subscribers</strong> in a month and about <strong>0.6 referred members</strong>, although the latter have been unsubscribing recently. Each of the referred members brings me about 2 USD per month. Thanks!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87Uz8qozFpg-jjrciGcXeQ.jpeg" /><figcaption>Followers stats. Image by Author</figcaption></figure><p>In total, I earned $302 on paid subscribers, which is <strong>$18 per month</strong> on average.</p><h3>Total Number of Earnings</h3><p>$880 article earnings + $300 followers earnings = $1180 in total.</p><p>But how much did I actually get?</p><p>Here is the screenshot of my Stripe account payments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*zBAk6ojbhNICF6Yo03OkHw.jpeg" /><figcaption>Stripe payments. Image by Author</figcaption></figure><blockquote>The sum of all Stripe payments is <strong>830.42 USD</strong>, which is about 1080 CAD.</blockquote><blockquote>This is the final number of my earnings so far — for 17 months of my writing career, 5 of which were unmonetized.</blockquote><h3>Top 10 of My Most Popular Articles</h3><p>Analyzing the indicators of articles, I constantly came across the same titles among the best. And <a href="https://en.wikipedia.org/wiki/Pareto_principle"><em>although 80% of the result was achieved not by 20% of the articles</em></a>, there are clearly favorites.</p><p>Here are the top ten of my most successful articles (with <strong>fans </strong>and <strong>earnings </strong>in brackets).</p><h4>Projects</h4><ul><li><a href="https://towardsdatascience.com/automatic-video-editing-using-python-324e5efd7eba">Automatic Video Editing using Python</a> (31, $30) and <a href="https://towardsdatascience.com/speech-recognition-with-timestamps-934ede4234b2">Speech Recognition with Timestamps</a> (17, $30)</li><li><a href="https://towardsdatascience.com/how-to-create-real-time-face-detector-ff0e1f81925f">How to create a real-time Face Detector</a> (43, $33)</li></ul><h4>Reviews</h4><ul><li><a href="https://towardsdatascience.com/what-you-need-to-know-before-taking-the-machine-learning-course-by-stanford-84fd7bf94628">What you need to know before taking the Machine Learning course by Stanford</a> (38, $38)</li></ul><h4>Cheat sheets</h4><ul><li><a href="https://towardsdatascience.com/tensorflow-keras-cheat-sheet-5ec99d9a1ccf">TensorFlow/Keras cheat sheet</a> (23, $54)</li><li><a href="https://towardsdatascience.com/unsupervised-learning-algorithms-cheat-sheet-d391a39de44a">Unsupervised Learning algorithms cheat sheet</a> (21, $61)</li><li><a href="https://towardsdatascience.com/clustering-cheat-sheet-dcf72259abb6">Clustering cheat sheet</a> (21, $68)</li></ul><h4>Tutorials</h4><ul><li><a href="https://towardsdatascience.com/overfitting-and-underfitting-principles-ea8964d9c45c">Overfitting and Underfitting Principles</a> (82, $50)</li><li><a href="https://towardsdatascience.com/graphs-with-python-overview-and-best-libraries-a92aa485c2f8">Graphs with Python: Overview and Best Libraries</a> (47, $94)</li><li><a href="https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c">Top 7 Machine Learning resources I wish I knew earlier</a> (105, $234)</li></ul><h3>Conclusion</h3><p>Here’s what I’ve got: 24 articles, 200k views, 12 days of member reading time, 500 followers, and $800 earnings. It’s not a lot, but it’s not a little. As they say, <em>it ain’t much, but it’s honest work</em>.</p><p>I would like to take the opportunity to say <strong>thank you</strong> to all my readers and followers. All these successes would not have been possible without you.</p><p>I could have done better. But I don’t want to force myself to release an article a week, copy other people’s posts, or talk about things that can be found in a few seconds once again. I will write about what I think is interesting and useful for others, and I am honest with myself and with you.</p><p>In the end, this article is about <em>my </em>writing journey, and not about anyone else. But I can share this data with you and I believe it is necessary to do so. Maybe if you start writing next week in a year you will have five hundred subscribers. Maybe twenty hundred. Maybe just one. But it will be <em>your </em>subscribers.</p><p>Keep learning!</p><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e70e01aacc22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Estimate the Number of Parameters in Transformer models]]></title>
            <link>https://medium.com/data-science/how-to-estimate-the-number-of-parameters-in-transformer-models-ca0f57d8dff0?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca0f57d8dff0</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 15:11:27 GMT</pubDate>
            <atom:updated>2023-06-19T14:52:54.377Z</atom:updated>
            <content:encoded><![CDATA[<h4>An inside look at the Transformer Encoder/Decoder building blocks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*FZlzHRmW0ObTZ-ZXQRBrBw.jpeg" /><figcaption>Preview. Image by Author</figcaption></figure><blockquote>Thanks to <a href="https://medium.com/u/84ea27feb7de">Regan Yue</a>, you can read the Chinese version of this article at <a href="https://mp.weixin.qq.com/s/-zAqPfR-RVeRYjX5raehtA">mp.weixin.qq.com</a>, <a href="https://juejin.cn/post/7243435843145924667">juejin.cn</a>, <a href="https://segmentfault.com/a/1190000043888810">segmentfault.com</a> and <a href="https://xie.infoq.cn/article/3d1edc1049f34d0f797231c2c">xie.infoq.cn</a>!</blockquote><p>The most effective way to understand new machine learning architecture (as well as any new technology in general) is to <em>implement it from scratch</em>. This is the best approach that helps you understand the implementation <em>down to the smallest details</em>, although it is very complex, time-consuming, and sometimes <strong>just impossible</strong>. For example, if you do not have similar computing resources or data you will not be able to make sure that there is no hidden bug in your solution.</p><p>However, there is a much easier way — to count the number of parameters. It’s not much harder than just reading the paper, but allows you to dig quite deep and check that you fully understand the building blocks of the new architecture (Transformer Encoder and Decoder blocks in our case).</p><p>You can think about this with the following diagram, which presents three ways to understand a new ML architecture —<em>the size of the circle represents the level of understanding</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*OLYaf8BtpYOWMCpfy7iAWw.png" /><figcaption>Ways to understand ML architecture. Calculating the number of parameters is not much more difficult than simply reading the paper, but it will allow you to delve deeper into the topic. Image by Author</figcaption></figure><p>In this article, we will take a look at the famous Transformer architecture and consider <strong>how to calculate the number of parameters</strong> in PyTorch <a href="https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html"><em>TransformerEncoderLayer</em></a> and <a href="https://pytorch.org/docs/stable/generated/torch.nn.TransformerDecoderLayer.html"><em>TransformerDecoderLayer</em></a><em> </em>classes. Thus, we will make sure that there are no mysteries left for us about what this architecture consists of.</p><h4>TL;DR</h4><p>All formulas are summarized in the <strong>Conclusions </strong>section. You are welcome to take a look at them right now.</p><p>I present not only exact formulas but also their less accurate <em>approximate versions</em>, which will allow you to <strong>quickly estimate</strong> the number of parameters in any Transformer-based model.</p><h3>Transformer Architecture</h3><p>The famous Transformer architecture was presented in the breathtaking <a href="https://arxiv.org/abs/1706.03762">“Attention Is All You Need” paper</a> in 2017 and became the de-facto standard in the majority of Natural Language Processing and Computer Vision tasks because of its ability to effectively capture long-range dependencies.</p><blockquote>Now, in early 2023, <a href="https://techcrunch.com/2022/12/22/a-brief-history-of-diffusion-the-tech-at-the-heart-of-modern-image-generating-ai/">diffusion</a> is gaining extreme popularity, mainly due to <a href="https://www.washingtonpost.com/technology/interactive/2022/ai-image-generator/">text-to-image generative models</a>. Maybe, soon <strong>they </strong>will become the new state-of-the-art in various tasks, as it was with Transformers vs LSTMs and CNNs. But let’s take a look at Transformers first…</blockquote><p>My article is not an attempt to explain Transformer architecture since there are enough articles that do it very well. It just might allow you <em>to look at it from a different side</em> or <em>clarify some details</em> if you haven’t fully figured it out yet. So if you are seeking more resources to learn about this architecture, I’m referring you to some of them; otherwise, you can just keep reading.</p><h4>Resources to know more about Transformer</h4><p>If you are looking for a more detailed Transformer architecture overview, take a look at these materials (note that there are plenty of other recourses on the Internet, I just personally like these):</p><ul><li>First of all, <a href="https://arxiv.org/abs/1706.03762">the official paper</a>. It may be not the best way for the first time, but it is not as complex as it seems. You can try <a href="https://www.explainpaper.com/papers/attention">Explainpaper to help you read this</a> or <a href="https://www.explainpaper.com/">other papers</a> (<em>it is an AI-based tool that can explain the text you highlight</em>).</li><li>Great <a href="https://jalammar.github.io/illustrated-transformer/">Illustrated Transformer article by Jay Alammar</a>. If you do not enjoy the reading, watch the <a href="https://youtu.be/-QH8fRhqFHM">YouTube video</a> by the same author.</li><li>Awesome <a href="https://www.youtube.com/watch?v=rBCqOTEfxvg">Tensor2Tensor talk by Lukasz Kaiser from Google Brain</a>.</li><li>If you want to go straight to practice and use various Transformer models to build real applications, check the <a href="https://huggingface.co/course/chapter1/1">Hugging Face course</a>.</li></ul><h4>Original Transformer</h4><p>To begin with, let’s remember Transformer basics.</p><p>The architecture of the Transformer consists of two components: the encoder (on the left) and the decoder (on the right). The encoder takes a sequence of input tokens and produces a sequence of hidden states, while the decoder takes this sequence of hidden states and produces a sequence of output tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*Wn_NVYkrlcxOwvDlyvqrlw.png" /><figcaption>Transformer architecture. Figure 1 from the <a href="https://arxiv.org/pdf/1706.03762.pdf">public domain paper</a></figcaption></figure><p>Both the encoder and decoder consist of a stack of identical layers. For the encoder, this layer includes <strong><em>multi-head attention</em></strong><em> (1 — here, and later numbers refer to the image below) </em>and a <strong><em>feed-forward neural network</em></strong><em> (2) </em>with some <strong><em>layer normalizations</em></strong><em> (3) </em>and skip connections.</p><p>The decoder is similar to the encoder, but in addition to the <em>first </em><strong><em>multi-head attention</em></strong><em> (4) </em>(which is <em>masked </em>for machine translation task so the decoder doesn’t cheat by looking at the future tokens) and a <strong><em>feedforward network (5)</em></strong>, it also has a <em>second </em><strong><em>multi-head attention</em></strong><em> mechanism (6)</em>. It<em> </em>allows the decoder to use the context provided by the encoder when generating output. As the encoder, the decoder also has some <strong><em>layer normalization</em></strong><em> (7) </em>and skip connections components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArPstPlS0zIEDfKA1VajXw.png" /><figcaption>Transformer architecture with signed components. Adapted from figure 1 from the <a href="https://arxiv.org/pdf/1706.03762.pdf">public domain paper</a></figcaption></figure><blockquote>I will not consider the input embedding layer with positional encoding and final output layer (linear + softmax) as Transformer components, focusing only on Encoder and Decoder blocks. I do so since these components are specific to the task and embedding approach, while both Encoder and Decoder stacks formed the basis of many other architectures later.</blockquote><blockquote>Examples of such architectures include BERT-based models for the Encoder (<a href="https://arxiv.org/abs/1810.04805">BERT</a>, <a href="https://arxiv.org/abs/1907.11692">RoBERTa</a>, <a href="https://arxiv.org/abs/1909.11942">ALBERT</a>, <a href="https://arxiv.org/abs/2006.03654">DeBERTa</a>, etc.), GPT-based models for the Decoder (<a href="https://paperswithcode.com/paper/improving-language-understanding-by">GPT</a>, <a href="https://paperswithcode.com/paper/language-models-are-unsupervised-multitask">GPT-2</a>, <a href="https://arxiv.org/abs/2005.14165v4">GPT-3</a>, <a href="https://openai.com/blog/chatgpt/">ChatGPT</a>), and models built on the full Encoder-Decoder framework (<a href="https://arxiv.org/abs/1910.10683v3">T5</a>, <a href="https://arxiv.org/abs/1910.13461">BART</a>, and others).</blockquote><p>Although we counted <em>seven</em> components in this architecture, we can see that there are only <em>three </em>unique ones:</p><ol><li>Multi-head attention;</li><li>Feed-forward network;</li><li>Layer normalization.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqnFnW06Jzt1RRgpNsMdug.png" /><figcaption>Transformer building blocks. Adapted from figure 1 from the <a href="https://arxiv.org/pdf/1706.03762.pdf">public domain paper</a></figcaption></figure><p>Together they form the basis of a Transformer. Let’s look at them in more detail!</p><h3>Transformer Building Blocks</h3><p>Let’s consider the internal structure of each block and how many parameters it requires. In this section, we will also start using <a href="https://pytorch.org/">PyTorch</a> to validate our calculations.</p><p>To check the number of parameters of a certain model block, I will use <a href="https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/9">the following one-line function</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43a7c17a6e047b72d08fc2bc1b9148f3/href">https://medium.com/media/43a7c17a6e047b72d08fc2bc1b9148f3/href</a></iframe><p>Before we start, pay attention to the fact that all blocks <strong>are standardized</strong> and used with skip connections. This means that <strong><em>the shape </em></strong><em>(more precisely, its last number, since the batch size and the number of tokens may vary)</em><strong><em> of all inputs and outputs must be the same</em></strong>. For the original paper, this number (<em>d_model</em>) is 512.</p><h4>Multi-Head Attention</h4><p>A famous attention mechanism is a key to Transformer architecture. But putting aside all motivations and technical details it is just a few matrix multiplications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VREqbcIqM19jNeEs7KI3VQ.png" /><figcaption>Transformer multi-head attention. Adapted from figure 2 from the <a href="https://arxiv.org/pdf/1706.03762.pdf">public domain paper</a></figcaption></figure><p>After calculating attention for every <em>head</em>, we concatenate all heads together and pass it through a linear layer (<em>W_O matrix</em>). In turn, each head is <em>scaled dot-product attention</em> with three separate matrix multiplications for the query, key, and value (<em>W_Q</em>, <em>W_K</em>, <em>and W_V matrices respectively</em>). These three matrices are <em>different for each head</em>, which is why subscript <em>i</em> is present.</p><p>The shape of the final linear layer (<em>W_O</em>) is <em>d_model to d_model</em>. The shape of the rest three matrices (<em>W_Q</em>, <em>W_K</em>, <em>and W_V)</em> is the same: <em>d_model to d_qkv</em>.</p><blockquote>Note that <strong>d_qkv</strong> in the image above is denoted as <strong>d_k </strong>or <strong>d_v</strong> in the original paper. I just find this name more intuitive, because although these matrices may have different shapes, it is almost always the same.</blockquote><blockquote>Also, note that <strong>d_qkv </strong>= <strong>d_model </strong>/ <strong>num_heads </strong>(<strong>h </strong>in the paper). That’s why <strong>d_model</strong> must be divisible by <strong>num_heads</strong>:<strong> </strong>to ensure correct concatenation later.</blockquote><p>You can test yourself by checking the shapes in all the intermediate phases in the picture above (the correct ones are indicated at the bottom right).</p><p>As a result, we need three smaller matrices for each head and one large final matrix. How many parameters do we need (do not forget biases)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89oTpB9sm9MklURisyLhFQ.png" /><figcaption>The formula for calculating the number of parameters in the Transformer attention module. Image by Author</figcaption></figure><p>I hope it’s not too tedious — I tried to make the deduction as clear as possible. Don’t worry! The future formulas will be much smaller.</p><p>The approximate number of parameters is such because we can neglect 4*d_model compared to 4*d_model^2. Let’s test ourselves using PyTorch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0765fc8b0d1fb37f262f332db87369a9/href">https://medium.com/media/0765fc8b0d1fb37f262f332db87369a9/href</a></iframe><p>The numbers match, meaning we are good!</p><h4>Feed-forward Network</h4><p>The feed-forward network in Transformer consists of two fully connected layers with a ReLU activation function in between. The network is built in such a way that its internal part is more expressive than input and output (which, as we remember, must be the same).</p><p>In general case, it is <em>MLP(d_model, d_ff) -&gt; ReLU -&gt; MLP(d_ff, d_model)</em>, and for original paper <em>d_ff</em> = 2048.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBWA7ShxGTmfKg-UdOcrPQ.jpeg" /><figcaption>Feed-forward neural network description. <a href="https://arxiv.org/pdf/1706.03762.pdf">Public domain paper</a></figcaption></figure><p>A little visualization never hurts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*ijeMTBMuZssyl3cVFCW41Q.png" /><figcaption>Transformer feed-forward network. Image by Author</figcaption></figure><p>The calculation of parameters is quite easy, the main thing, again, is not to get entangled by biases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ZI9r8ofotJyb-IN939rog.png" /><figcaption>The formula for calculating the number of parameters in the Transformer feed-forward net. Image by Author</figcaption></figure><p>We can describe such a simple network and check the number of its parameters using the following code (<em>note that official PyTorch implementation also uses </em><strong><em>dropout</em></strong><em>, which we will see later in Encoder/Decoder code. But as we know, the dropout layer does not have trainable parameters, so I omit it here for simplicity)</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38478b2ba5c159c75fecda0100b6b121/href">https://medium.com/media/38478b2ba5c159c75fecda0100b6b121/href</a></iframe><p>The numbers match again, and only one component remains.</p><h4>Layer Normalization</h4><p>The last building block of the Transformer architecture is <a href="https://arxiv.org/abs/1607.06450">layer normalization</a>. Long story short, it is just an intelligent (i.e. <em>learnable</em>) way of <em>normalization with scaling</em>, that improves the stability of the training process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTQWH1hKpALTpVCK2TN3_w.png" /><figcaption>Transformer layer normalization. Image by Author</figcaption></figure><p>The trainable parameters here are two vectors <em>gamma </em>and <em>beta</em>, each of which has a <em>d_model </em>dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_iJ83Gxv49lF0tBeURiFWg.png" /><figcaption>The formula for calculating the number of parameters in the Transformer layer normalization module. Image by Author</figcaption></figure><p>Let’s check our assumptions with code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b468ca89f8b973557da430eff2918a6/href">https://medium.com/media/3b468ca89f8b973557da430eff2918a6/href</a></iframe><p>Good! In approximate calculations, this number can be neglected, since layer normalization has dramatically fewer parameters than feed-forward network or multi-head attention block (despite the fact that this module occurs several times).</p><h3>Derive Complete Formulas</h3><p>Now we have everything to count the parameters for the entire Encoder/Decoder block!</p><h4><strong>Encoder and Decoder in PyTorch</strong></h4><p>Let’s remember that the Encoder consists of an attention block, feed-forward net, and two layer normalizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*AERuFeB38A-riZaL7uCOCA.png" /><figcaption>Transformer Encoder. Adapted from figure 1 from the <a href="https://arxiv.org/pdf/1706.03762.pdf">public domain paper</a></figcaption></figure><p>We can verify that all components are in place by looking inside the PyTorch code. Here <em>multi-head attention</em> is indicated <em>in red</em> (on the left), <em>the feed-forward network</em> <em>in blue</em> and <em>layer normalizations in green</em> (screenshot of the Python console in PyCharm).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhzMy_e5u-9bNH0oOB2gGA.png" /><figcaption>PyTorch TransformerEncoderLayer. Image by Author</figcaption></figure><p>As noted above, this implementation includes <em>dropout </em>in the feed-forward net. Now we can see the dropout layers related to layer normalizations as well.</p><p>The decoder, in turn, consists of two attention blocks, a feed-forward net, and three layer normalizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*4NlgbSQ-Z9Fx5kOqq2D5Ng.png" /><figcaption>Transformer Decoder. Adapted from figure 1 from the <a href="https://arxiv.org/pdf/1706.03762.pdf">public domain paper</a></figcaption></figure><p>Let’s look at PyTorch again (the colors are the same).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xT_Wr0kGFVcSEkDswj4GbQ.png" /><figcaption>PyTorch TransformerDecoderLayer. Image by Author</figcaption></figure><h4>Final Formula</h4><p>After making sure, we can write the following function to calculate the number of parameters. In fact, these are just three lines of code that can even be combined into one. The rest of the function is a docstring for clarification.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45d56b202b32cd5542841cb8aaa8707a/href">https://medium.com/media/45d56b202b32cd5542841cb8aaa8707a/href</a></iframe><p>Now it’s time to test it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9b5873047c861b8d482733e28d61662/href">https://medium.com/media/a9b5873047c861b8d482733e28d61662/href</a></iframe><p>The exact formulas are correct, meaning we have correctly identified all building blocks and deconstructed them into their components. Interestingly, since we ignored relatively small values (<em>thousands compared to millions</em>) in the approximate formulas, <strong>the error is only about 0.2% </strong>compared to the exact results! But there is a way to make these formulas even simpler.</p><p>The approximate number of parameters for the attention block is 4*d_model^2. It sounds pretty simple, considering that <em>d_model </em>is an important hyperparameter. But for the feed-forward network, we need to know <em>d_ff</em>, since the formula is 2*d_model*d_ff.</p><p><em>d_ff </em>is a separate hyperparameter that you have to memorize in the formula, so let’s think about how to get rid of it. In fact, as we saw above, <em>d_ff = 2048</em> when <em>d_model = 512</em>, so <strong><em>d_ff = 4*d_model</em></strong>.</p><p>For many Transformer models, such an assumption will make sense, <em>greatly simplifying the formula</em>, and still giving you an <strong>estimate </strong>of the approximate number of parameters. After all, no one wants to know the precise amount, it’s just useful to understand whether this number is in the <em>hundreds of thousands</em> or <em>tens of millions</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HxvwZu75cb9-TQkcAE12Q.png" /><figcaption>Approximate Encoder-Decoder formulas. Image by Author</figcaption></figure><p>To get an understanding of <em>the order of magnitude</em> you are dealing with, you can also round the multipliers and you will get 10*d_model^2 for every Encoder/Decoder layer.</p><h3>Conclusions</h3><p>Here is a summary of all the formulas that we have deduced today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCJzow8uTLcR7IAgSWnwfQ.jpeg" /><figcaption>Formulas recap. Image by Author</figcaption></figure><p>In this article, we’ve calculated the number of parameters in Transformer Encoder/Decoder blocks, but of course, I don’t invite you to count the parameters of all new models. I have just chosen this method because I was surprised that I didn’t find such an article when I started studying Transformers.</p><p>While the number of parameters can give us an indication of the complexity of the model and the amount of data it will require to train, it is just one way to gain a deeper understanding of the architecture. I want to encourage you to explore and experiment: take a look at implementation, run the code with different hyperparameters, etc. So, keep learning and have fun!</p><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca0f57d8dff0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-estimate-the-number-of-parameters-in-transformer-models-ca0f57d8dff0">How to Estimate the Number of Parameters in Transformer models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graphs with Python: Overview and Best Libraries]]></title>
            <link>https://medium.com/data-science/graphs-with-python-overview-and-best-libraries-a92aa485c2f8?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/a92aa485c2f8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 16:05:51 GMT</pubDate>
            <atom:updated>2022-12-02T22:42:35.959Z</atom:updated>
            <content:encoded><![CDATA[<h4>Graph analysis, interactive visualizations, and graph machine learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*s-iEx2JayetWaWVKcwQCAQ.jpeg" /><figcaption>Preview. Image by Author</figcaption></figure><p>A <strong>graph </strong>is a relatively old mathematical data entity that is a set of connected elements. Since the graph is a very <em>flexible </em>structure and allows you to store information in a form familiar and convenient to humans, graphs have always been used in computer science and technology. With the rise of machine learning and deep learning, graphs have gained even more popularity by creating the field of <strong>graph machine learning</strong>.</p><p>In this post, I would like to share with you the most useful Python libraries I’ve used for graph/network analysis, visualization, and machine learning. Today, we will review:</p><ul><li><a href="https://networkx.org/">NetworkX</a> for general graph analysis;</li><li><a href="https://pyvis.readthedocs.io/en/latest/">PyVis</a> for interactive graph visualizations right in your browser;</li><li><a href="https://www.pyg.org/">PyG</a> and <a href="https://www.dgl.ai/">DGL</a> for solving various graph machine learning tasks.</li></ul><p>Before that, let me tell you a few words about <strong>graph theory</strong> and <strong>graph machine learning</strong> and provide some learning resources that may be helpful to you. If you don’t know what graph or graph machine learning is, that is a great opportunity to lift the veil of secrecy!</p><h3>Graph Theory and Graph Machine Learning: a Brief Introduction</h3><p>The graph is simply a set of elements connected to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*JFXEQ4rj9Wd-10-bqSEuRw.png" /><figcaption>Graph example. <a href="https://commons.wikimedia.org/wiki/File:Graph_example_%28Graph_theory%29.png">Public domain</a></figcaption></figure><p>However, the fact these elements (called <em>nodes</em>) can contain any information and can be connected in any way (with <em>edges</em>) makes the graph the <strong>most general data structure</strong>. Indeed, any complex data familiar to us can be represented as a simple graph: for example, an image — as a grid of pixels or text — as a sequence (or chain) of words.</p><p>You might wonder: are graphs really <em>so</em> important? Well, some tasks simply cannot be solved or even formulated without them, as some information cannot be structured in data. Imagine the following situation: you need to visit a list of cities, say for tourism or for work. You have information about the distance from one city to another, or say, the cost of tickets for different transport modes — it’s even more interesting! How to create an <em>optimal route</em>, that is, spend the minimum amount of money or drive a minimum distance?</p><p>For me, the task is quite practical — think at least about its application in logistics. And, this is an example of a problem that cannot be solved without the help of graphs. Think about how you will represent the data and in any case, you will still come to the <em>weighted </em>graph (a graph whose edges have some value, called <em>weight</em>). By the way, if each city needs to be visited exactly once, this task turns into the famous <a href="https://www.youtube.com/watch?v=1pmBjIZ20pE">traveling salesman problem (TSP)</a>, which is not so easy to solve. One of the reasons is that the number of possible routes is growing very fast, and even for 7 cities, there are already 360 of them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*KrZyOfyaAz5b4utRmHXgnw.gif" /><figcaption>The solution to a TSP with 7 cities using brute force search. <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem#/media/File:Bruteforce.gif">Public domain</a></figcaption></figure><p><strong>Graph theory</strong> (originated in the 18th century) was engaged in the study of graphs and solving various graph problems: finding a possible or optimal path in a graph, building and researching <em>trees </em>(a special type of graph), and so on. Graph theory was successfully used in social sciences, chemistry, biology, and other fields. But with the development of computers, the process of using graphs has reached another level.</p><p>What is really important is that this base: <em>a set of related elements</em>, often with different elements and types of connections, is very useful for modeling real-world tasks and datasets. This is the place where graph machine learning comes into the picture (although amazing tasks were solved before it as well). After humanity collected the appropriate datasets and developed technologies to model them (like <a href="https://towardsdatascience.com/graph-convolutional-networks-deep-99d7fee5706f"><em>Graph Convolutional Networks (GCNs)</em></a>, by analogy with <a href="https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53"><em>Convolutional Neural Networks (CNNs)</em></a>) it becomes possible to solve a wide range of graph tasks:</p><ul><li>Node-level tasks, like <strong>node classification</strong> — assign a label for every node in the graph. We will see an example a little below — divide a group of people into two clusters, knowing how they communicate with each other; but other applications can be very different. The intuition here comes from <em>social science</em>, which says that we are dependent on our environment. Indeed, any entity can be classified more effectively taking into account not only some set of features but also data about its neighborhood. For example, if your friends smoke, you are more likely to smoke, and if your friends go to the gym, you are more likely to go to the gym.</li><li>Edge-level tasks, like <strong>edge prediction</strong> — predict if two nodes have an edge or, more often, predict <em>edge type</em> (graphs that have several edge types are called <em>multigraphs</em>). This task is very interesting for the <em>knowledge graphs</em>, which we see in a couple of minutes.</li><li>Graph-level tasks. This can be <strong>graph classification</strong>, <strong>graph generation,</strong> and so on. This field is especially useful for biology and chemistry because <em>molecules can be effectively represented as graphs</em>. Molecule classification (determining if the molecule has certain properties) or molecule generation (and especially drug generation) sounds much cooler than some “graph-level tasks”!</li></ul><p>Let’s take a look at examples of graphs from real life. One of the most famous graph datasets is the <a href="http://konect.cc/networks/ucidata-zachary/">karate club dataset</a>. Here, each node is a person (club member), and each edge represents the two members who interacted outside of the club.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNuDg6RnCJpV8YxzwzCEuA.png" /><figcaption>Karate club dataset visualization. <a href="https://en.wikipedia.org/wiki/Zachary&#39;s_karate_club#/media/File:Zachary_karate_club_social_network.png">Public domain</a></figcaption></figure><p>A common problem is finding two groups of people into which the club split after an argument between two instructors (now we can treat it as <em>binary (or 2-class) node classification</em>). The dataset was collected back in 1977 and become a classic example of a <em>human social network</em> or <em>community structure</em>.</p><p>Another graph type, interpretable for humans, and therefore extremely useful for machine learning models is a <em>knowledge graph</em>. In a knowledge graph, a node is some entity or concept and an edge represents knowledge about the interaction of a pair of entities. Thus, the <em>node-edge-node</em> structure stores a certain fact about the world or a particular system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bx-Qpdw76av6vKNdoLmgA.png" /><figcaption>A simple example of the knowledge graph. <a href="https://en.wikipedia.org/wiki/Knowledge_graph#/media/File:Conceptual_Diagram_-_Example.svg">Public domain</a></figcaption></figure><p>The knowledge graph in the example above contains two types of edges: <em>is </em>and <em>eat </em>and is thus a <strong>multigraph </strong>we introduced earlier. The <em>Dogs-is-Animals</em> structure gives us the knowledge that <em>the “dogs” set is a subset of the “animals” set</em>, or, in simpler terms, that <em>dogs are animals</em>.</p><p><a href="https://www.wikidata.org/wiki/Wikidata:Main_Page">Wikidata</a> is a huge free knowledge base by Wikipedia, which is constantly updated and has more than <strong>100 million</strong> nodes now. There are more than 400 edge types, some of which are <em>part of</em>, <em>different from</em>, <em>opposite of</em>, <em>population</em>, and <em>location</em>, so definitely make sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*J1OSSjdrFNB4zTOUJyNOuQ.jpeg" /><figcaption>Top 20 edge relations in the wikidata knowledge base for 2020. <a href="https://wikidataworkshop.github.io/2020/papers/Wikidata_Workshop_2020_paper_10.pdf">Public domain</a></figcaption></figure><p>That huge knowledge base contains a lot of information about the world around us. It’s still amazing to me how humanity has collected this data, and that machines are now able to process it!</p><p>One more thing I can’t keep silent about is <strong>wikidata&#39;s beautiful visualization capabilities</strong>. For example, here you can see the plot of connectivity of the United States states. Note that it is not drawn by anyone, it is just a subgraph of the entire wikidata graph: we took only American states as nodes and <a href="https://www.wikidata.org/wiki/Property:P47">P47 (shares border with)</a> as edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*YrCW75mlvgr2uSsRtD7SZQ.jpeg" /><figcaption>Connectivity of the USA states. <a href="https://angryloki.github.io/wikidata-graph-builder/?mode=wdqs&amp;wdqs=SELECT%20%3Fitem%20%3FitemLabel%20%3FlinkTo%20%7B%0A%20%20%3Fitem%20wdt:P31%20wd:Q35657%20.%0A%20%20OPTIONAL%20%7B%20%3FlinkTo%20wdt:P47%20%3Fitem%20;%20wdt:P31%20wd:Q35657%20%7D%20.%0A%0A%20%20SERVICE%20wikibase:label%20%7Bbd:serviceParam%20wikibase:language%20%22en%22%20%7D%0A%7D">Public domain</a></figcaption></figure><p>Take a look at <a href="https://angryloki.github.io/wikidata-graph-builder/">Wikidata Graph Builder</a> and <a href="https://www.wikidata.org/wiki/Wikidata:Tools/Visualize_data">other visualizations</a>. Let me point you to some of them that I find entertaining:</p><ul><li><a href="https://projetjourdain.org/network/index.html">Map of the relationships between master and student from Socrates to the end of the Hellenistic Period</a></li><li><a href="http://histropedia.com/timeline-everything.html">Interactive timelines with historical events</a></li><li><a href="https://wikioverdata.toolforge.org/wikitree/public/?q=Q15928745&amp;level=3&amp;type=descendants&amp;orientation=North&amp;lang=en">Pan Pan panda family tree</a></li></ul><h4>Know More about Graphs</h4><p>If after that brief overview you are now interested in graphs and want to know more about them, I refer you to the wonderful <a href="https://distill.pub/2021/gnn-intro/">Gentle Introduction to Graph Neural Networks by Google Research</a>. In this article, you can find more examples and interactive visualizations.</p><p>Check the <a href="https://www.youtube.com/watch?v=09_LlHjoEiY">Graph Theory Algorithms course by freeCodeCamp.org</a> for various graph theory algorithms overviews or <a href="https://www.youtube.com/playlist?list=PLoROMvodv4rPLKxIpqhjhPgdQy7imNkDn">Stanford CS224W: Machine Learning with Graphs course</a> to start your graph machine learning journey.</p><p>After that brief introduction, let’s actually start with Python libraries!</p><h3>NetworkX — General Graph Analysis</h3><p>If you have to do some operations on graphs and you use Python as your programming language, you will most likely find the NetworkX library pretty quickly. It is probably the most fundamental and commonly used library for network analysis that provides a wide range of functionality:</p><ul><li>Data structures for storing and operating on undirected or directed graphs and multigraphs;</li><li>Many graph algorithms implemented;</li><li>Basic visualization tools.</li></ul><p>The library is pretty intuitive and easy to use. Also, the majority of fundamentals, like <em>graph data structures</em> will remain the same or at least similar for all popular graph libraries. For clarity, you can create a simple graph and visualize it with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ca583e287c5bdc6d425954c107dc246/href">https://medium.com/media/5ca583e287c5bdc6d425954c107dc246/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*_DuuDZAVtaOIfxEHnwfo8g.png" /><figcaption>Basic NetworkX visualization. Image by Author</figcaption></figure><p>When it comes to algorithms, networkx is pretty powerful and has <a href="https://networkx.org/documentation/stable/reference/algorithms/index.html"><strong>hundreds </strong>of graph algorithms implemented</a>.</p><p>To summarize, this is an efficient, scalable, and powerful library, that will definitely be useful for you if you are dealing with graph analysis.</p><h4>Reference</h4><p><a href="https://networkx.org/">NetworkX - NetworkX documentation</a></p><h3>PyVis — Interactive Graph Visualizations</h3><p>Using networkx for graph visualization can be pretty good for little graphs but if you need more <strong>flexibility</strong> or <strong>interactivity</strong>, you better give PyVis a chance. The situation is similar to <a href="https://matplotlib.org/">matplotlib</a> vs <a href="https://plotly.com/">plotly</a>. Using matplotlib for quick and straightforward visualizations is perfectly fine, but if you need to interact with your chart or present it to somebody else, you better use more powerful tools.</p><p>PyVis is built on the <a href="https://visjs.github.io/vis-network/examples/">VisJS library</a> and produces interactive visualizations in your browser with simple code. Let’s plot the same graph as in the example above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c319cb28407e13d88152725c0d9c86e9/href">https://medium.com/media/c319cb28407e13d88152725c0d9c86e9/href</a></iframe><p>This code will create a graph.html file. By opening it, you will be able to interact with your visualization: zoom it, drag it, and much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*B7jnuQi-jOud-C1lc_Qlsg.gif" /><figcaption>PyVis visualization example. Gif by Author</figcaption></figure><p>Looks interesting, right? The library even allows you to use web UI to dynamically tweak display configurations. Definitely check the official tutorial that will walk you through the main library’s capabilities.</p><h4>Reference</h4><p><a href="https://pyvis.readthedocs.io/en/latest/">Interactive network visualizations - pyvis 0.1.3.1 documentation</a></p><h3>DGL and PyG Graph Machine Learning</h3><p>Let’s now switch to the more advanced topic — graph machine learning. I will mention two of the most popular libraries for it: DGL and PyG.</p><p>DGL (Deep Graph Library) was initially released in 2018. In contrast to PyG (PyTorch Geometric), which is built on top of the PyTorch and therefore supports only PyTorch tensors, DGL supports multiple deep learning frameworks, including PyTorch, TensorFlow, and MXNet.</p><p>Both libraries implement popular <em>Graph Neural Network (GNN) cells</em> such as <em>GraphSAGE</em>, <em>GAT (Graph Attention Network)</em>, <em>GIN (Graph Isomorphism Network)</em>, and others. It will not be difficult to build a model from pre-made blocks — the process is very similar to plain PyTorch or TensorFlow.</p><p>Here is how you can create a 2-layer GCN model for node classification in PyG:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0124baa7bed684fb802b6c9dfe7607e/href">https://medium.com/media/b0124baa7bed684fb802b6c9dfe7607e/href</a></iframe><p>And the same code for DGL:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5805e459fc4ac393bb572e416eb1ae8c/href">https://medium.com/media/5805e459fc4ac393bb572e416eb1ae8c/href</a></iframe><p>Both code snippets are pretty straightforward if you are familiar with deep learning and PyTorch.</p><p>As you see, the model definition is very similar for both libraries. The training loop then can be written on the plain PyTorch for PyG and require some modifications for DGL (since DGL graph objects store the entire dataset, and you have to address train/validation/test sets using binary <em>masks</em>).</p><p>There is a slight difference in data representation here: you can see it at least based on the different input parameters for the forward method. Indeed, PyG stores everything as PyTorch tensors and DGL has a separate graph object that you have to use, and under the hood, it follows a more classical NetworkX style.</p><p>However, that is not a big deal — you can convert the PyG graph object to the DGL graph and vice versa with a few lines of code. The more important question is: how else are they different? And which one should you use?</p><h4>DGL vs PyG</h4><p>Trying to figure out which of the libraries is better, you will keep coming across the same answer — “<em>try both and decide which works best for you”</em>. Okay, but how are they at least different? Again, the answer that you will constantly encounter is “<em>they are quite similar”</em>.</p><p>And they really are! Moreover, you saw it for yourself by looking at the code a few minutes ago. But of course, you can find some differences digging deeper: <a href="https://discuss.dgl.ai/t/dgl-vs-pytorch-geometric/346/8">here is a good resource list including a few thoughts by library authors</a>, and <a href="https://blog.paperspace.com/geometric-deep-learning-framework-comparison/">here is a pretty detailed comparison on different sides</a>.</p><p>In general, the answer is really <em>to try both</em>. In fact, DGL has more low-level API and can be harder to use in the sense of implementing new ideas. But this makes it more flexible: DGL is not limited to <em>message-passing networks </em>(classical <em>Graph Convolutional Networks</em>)<em> </em>and has the implementation of several concepts that PyG can not provide, for example, <a href="https://docs.dgl.ai/tutorials/models/2_small_graph/3_tree-lstm.html">Tree-LSTM</a>.</p><p>PyTorch Geometric, on the other hand, makes his API as easy as possible and then gains more popularity among researchers that can quickly implement new ideas, i.e. new GNN cells. In the past time, <a href="https://trends.google.com/trends/explore?date=today%205-y&amp;q=Deep%20Graph%20Library,PyTorch%20Geometric">PyG becomes more and more popular</a> due to important updates with PyG 2.0 and active and powerful teams of collaborators, including Stanford University.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sOkyLMofokxsDP47v54vw.jpeg" /><figcaption>Number of DGL vs PyG search queries over the last 5 years. <a href="https://trends.google.com/trends/explore?date=today%205-y&amp;q=Deep%20Graph%20Library,PyTorch%20Geometric">Public domain</a></figcaption></figure><p>So I still encourage you to try both of them, <em>giving PyG the chance first</em>.</p><p>If you are working on a relatively familiar graph problem (be it node classification, graph classification, etc.), both <a href="https://pytorch-geometric.readthedocs.io/en/latest/notes/cheatsheet.html">PyG</a> and <a href="https://docs.dgl.ai/api/python/nn-pytorch.html#conv-layers">DGL</a> have a huge amount of GNN cells implemented. Also with PyG, it will be easier for you to implement your own GNN as part of any research.</p><p>However, if you want to get full control over what is happening under the hood or implement something more complicated than the message-passing framework, your choice will most likely fall on DGL.</p><h4>References</h4><ul><li><a href="https://www.pyg.org/">PyG official website</a>, <a href="https://pytorch-geometric.readthedocs.io/en/latest/">PyG documentation</a></li><li><a href="https://www.dgl.ai/">DGL official website</a>, <a href="https://docs.dgl.ai/">DGL documentation</a></li></ul><h3>Conclusion</h3><p>The target audience of this article (people interested in graphs) is quite small. Well, machine learning is a fairly young field of computer science, and graph machine learning is even younger. The last mainly attracts the attention of the research community, but, believe it or not, it is used in important real-world applications such as recommendation systems and biology/chemistry studies.</p><p>In any case, I hope these materials were interesting or helpful for you — whether you were looking for anything specific or just learned something new today. As a recap, today we briefly reviewed what graph and graph machine learning is, and took a look a the following libraries:</p><ul><li><a href="https://networkx.org/">NetworkX</a>: general graph analysis;</li><li><a href="https://pyvis.readthedocs.io/en/latest/">PyVis</a>: interactive graph visualizations;</li><li><a href="https://www.pyg.org/">PyG</a> and <a href="https://www.dgl.ai/">DGL</a>: machine learning on graphs.</li></ul><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a92aa485c2f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/graphs-with-python-overview-and-best-libraries-a92aa485c2f8">Graphs with Python: Overview and Best Libraries</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What you need to know about updated Machine Learning Specialization by DeepLearning.AI]]></title>
            <link>https://medium.com/data-science/what-you-need-to-know-about-updated-machine-learning-specialization-by-deeplearing-ai-97118fa03297?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/97118fa03297</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Thu, 11 Aug 2022 00:56:46 GMT</pubDate>
            <atom:updated>2024-02-18T19:59:54.123Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything new is a well-forgotten old, isn’t it?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBNF_N3GL0k_xM9coHXPAQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dietmarbecker?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dietmar Becker</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>On April 18th, 2022, at Coursera’s 10th anniversary, Andrew Ng (founder of <a href="https://www.deeplearning.ai/">DeepLearning.AI</a>, co-founder of <a href="https://www.coursera.org/">Coursera</a>, and one of the most famous popularizers of Machine Learning and AI) released a new <a href="https://www.coursera.org/specializations/machine-learning-introduction">Machine Learning Specialization</a>. This is an updated version of the original Machine Learning Stanford course created back in 2010, which was taken by about 5 million people since it was initially released.</p><p>I took the original course some time ago and have taken the updated one as soon as it was finished in July. Let’s take a closer look at these learning materials and find out, what exactly has been updated and if is it worth taking this course in 2022.</p><h4>TL;DR</h4><p>Yes, it is. In my view, now this is the <strong>best way to start your machine learning journey</strong> <em>especially if you are a complete beginner</em> and have never heard about data science and machine learning before.</p><h3>Previous article</h3><p>In my <a href="https://towardsdatascience.com/what-you-need-to-know-before-taking-the-machine-learning-course-by-stanford-84fd7bf94628">previous article on this topic</a>, I shared my thoughts about Stanford’s original Machine Learning course. There I listed my personal opinion about the drawbacks of the course and suggestions on what it would be worth to supplement it with.</p><p>Now that I have taken both versions — original and updated, in my further reasoning, I will rely on the theses expressed in this article (mostly in <strong>Comparison with the Original Course</strong> section). So, if you want to get familiar with my initial thoughts, I share the link to my previous article below.</p><p><a href="https://towardsdatascience.com/what-you-need-to-know-before-taking-the-machine-learning-course-by-stanford-84fd7bf94628">What you need to know before taking the Machine Learning course by Stanford</a></p><h3>Comparison with the Original Course</h3><p>In this section, I’m going to compare two versions of the course based largely on what I’ve stated before. I don’t know if someone from the DeepLearning.AI team has read my review, but almost all of my claims were properly considered and satisfied. :)</p><h4><strong>Outdating</strong></h4><p>In my previous article, I said that the main drawback of this course is that it is outdated. Of course, I was not the only one who understood this, and I think this was the main reason for its update.</p><p>Although <strong>the basics that the course talks about will never change</strong>, it’s much more pleasant to know that all the information you receive, including assignments and practical examples, is topical and relevant to the present.</p><p>Based on the numerous advantages of the course, <strong>the elimination of this disadvantage only is already a sufficient condition for this course to be a</strong> <strong>very good</strong> <strong>learning material</strong>. But its creators went further, refining and improving the educational plan and ways of interacting with students, not only by updating the course but also by making it more complete, broad, and interesting.</p><h4>Python Instead of Octave</h4><p>In the original course, practical assignments had to be solved on Octave (MATLAB). And although there were ways around it, the official implementation didn’t use Python. Fortunately for everyone, this has been fixed, and <strong>now the course uses Python</strong>.</p><p>This means not only that you don’t need to learn a programming language that you will almost certainly never use again in your life (sorry, MATLAB programmers). It also means that together with Python, you will get the basic knowledge about the libraries that you will use almost every day if you start working in data science or machine learning: <a href="https://numpy.org/"><em>numpy</em></a>, <a href="https://scikit-learn.org/stable/"><em>scikit-learn</em></a><em>,</em> and <a href="https://www.tensorflow.org/"><em>TensorFlow</em></a>. It’s just great!</p><p>It is important to note that the course <strong>does not teach you Python</strong>, and you need to understand the basics of this language and programming in general — variables, conditional expressions, loops, and functions will be quite enough (classes and <em>Object Oriented Programming</em> in its purest form is not used in the course). So if you are a complete beginner, maybe you should take <a href="https://www.youtube.com/watch?v=rfscVS0vtbw">some Python basics course</a> first.</p><h4>Ensemble Learning</h4><p>The original course did not mention any of the ensemble models, but now it will tell you in detail about <em>Decision Trees </em>(which also didn’t happen before), explain the motivation of <em>ensemble learning</em>, and demonstrate the <em>Random Forest</em> and <em>Boosting </em>models.</p><p>Although ensemble learning is explained here only in the context of decision trees and not other models, it is a <strong>step in the right direction</strong> that allows you to get a more complete picture of the machine learning models zoo.</p><p>You will also be shown the <a href="https://xgboost.readthedocs.io/en/stable/">XGBoost library</a>, one of the most powerful tools of <em>classical machine learning</em> (by <em>classical </em>I mean machine learning without deep neural networks), so you get it into your toolbox right away!</p><h4>Categorical Variables</h4><p>The original course also did not mention categorical variables at all, which seems very strange to me, because it will confuse a beginner in the very first task that he decided to solve on his own (since categorical variables are very common). This fault has been corrected here, and the course will tell you about <em>one-hot encoding</em>.</p><p>You will have to get acquainted with the rest of the methods by yourself, but since this course is designed for beginners, I do not consider this a disadvantage.</p><h4>Unsupervised Learning Algorithms: Clustering, Anomaly Detection, and Dimensionality Reduction</h4><p>As for unsupervised learning algorithms, the situation has remained about the same. <em>K-Means</em> only is considered for clustering, as well as <em>Gaussian Mixture Models (GMM)</em> for anomaly detection.</p><p>Dimensionality reduction is mentioned in the course as an auxiliary technique, and less attention is paid to it than before when we have a couple of separate lectures on <em>Principal Component Analysis (PCA)</em>.</p><p><em>Update: However, in December 2022, the course was updated a little more, and several videos about PCA were returned as like in the original course.</em></p><p>Although it may seem that I consider many other approaches overlooked (and last time I thought so) I’ve changed my mind, which I’ll talk about a bit later.</p><h4>Sorry, Support Vector Machine</h4><p>Before moving on to more general considerations, to be completely honest, I should note that <strong>Support Vector Machine</strong> <strong>materials were cut out of the updated course</strong>, although the original course contained them.</p><p>Perhaps the mention of <em>SVM </em>did not fit into the course due to timekeeping, but I think that it was removed because of the complexity since this algorithm with its kernel trick is quite difficult to understand and is probably the most difficult aspect of classical supervised learning.</p><p>So, I think it was removed to not scare off newcomers; in any case, changing <em>SVM </em>to <em>Decision Trees</em>, <em>Random Forest</em> and <em>Boosting </em>is a good exchange.</p><p><em>Update: After the addition of PCA and backpropagation materials in December 2022, it is quite possible that SVM will be included in the program with some upcoming updates.</em></p><h3>What else? More General Reasoning</h3><h4>Structuredness</h4><p>Updated specialization has become <strong>much more structured</strong>. The original source consisted of 11 weeks, the materials inside of which were not separated from each other.</p><p>Now, the content of the specialization is divided into 3 courses, each of which has a specific topic and an internal division by weeks. So <strong>it becomes much easier to navigate inside the course</strong>, return to it and search for particular materials. By the way, these three courses are:</p><ol><li>Supervised Machine Learning: introduction to machine learning, regression (linear regression), and classification (logistic regression);</li><li>Advanced Learning Algorithms: neural networks, decision trees, random forest, boosting, and practical advice for applying machine learning;</li><li>Unsupervised Learning, Recommenders, Reinforcement Learning: clustering, anomaly detection, recommender systems, and reinforcement learning.</li></ol><p>See the <a href="https://www.coursera.org/specializations/machine-learning-introduction">specialization homepage</a> to get a more detailed description.</p><h4>More Labs, More Visualizations, and More Interactivity</h4><p>Another good solution, in my opinion, is to include more practical labs and allow people to see more code. Since the code can now be executed in Jupyter Notebooks, this has freed the authors’ hands. Labs (almost all of which are optional, so no one will be scared off) have become more numerous, detailed, and diverse.</p><p>At the same time, many of them contain very intuitive and interactive visualizations. The quality of some of them, let’s be honest, could have been better (I honestly don’t understand why they used pure <a href="https://matplotlib.org/"><em>matplotlib</em></a><em> </em>even for interactive plots instead of for example <a href="https://plotly.com/"><em>plotly</em></a>) but some of them really allow you to get very useful insights.</p><p>To get an idea of what kind of interactivity is meant, you can see the <a href="https://www.youtube.com/watch?v=D1W0kS40otM&amp;t=4870s">most recent specialization demo on YouTube</a>.</p><h4>The Third Course is Amazing</h4><p>Although I said that it would be possible to mention more algorithms and approaches for unsupervised learning tasks, the third course of specialization <strong>covers much more than an analogous part before</strong>.</p><p>Clustering and anomaly detection are reviewed only during the first week. The second week is devoted to two algorithms of the most commercially successful machine learning application, recommender systems: <em>collaborative filtering</em> and <em>content-based filtering</em>, and the third week is dedicated to <em>Deep Q-Learning (DQL)</em>, a <em>reinforcement learning </em>algorithm, which is really awesome!</p><p>First, tales about reinforcement learning are always very inspiring, at least to me since I think this is the most “machine”-based part of machine learning. Second, the teaching talent of Andrew Ng and the course team make this, one of the most complex fields of science, or at least its basics, understandable for everyone.</p><p>By the way, reinforcement learning is a part of machine learning, where an <em>agent </em>learns to do something in a given <em>environment </em>without knowing anything about how things work, and receiving only <em>rewards </em>in the case of success. This part of machine learning is also the most popular in news: that is where robots learn to play <a href="https://spectrum.ieee.org/how-ibms-deep-blue-beat-world-champion-chess-player-garry-kasparov">chess</a>, <a href="https://www.bbc.com/news/technology-40042581">go</a>, or <a href="https://www.newscientist.com/article/2221840-deepminds-starcraft-playing-ai-beats-99-8-per-cent-of-human-gamers/">video games</a>. You can also find a dozen of YouTube videos where AI agents learn different things: from walking to boxing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*kMSbc1N6kVanqWpD" /><figcaption>Reinforcement Learning diagram. <a href="https://commons.wikimedia.org/wiki/File:Reinforcement_learning_diagram.svg">Public domain</a></figcaption></figure><p>Putting all together, the third course shows an <strong>extremely broad picture of real-world machine learning applications</strong> and takes specialization to the next level.</p><h4>Definitely, the Specialization was Designed for Beginners</h4><p>For a variety of authors&#39; reasons, specialization was made as simple as possible, <em>sometimes even too much</em>. This is not a drawback, but rather an advantage for the majority of learners, but in any case, it is a feature that has several consequences.</p><p>Most of all, this concerns people who are familiar with high school mathematics (and understand what is a derivative, optimization tasks, why gradient descent really works, etc.). There will be a lot of <em>understatement</em> in the course for you, as if you lack additional lectures describing the math behind certain algorithms. This is because the <em>course tries to do without math at all</em>, but sometimes it looks strange, for example <strong>not mentioning backpropagation</strong> when talking about neural networks.</p><p><em>Update: A couple of lectures about backpropagation were added in the December 2022 update, so this comment has lost its relevance.</em></p><p>Of course, you can fill in these understatements by reading one of the many books or by taking a more advanced ML course. But if you are a computer science student, there <strong>may be more effective ways</strong> to dive into the world of AI, data science, and machine learning specifically for you. After all, you <strong>really don’t need a strong mathematical background to start exploring ML</strong>, but <em>you may need to know a lot of mathematical points if you decide to do it seriously</em>.</p><h3>Summary</h3><p>The hypothesis that I got during the course completion was completely proved when I was watching the <a href="https://www.youtube.com/watch?v=D1W0kS40otM">Accelerating Your AI Career discussion by the DeepLearning.AI team</a>.</p><p>Apparently, Andrew Ng and the team have done everything possible to <strong>give anyone the opportunity to pass this specialization</strong> and understand what machine learning is. This can be helpful for:</p><ul><li>students who want to find ML-related jobs,</li><li>established professionals who want to change their field of activity,</li><li>or just people who are interested in what ML is and whether there is a real danger from Artificial Intelligence at least for the current moment.</li></ul><p>Andrew Ng mentioned that one of the goals of spreading knowledge about AI and ML is <strong>to make AI more accessible for people of non-technical specialties</strong> because it will still be very useful for them. AI-related products and goods are entering our lives more and more actively and by understanding the basics, you can greatly facilitate your work or see the opportunities to do so, no matter what profession you are working in. We are talking about <em>automation</em>, and if programming has made it possible to <em>automate routine actions</em>, then AI makes it possible to <em>automate routine actions, requiring some level of intelligence</em> right before our eyes.</p><p>This specialization is one of the steps to achieving this goal. It does not tell you at once about all approaches to training neural networks or all the pitfalls of the dimensionality reduction task. But <em>none of the specializations, courses, or books can</em>. Instead, it gives you <strong>the broadest possible understanding</strong> of machine learning, and it is <strong>deep enough to engage in it</strong>. The lack of math may annoy some enthusiasts, but this lowers the entry threshold so much that it has much more pros than cons.</p><p>If you:</p><ul><li>have never heard about machine learning,</li><li>are afraid that your knowledge of math is not enough, or</li><li>are not working in IT or in a technical occupation,</li></ul><p>this specialization is an <strong>excellent choice</strong>. It will reward your decision to explore new things without scaring you with complex terms and formulas. And when you finish it, you will be able to <strong>start implementing your own project</strong> or be not afraid to continue to get acquainted with AI word with the help of more advanced materials.</p><p>In the worst case, learning about AI will be interesting, and in the best one, it can change your life for the better.</p><h3>Reference</h3><p><a href="https://www.coursera.org/specializations/machine-learning-introduction">Machine Learning</a></p><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97118fa03297" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-you-need-to-know-about-updated-machine-learning-specialization-by-deeplearing-ai-97118fa03297">What you need to know about updated Machine Learning Specialization by DeepLearning.AI</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Does Your Favorite Movie Look Like?]]></title>
            <link>https://medium.com/data-science/what-does-your-favorite-movie-look-like-8c7b4a13ee94?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c7b4a13ee94</guid>
            <category><![CDATA[movies]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[gift-ideas]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 20:05:56 GMT</pubDate>
            <atom:updated>2024-02-18T19:55:10.800Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to convert any video into an image that reflects its color scheme</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*vygDcrYdjTb3K8w1Y7Ni6Q.jpeg" /><figcaption>What does your favorite movie look like? Image by Author</figcaption></figure><p>Have you ever wondered what your favorite movie looks like? Well, you definitely know what it looks like because you have most probably watched it more than once, but how does it look <em>in static </em>or how can it be visualized using a single image?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DK9inY-V-0BRAO-lHTqt3A.png" /><figcaption>The color scheme of the Shrek 2 movie. Image by Author</figcaption></figure><p>I present an approach to creating an image that reflects the color scheme of any video using machine learning algorithms. This is not only an interesting project, but also an <strong>endless source of gift ideas</strong> for your movie-loving friends and acquaintances: first, it’s pretty <em>personal and unique</em>, and second, it’s <em>highly customizable</em> since you can use this image as a print for anything you can order a print on: a cap, t-shirt, towel, canvas, etc., etc.</p><p><a href="https://github.com/Winston-503/movie_color_scheme">GitHub - Winston-503/movie_color_scheme</a></p><h3>How to read this article</h3><p>For your convenience, let me briefly describe all the main sections of this article so that you know where to start and can successfully navigate in the future:</p><ul><li>In the <strong>Problem Statement</strong> section, I will tell you what problem I am going to solve with this project;</li><li>In the <strong>Algorithm and Implementation Details</strong> section, I will tell you how I’ve implemented the project using Python, and its libraries: <a href="https://zulko.github.io/moviepy/">moviepy</a> and <a href="https://scikit-learn.org/stable/">scikit-learn</a>. Don&#39;t be afraid to skip this section <em>if you are not familiar with Python or programming in general</em>, since using the project code does not require any specific knowledge from you;</li><li>In the <strong>User’s Guide</strong> section, you will find a user’s guide for the final program and a link to the <a href="https://github.com/Winston-503/movie_color_scheme">repository with source code</a>;</li><li>In the <strong>Gallery </strong>section, you can see result images generated by the program based on different movies. <em>Take a look here at the beginning to see what the program is able to do;</em></li><li>In the <strong>Results and Conclusions</strong> section, I conclude the work done and share my thoughts about possible improvements.</li></ul><p>Now, when you know in which order to read this article, let’s go!</p><h3>Problem Statement</h3><p>I want to write a program that takes some video file as input and outputs an image, reflecting the color scheme of a given video. Some characteristics of the resulting image are also set by additional parameters.</p><p>To see example images that the program is able to generate, see the <strong>Gallery </strong>section.</p><h3>Algorithm and Implementation Details</h3><p>Let’s decompose the initial problem into sub-problems and review the algorithm step by step:</p><ol><li>First, we need to <strong>convert the proposed video to a list of images;</strong></li><li>For each image in the given list, we need to <strong>extract the most popular colors</strong> by analyzing the image;</li><li>Finally, having the list of colors we need to <strong>compose the resulting image.</strong></li></ol><p>Let’s discuss these steps in more detail and see the code to perform them. Please note that <strong>the code in gists should not be used directly</strong>, and it is here only to give you a general idea. I tried to keep it as simple as possible while the resulting code in the repository is in a way optimized and wrapped in the class.</p><h4>1. Convert the video to a list of images</h4><p>First, we need to convert the given video to an array of images for future analysis. It is very easy with the <a href="https://zulko.github.io/moviepy/">moviepy library</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a14bad0b0d05db030d9fe5938a6aa68/href">https://medium.com/media/7a14bad0b0d05db030d9fe5938a6aa68/href</a></iframe><p>First, we read the video in the moviepy object. Getting the video duration in seconds using duration property, and setting step variable that determines how often we want to extract a video frame, we use <em>for loop</em> to get the image in the current timestamp (using <a href="https://zulko.github.io/moviepy/ref/VideoClip/VideoClip.html#moviepy.video.VideoClip.VideoClip.get_frame"><em>get_frame </em>function</a>) and add it into the resulting list.</p><p>start variable is needed for a little offset since all videos start with a black screen at the zeroth second.</p><h4>2. Analyse image colors</h4><p>When we have a video “sliced” into an array of images, we need to analyze which colors are the most popular in them. Let me briefly tell you how we will do this.</p><p>General idea is to use a clustering algorithm on the image. Clustering is the task of grouping similar data points into groups (or clusters). In our case, data points are pixels of the image and features are three RGB color values.</p><p>After the clustering algorithm has calculated clusters for us (meaning that it analyzed all image pixels and create <em>top-k pixels groups</em> based on a color, where k is a number of clusters), we can use these cluster representatives to get the most popular colors. The easiest way to do this is to apply a clustering algorithm that is based on the <em>centroid</em> concept. A centroid in clustering is simply a geometric center of a cluster (that can be interpreted as the most common element for the given group). There are several centroid-based cluster algorithms; I have chosen <a href="https://scikit-learn.org/stable/modules/clustering.html#k-means"><em>K-Means</em></a> (can be also <a href="https://scikit-learn.org/stable/modules/clustering.html#mean-shift"><em>MeanShift</em></a>, <a href="https://scikit-learn.org/stable/modules/clustering.html#affinity-propagation"><em>Affinity Propagation</em></a>, etc.): it iteratively updates cluster centroids until convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*_HQTHY2_IO-PBTFYyEo1mw.gif" /><figcaption>Convergence of K-Means algorithm. <a href="https://en.wikipedia.org/wiki/K-means_clustering#/media/File:K-means_convergence.gif">Public domain</a></figcaption></figure><h4>Resources to Know More about Clustering</h4><p>If you want to know more detail about how clustering is used to extract colors from images you can check the following article:</p><p><a href="https://medium.com/analytics-vidhya/color-separation-in-an-image-using-kmeans-clustering-using-python-f994fa398454">Color Separation in an Image using KMeans Clustering using Python</a></p><p>If you want to know more about clustering algorithms in general, check my clustering cheat sheet article, which will give you a big picture about clustering algorithms zoo and clustering analysis in general:</p><p><a href="https://towardsdatascience.com/clustering-cheat-sheet-dcf72259abb6">Clustering cheat sheet</a></p><h4>Back to the practice</h4><p>But let’s get back to practice. Let’s do color analysis using the example of the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvjBsW2dFkxq2-OQKA04lA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lighttouchedphotography?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kevin Schmid</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Running this image through a clustering algorithm with different values of k, you will get the following outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPAqpRqSXU3kL57fSg_7wA.png" /><figcaption>3, 5, 10, and 20 most popular colors in the image above. Image by Author</figcaption></figure><p>As you can see, using too few colors does not reflect the real picture, and using too many colors makes the result noisy. In my experiments, I set a number of colors equals to 5.</p><p>Let’s see the code and discuss implementation details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa56ca2a2d4c95d11bda7bd3fbcc1777/href">https://medium.com/media/aa56ca2a2d4c95d11bda7bd3fbcc1777/href</a></iframe><p>We first preprocess a given image: resize it to a smaller size to allow the algorithm to run faster and reshape it into a 2D array as the scikit-learn object expects. Then we train a clustering algorithm, get coordinates of the cluster centroids, and sort the resulting colors by popularity, converting them from RGB to HEX for easier visualization.</p><p>In case you want to better understand the code and each variable type and shape, please take a look at <a href="https://github.com/Winston-503/movie_color_scheme/blob/main/video_color_scheme_demo.ipynb">this interactive Jupyter notebook</a> with demo code and more detailed comments.</p><h4>3. Compose the resulting image</h4><p>Now the matter remains small: having an array of colors, we only need to compose the final image.</p><p>To do this, we will need some simple coordinate calculations, which I have visualized below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKGESR3T2VGjNzxFkginrw.png" /><figcaption>Visualization of coordinates calculations. Image by Author</figcaption></figure><p>As we know, in matplotlib convention the lower left image corner point has coordinates <em>(0, 0)</em>, and the upper right point has coordinates <em>(w, h)</em> (if the width of the image equals <em>w</em> and height equals <em>h</em>).</p><p>We need to draw <em>n</em> rectangles sequentially, each time shifting slightly to the right. <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.Rectangle.html">Matplotlib Rectangle class</a> that I will use draws a rectangle using three parameters: coordinates of the lower left point, width, and height.</p><p>The width and height of each rectangle are the same: the height is equal to the height of the image, and the width is the width of the image divided by the number of rectangles. The coordinates of the lower left point are equal to the product of the index <em>i</em> by the width of the image divided by the number of rectangles. Make sure of this by substituting <em>i</em> = 0, 1, 2 into the formula above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f659bf556c8f90b1b99bfdfee40cd23f/href">https://medium.com/media/f659bf556c8f90b1b99bfdfee40cd23f/href</a></iframe><p>Note that image width and height are set in inches, not pixels. Please refer to the same Jupyter notebook with demo code for interactive visualization.</p><p>For simplicity, in the example above, I explicitly specify a list of colors. In fact, for each image, I save <em>all the top-k colors</em>. With this information, you can create different ways to choose a color based on the results of this analysis.</p><p>I have implemented two options that are selected by the mode parameter. If mode=&quot;popular&quot;, we just choose the most popular color. But if mode=&quot;sample&quot;, we sample a color according to a given distribution. Thus, even for the same video, you can get different results that make the images more diverse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZhJoUJ4fDCtHtbMzOn9Mw.png" /><figcaption>Explanation of the mode parameter using a frame from the <a href="https://www.youtube.com/watch?v=mqqft2x_Aa4">Batman trailer</a>. Image by Author</figcaption></figure><h3>User’s guide</h3><p>Let’s talk about how you can use this program.</p><p>After setting up the environment and installing the required libraries, you can use the program by setting parameters as we usually do in Python scripts: python main.py --parameter1 value --parameter2 value. Let’s review the program parameters.</p><h4>The list of program parameters</h4><p>Required parameters:</p><ul><li>video_path: Path to the video file to process;</li><li>result_path: Path to save the resulting image (including .png);</li><li>width: Width of the resulting image, inches. Default value: 25;</li><li>height: Height of the resulting image, inches. Default value: 5.</li></ul><p>Less important parameters (you can just use default values):</p><ul><li>mode: Mode to choose a color. If &#39;popular&#39; - return the most popular color, else sample a color according to distribution. Default value: &#39;sample&#39;;</li><li>start: Time to start video processing (seconds). Default value: 1;</li><li>step: Step in seconds. Default value: 1;</li><li>number_of_colors: Number of colors to extract from each image (number of clusters). Default value: 5;</li><li>compress_to: Number of pixels to resize the image during preprocessing. Default value: 200;</li><li>verbose: If True, show the resulting image. Default value: False;</li><li>delete_after: If True, delete temporary files after processing. Default value: False.</li></ul><h4>Saving intermediate results</h4><p>I also need to mention one more implementation detail that can save your time. Since the analysis stage takes a long time, refusing to save intermediate results will not be a good solution.</p><p>So, I save the <em>image array</em> and <em>colors array</em> so that you can reproduce experiments later. For example, if you set mode=&quot;sample&quot; but don’t find the resulting image very engaging, you can just run the last stage providing the path to the saved colors array file (commenting out the corresponding lines of code in <em>main.py</em>) <strong>without the need to run the whole analysis from scratch</strong>.</p><p>For <em>videoname.mp4</em> these files will be named <em>videoname_images.pkl</em> and <em>videoname_colors.pkl</em> and will be saved in tmp folder.</p><h3>Gallery</h3><p>In this section, you can find program outputs based on different movies. All the provided images in high resolution you can also find in the repo.</p><p>Let me first analyze the color scheme of Shrek 2 I showed you at the beginning of the article to basically prove that this approach works and can interest real movie lovers. Let’s zoom in and review the first 10 minutes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YWEfmYxJQTG_pi8EGiG4g.png" /><figcaption>Color analysis of the first 10 minutes of Shrek 2. Image by Author.</figcaption></figure><p>Here step parameter is equal to its default value of 1, so every tiny rectangle on the image above is one second in the video.</p><p>The cartoon starts with DreamWork&#39;s opening theme, where a child throws a fishing rod while sitting on the moon. This is happening in the <em>light-blue</em> <em>background</em>. A little white title on the <em>black background</em> with DreamWork’s presents… then follows.</p><p>This is followed by a short tale with a storybook and a moment where Prince Charming allegedly saves Fiona, after which there is a real screensaver of the movie with Fiona and Shrek, where by the way there are many references to various cultural works. After that, the narration actually begins in the swamp, in the appropriate color tones.</p><p>Let’s continue with <em>the Lord of the Rings</em>. The color scheme of the second film and the bright ending of the third catch my eye.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOLkWLSqmFveee1J-Gn-iw.png" /><figcaption>The Lord of the Rings — The Fellowship of the Ring. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8C2NTulxiTuV3YXN6DJHA.png" /><figcaption>The Lord of the Rings — The Two Towers. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hih4DSQZ7khaBU3tUWCl3g.png" /><figcaption>The Lord of the Rings — The Return of the King. Image by Author</figcaption></figure><p>I also analyzed all <em>Harry Potter</em> movies. The titles of the third film are most noticeable here — they are light (against the background of the Marauders’ Map). The bright moment of Harry’s conversation with Dumbledore in the last film also stands out vividly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-_uXUqFyR_u8B4wwSICeg.png" /><figcaption>Harry Potter and the Philosopher’s Stone. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1q4hQB-gwmYNIEkOKE2BjA.png" /><figcaption>Harry Potter and the Chamber of Secrets. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUkxhrsY6ajMehvxJiY-sg.png" /><figcaption>Harry Potter and the Prisoner of Azkaban. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqSCMZ7ToEYVt_1QDdYSyg.png" /><figcaption>Harry Potter and the Goblet of Fire. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZI9dSWNTM3Gw1M86BWi1g.png" /><figcaption>Harry Potter and the Order of the Phoenix. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYT03nVpsZ3mHWT2wDctBw.png" /><figcaption>Harry Potter and the Half-Blood Prince. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLk3n0J9EZBapyQ8aHt0yA.png" /><figcaption>Harry Potter and the Deathly Hallows — Part 1. Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBjYcxRwc_NlVvRbJUN9tw.png" /><figcaption>Harry Potter and the Deathly Hallows — Part 2. Image by Author</figcaption></figure><p>With a little imagination, you can create fascinating art based on these images. I’m not very good at that, but let me share with you a general idea.</p><p>From this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXaaGb4yqcbON5oZQHG6Ng.png" /><figcaption>Fight Club, 1999. Image by Author</figcaption></figure><p>To this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxqgKNlMfG-GaLV_JSLtew.jpeg" /><figcaption>Fight Club art. Images: <a href="https://commons.wikimedia.org/wiki/File:Fight_Club_logo1.png">public domain</a> and photo by <a href="https://www.pexels.com/photo/left-fist-635356/">NEOSiAM 2021</a></figcaption></figure><h3>Results and Conclusions</h3><p>In closing, let me discuss a little the work done.</p><h4>Supported Video Formats</h4><p>This program uses <a href="https://zulko.github.io/moviepy/"><em>moviepy </em>library</a> for video processing, so it supports various video formats supported by FFmpeg, like .mp4, .mpeg, .avi, .mov, .mkv, etc. See the full list <a href="https://en.wikipedia.org/wiki/FFmpeg#:~:text=of%20re%2Dencoding.-,Muxers,-%5Bedit%5D">here (in the Muxers section)</a>.</p><p>Sometimes I have encountered moviepy video reading errors, and converting a video file from one format to another usually helped. I used a free <a href="https://www.videolan.org/">VLC video player</a>.</p><h4>Execution Time</h4><p>As we discussed above, the program consists of three main stages — extracting images from the video, analyzing them, and compiling the final image.</p><p>The first and last stages are performed fairly quickly. The compilation of the image takes place <em>almost instantly</em>, while the conversion of video into images <em>usually does not take more than two minutes</em>.</p><p>But image analysis takes a lot of time, usually, it is <strong>about the same time as the duration of the video </strong>(for a 1-second step). To reduce this time, you can:</p><ul><li>Set step parameter to larger values (2 or 3 for example). This will allow you to get less accurate visualizations with fewer rectangles in the final image, but will significantly increase the execution speed.</li><li>Set number_of_colors or compress_to parameter to smaller values although it can produce poor results and is not recommended.</li></ul><p>Since this project is amateur and made just for the sake of interest and fun, it has a number of drawbacks and huge field for future work. For example, an optimized implementation of clustering algorithms and the use of GPU can greatly reduce the running time.</p><h4>Conclusion</h4><p>The idea for this project came to my mind a very long time ago. I didn’t find time to implement it for a long time, but then I started to write the code, encountering errors and unknowns. When the code was ready, I spent <em>over 20 hours</em> processing the popular movies you see above. Finally, I structured my thoughts for a while to transfer them to this article.</p><p>And although the implementation is not without drawbacks (it could work much faster, and I am not removing black bars, which can be a problem in dark movies), I am very pleased with the result. Setting goals, and facing setbacks, but finally achieving what you want is one of the best feelings a person can experience.</p><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c7b4a13ee94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-does-your-favorite-movie-look-like-8c7b4a13ee94">What Does Your Favorite Movie Look Like?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 7 Machine Learning resources I wish I knew earlier]]></title>
            <link>https://medium.com/data-science/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f4b8d3364c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[useful-websites]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Sat, 30 Apr 2022 20:19:28 GMT</pubDate>
            <atom:updated>2023-09-05T20:21:32.065Z</atom:updated>
            <content:encoded><![CDATA[<h4>Not teaching materials, just useful websites</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYfQvU9fEnHEnxFxZQo9Kg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’ve been learning Data Science and Machine Learning for a while, and during that time I passively collected a lot of useful resources. You know how it is actually happening — you are reading a book or watching a course and the author pays your attention (or just briefly mentions) something you didn’t hear about before. This can be everything: programming language, technology, dataset, task, metric, benchmark, visualization tool, really everything. You save it to figure out a bit later and you forget about it forever.</p><p>I tried not to forget, and explore these resources, and now I am presenting to you my top 7. They are split into categories depending on the usefulness, where the first is just funny things and the last is the most useful ones:</p><ul><li>Interestingness</li><li>Where to find models?</li><li>How to start reading research papers</li></ul><p>These are not learning recourses (e.g. books or courses). These are materials that can just make your life a bit easier or help you to look at the machine learning world from a slightly different perspective.</p><h3>Interestingness</h3><p>To begin with, let’s look at three resources that are suitable for people with <strong>any level of knowledge in data science and machine learning</strong>. These are just interesting stuff, familiarity with which might amuse you and at the same time bring some benefit for you.</p><h4>Spurious Correlations</h4><p>Do you still think that correlation means dependency? This site is the easiest way to dissuade you from this — and it needs to be done: statistics are not the last deal in DS and ML. It contains 15 cases with high correlation, which, however, just cannot cause each other.</p><p>The number of people who drowned by falling into a pool and the number of films Nicolas Cage appeared in? Well, the correlation is just 66%, looks like a coincidence. What about the divorce rate in Maine and the consumption of margarine? 99%? What the…</p><p><a href="https://www.tylervigen.com/spurious-correlations">Spurious Correlations</a></p><h4>Netron</h4><p>Netron is one of the simplest and most convenient ways to explore neural network architecture. I talked about it in <a href="https://towardsdatascience.com/predicting-the-number-of-dislikes-on-youtube-videos-part-2-model-aa981a69a8b2">one of my previous articles</a>. Without saying too much, it generates visualizations of the following type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*dtRzVj0XF9gnFb-MMBrrvA.png" /><figcaption>Neural network architecture. Visualization by <a href="https://netron.app/">Netron</a></figcaption></figure><p>The neural networks are getting bigger and bigger, and it’s getting harder and harder to visualize them. Nevertheless, at the beginning of your ML journey, it is interesting to look at the architecture <em>from the inside</em> or to understand how big ResNet152 really is. Netron gives you this opportunity.</p><p>These visualizations are pleasant and interactive — you can look into each structure in more detail, and even download the weights of the particular layer. Explore the example above <a href="https://netron.app/?url=https://raw.githubusercontent.com/Lausbert/Exermote/master/ExermoteInference/ExermoteCoreML/ExermoteCoreML/Model/Exermote.mlmodel">here</a>.</p><p>Netron supports TensorFlow and Keras and has experimental support for PyTorch. To know more visit the <a href="https://github.com/lutzroeder/netron">official GitHub repo</a>.</p><p><a href="https://netron.app/">Netron</a></p><h4><strong>Neural Network Playground by TensorFlow</strong></h4><p>And the last resource from this section again will not surprise people with experience in machine learning. However, for those who are just getting started discovering deep learning, this interactive playground will help to understand the functional principles of neural networks better.</p><p>Understand the limitations of a one-layer neural network (and how adding extra layers can beat those limitations), experiment with different learning rates, data shapes, and activation functions in order to get visual and intuitive ideas of what a neural network is and how it works.</p><p><a href="http://playground.tensorflow.org/">Tensorflow - Neural Network Playground</a></p><h3>Where to find models?</h3><p>You already realize what machine learning is, understand how neural networks or SVM are trained, and know how L1 regularization differs from L2 one.</p><p>The following step (one of the possible ones) is <strong>to see what the models are able to do</strong>, and what tasks they are solving right now. Of course, you are learning a lot from the news nowadays, but it is much more useful to see the architecture from the inside, run it with your own hands, and if the implementation is open source, get your hands dirty and see that it has <em>the same layers and parameters like all other models</em>.</p><p>The following three resources will help you with this.</p><h4>AI Hub</h4><p><a href="https://aihub.cloud.google.com/u/0/">AI Hub from Google</a> is the first place where you can start. Here you can find datasets, pretrained models, and much more. But perhaps the main advantage of this resource is a <strong>large number of Google Colab notebooks</strong> that demonstrate the functioning or training process of some models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_pKHzya03LZ2SgyeyrToQ.png" /><figcaption><em>Example of the random notebook from AI Hub. Screenshot of the </em><a href="https://aihub.cloud.google.com/p/products%2F3449d2b3-bc85-4519-9d2b-27a85cb7928a"><em>public web page</em></a></figcaption></figure><p>Because notebooks are interactive, simple, and often don’t contain a lot of code, this is a good way to start not being afraid of code written by another person.</p><p><a href="https://aihub.cloud.google.com/u/0/">AI Hub</a></p><h4><strong>TensorFlow Hub</strong></h4><p><a href="https://www.tensorflow.org/hub">TensorFlow Hub</a> is right for you if you are using TensorFlow (surprisingly). If you are using Keras, maybe this is a good chance to dive into neural networks, switch to TF and try implementing custom models or layers.</p><p>This site contains a <strong>large number of pre-trained models</strong> that are very easy to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOglkHQS9AGf9hetkjB6zA.png" /><figcaption><em>Running the pre-trained model using TensorFlow Hub. Screenshot of the </em><a href="https://tfhub.dev/tensorflow/faster_rcnn/inception_resnet_v2_640x640/1"><em>public web page</em></a></figcaption></figure><p>Only by fine-tuning these models, you will be able to get very good results on many tasks. Also pay attention to the <a href="https://www.tensorflow.org/hub/tutorials">Tutorials tab</a>, where a link to the model is often provided with more detailed descriptions and explanations.</p><p><a href="https://www.tensorflow.org/hub">TensorFlow Hub</a></p><h4>Hugging Face</h4><p>Finally, <a href="https://huggingface.co/">Hugging Face</a>. It is the most powerful resource, containing, I think, the largest number of models, and, at the same time, having the best tools to get familiar with these models.</p><p>Hugging Face is mainly a collection of Transformers or Transformer-like models, that are primarily designed for solving various NLP tasks. However, the site provides models and datasets for other tasks in various fields — from Computer Vision to Reinforcement Learning. But as we know, the main success of Transformers has been achieved in NLP, and often right here you can find a <strong>state-of-the-art </strong>(SOTA) model that solves a specific task with the highest quality.</p><p>But what makes this site especially valuable is the community and the ability to publish <strong>demos of our models directly in the browser</strong>. And modern neural networks can do a lot, if not everything. Do you want to <a href="https://huggingface.co/spaces/akhaliq/demucs">separate different musical parties from each other</a>? You are welcome. <a href="https://huggingface.co/spaces/eugenesiow/remove-bg">Remove the background from the image</a>? You are welcome. <a href="https://huggingface.co/spaces/hysts/DualStyleGAN">Turn your photo into a hero of your favorite anime or cartoon using GAN</a>? You are welcome. Nothing needs to be downloaded and everything is absolutely free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxbAsth4mQFMbCga8bjCuw.png" /><figcaption>Results of the <em>portrait style transfer with Barack Obama and Hiccup Horrendous Haddock III. </em>Photo by <a href="https://unsplash.com/@libraryofcongress?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Library of Congress</a> on <a href="https://unsplash.com/s/photos/president?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>, processed using <a href="https://github.com/williamyang1991/DualStyleGAN">DualStyleGAN</a></figcaption></figure><p>This is truly one of the best resources for anyone, even a non-machine learning person, and I am very happy to share it with you.</p><p><a href="https://huggingface.co/">Hugging Face - The AI community building the future.</a></p><h3>How to start reading research papers</h3><p>And the last section in this article is the most important. This is the answer to the question “how to start reading ML research articles?”. And if I had something to say, I would definitely write a separate article about it. But</p><blockquote>The best way to start reading research papers is to start reading research papers.</blockquote><p>It sounds silly, but reread this phrase a couple of times, and everything will fall into place. In fact, many questions can be answered in this way. The best way to learn to program is to program, the best way to learn to ride a bike is to ride a bike, and the best way to read research papers is to read research papers.</p><p>Of course, I won’t leave you only with this stupid advice. The website that will help you with this is called <a href="https://paperswithcode.com/">papers with code</a>. For some reason, I found out about it very late, as if everyone was hiding it from me, and that’s why I’m sharing it with you.</p><p><a href="https://paperswithcode.com/">Trending Papers - Hugging Face</a></p><p>Intuitive interface, extensive search capabilities for datasets and tasks, and the opportunity to see the best models — this site is a real find for any ML person.</p><p>And that’s it. But wait. I’m showing you six resources in two categories, but when it comes to the most important, I have only one? Yes, that’s right. That’s because <strong>it’s enough</strong> (you probably know about <a href="https://arxiv.org/">arXiv</a> without me). The rest is up to you. There is a lot to tell about this site, but it is better that you find out it yourself.</p><p>If you think that research papers are only for the elite, then this is not true. If you don’t understand something for the first time, get confused or you’re just bored — that’s fine, no one gets it initially. If you have never read these articles before, pay attention to this awesome NVIDIA blog article, it can help you a lot:</p><p><a href="https://developer.nvidia.com/blog/how-to-read-research-papers-a-pragmatic-approach-for-ml-practitioners/">How to Read Research Papers: A Pragmatic Approach for ML Practitioners | NVIDIA Technical Blog</a></p><h3>Summary</h3><p>That’s it! Good luck in exploring these resources, and if you know any more, please share them in the comments. At the very end, let me enumerate everything again in a more compact way:</p><ol><li>Interestingness</li></ol><ul><li><a href="https://www.tylervigen.com/spurious-correlations">Spurious Correlations</a>: to get an intuitive explanation of why correlation is not a dependency;</li><li><a href="https://netron.app/">Netron</a>: to visualize neural networks architectures;</li><li><a href="http://playground.tensorflow.org/">Neural Network Playground</a>: to play with dense neural networks directly in your browser.</li></ul><p>2. Where to find models?</p><ul><li>At <a href="https://aihub.cloud.google.com/u/0/">AI Hub</a>, <a href="https://www.tensorflow.org/hub">TensorFlow Hub</a>, and <a href="https://huggingface.co/">Hugging Face</a>.</li></ul><p>3. How to start reading research papers</p><ul><li>Start with the <a href="https://developer.nvidia.com/blog/how-to-read-research-papers-a-pragmatic-approach-for-ml-practitioners/">NVIDIA blog post</a></li><li>Read papers with <a href="https://arxiv.org/">arXiv</a> and <a href="https://paperswithcode.com/">papers with code</a>.</li></ul><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f4b8d3364c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c">Top 7 Machine Learning resources I wish I knew earlier</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Resume with which I Got My First ML Internship in Canada]]></title>
            <link>https://medium.com/data-science/the-resume-with-which-i-got-my-first-ml-internship-in-canada-d1cd833cc452?source=rss-97b5279dad26------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1cd833cc452</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[first-job-resume]]></category>
            <dc:creator><![CDATA[Dmytro Nikolaiev (Dimid)]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 21:53:24 GMT</pubDate>
            <atom:updated>2024-02-18T19:48:31.443Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to get a job in machine learning? My personal story</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpRHCq3H_OXvCsrkaHkQmA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@officestock?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sebastian Herrmann</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>You’ve probably seen a lot of articles with this title. Each person’s experience is special, and you can get a grain of useful (and at the same time unique) information from each personal history.</p><p>Nevertheless, most of the articles on this topic that I came across sounded a little strange to me: one of the resumes in such an article consisted of two pages and the second page was literally a list of scientific publications and patents (wow, impressive!).</p><blockquote>2023 update.</blockquote><blockquote>A year later, some things have certainly changed here. Most of things in this article are still true, but I should also have said about the importance of a good questions, cover letter and of course referral if it’s possible, but this is a separate (and big) topic. I also think it’s better <strong>not to use the tabular resume format</strong> that I use here because apparently (but not certainly), it is worse recognized by the Application Tracking Systems and other software.</blockquote><blockquote>Remember that it is more a personal story than professional advice since I don’t have professional experience in the job hunting field. When writing your resume, review information from many sources, and it is best to ask for advice from experienced people from the industry. With this in mind hope you will enjoy the story and good luck in your job search!</blockquote><h3>TL; DR</h3><p>How is my story different from all the previous ones? Well, if I don’t have the worst resume, then probably one of the worst, at least in two main fields:</p><ul><li>Education — I’m a Bachelor of Computer Science from a city you never knew about;</li><li>Experience — I have almost no relevant work experience.</li></ul><p>However, I was able to find a machine learning related job in Canada, although it was difficult and <strong>took a whole year</strong>.</p><h3>Education</h3><p>As I already said — I’m a Bachelor of Computer Science from an unknown university. Of course, by having a good education, you have a better chance of getting a job, at least because of the connections and networking you have access to. But if you were not lucky enough to study at a top university — prove that you deserve a job by other means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImKEFnHmTuPrSxHG_rVW1w.jpeg" /><figcaption>Education section in the resume. Image by Author</figcaption></figure><h3>Experience</h3><p>I guess this is the most important point in your resume — where you worked before and how you can present the results of your work greatly affects your chances of getting a position. Nevertheless, everyone needs to start somewhere. This is the famous <em>Permission Paradox </em>or <em>Experience Paradox: </em><strong>if all employers require employees with work experience, how to get this work experience?</strong></p><p>I’m not really an expert in this matter, but that is what I’ve heard from many others: <strong>you can’t leave this field empty</strong>. It might be appropriate to list the university practice here and mention elaborate coursework or a corresponding degree project. But you can’t leave it empty. If things are really bad, you can look for an <em>open-source project</em> to contribute to or gain some <em>volunteer </em>experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQRZOsOWZLIVQmV7Rcv2sQ.jpeg" /><figcaption>Experience section in the resume. Image by Author</figcaption></figure><h3>Yes, Personal Projects (again)</h3><p>Since my work experience is completely unimpressive, the data science/machine learning projects section is the most valuable and powerful part of my resume. And if you have a similar situation with work experience, you should have a similar situation with projects as well.</p><p>That particular section can let you get a job. It can tell a potential employer: <em>“Hey, I don’t have any work experience, but I’m trying, and I’m trying hard!”.</em></p><p>You’ve probably heard this more than once, but <strong>if you don’t have any work experience, personal projects are vital to you</strong>. Make them <em>as interesting</em> and <em>complex</em> as possible, use <em>modern technologies</em>, try implementing something <em>from scratch</em> to get a deeper understanding of how a particular algorithm works, etc.</p><p><strong>All this shows that you are interested</strong>, that you are <strong>ready to learn new things</strong>, <strong>ready to face difficulties and overcome them</strong>. <br>Are you really like that? Prove it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-seBXTtqRP8jyD26ehT-zA.jpeg" /><figcaption>Projects section in the resume. Image by Author</figcaption></figure><p>Here are links to my projects. I don’t know how much it helped that I wrote blogs on Towards Data Science, but it helped <em>me </em>first of all. <em>Only by explaining something to another person, you can fully understand it. </em>So writing tutorials or a personal professional <strong>blog </strong>is <strong>a very good way to start</strong> a data science career.</p><ul><li>Predicting the number of dislikes on YouTube videos: <a href="https://towardsdatascience.com/predicting-the-number-of-dislikes-on-youtube-videos-part-1-dataset-9ec431585dc3">part 1</a> and <a href="https://towardsdatascience.com/predicting-the-number-of-dislikes-on-youtube-videos-part-2-model-aa981a69a8b2">part 2</a>;</li><li><a href="https://towardsdatascience.com/automatic-video-editing-using-python-324e5efd7eba">Automatic Video Editing</a>;</li><li><a href="https://towardsdatascience.com/how-to-create-real-time-face-detector-ff0e1f81925f">Real-time “me-not_me” Face Detector</a>.</li></ul><p>Your level or interests may differ significantly, but you need to find something that will <em>inspire you</em>.</p><p>If you don’t have any ideas for projects, you may not be ready to implement them yet. To think and see the world in machine learning terminology <em>you need a pretty serious knowledge base</em>. Try to read another book or take another course to digest this knowledge and reproduce your own idea.</p><p>If you think that you are ready, but there are still no ideas, look for them on the Internet. Often the quality of such articles leaves much to be desired (you are advised to classify the <a href="https://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html">iris dataset</a> OR to solve some computer vision problem, although these tasks are of completely different levels), but this may lead you to your own thoughts.</p><h3>Other Sections</h3><h4>Skills</h4><p>Honestly, I filled in this section in such a way to list as many keywords as possible so as not to be filtered out at the very beginning. As far as I know, <em>keywords search programs</em> are used when selecting resumes, especially for beginner-level positions (e.g. intern or junior), because HR specialists can’t process them manually.</p><p>Also, it is important to remember that specifying skills that you don’t actually have is a <strong>bad idea</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOQcLUA28n9jznjERmFIEw.jpeg" /><figcaption>Skills section in the resume. Image by Author</figcaption></figure><h4>Certifications</h4><p>Here I have listed the courses from which I got the main knowledge about data science and machine learning.</p><p>I also think it <strong>doesn’t make much sense</strong> to enumerate:</p><ul><li><em>individual courses</em> because the list will be too long and detailed; instead, you should list your programs/certifications;</li><li><em>entry-level courses</em> (like <a href="https://www.coursera.org/learn/machine-learning">Machine Learning by Stanford</a>) because your potential employer might think that your knowledge/qualification is insufficient.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYLgFP-Ash4fUb5E3q2X3Q.jpeg" /><figcaption>Certifications section in the resume. Image by Author</figcaption></figure><h3>Full Resume</h3><p>Putting all the parts together, I got the resume that brought me my first job in machine learning, my first job in Canada, and my first good job in general. Thank you, resume!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PUDvts4wrKePEVZbzZpfg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtToZopPoGpx0hF0OnCf5Q.jpeg" /><figcaption>The resume that brought me my first ML internship. Image by Author</figcaption></figure><h3>Conclusions and Final Thoughts</h3><p>Finding a job wasn’t easy. It took me <strong>a whole year to get one interview</strong> <strong>invitation</strong>. To be honest, I do not know whether I was unlucky all this year, or, on the contrary, I got lucky once.</p><p>While I was looking for a job, I often changed my resume, adding and removing some parts, changing formulations, or reorganizing the order of the sections. I don’t know which of these transformations were really successful, but here’s what I can say for sure:</p><ul><li><strong>Don’t complicate your resume</strong>. <br>Don’t list all the projects in your life or all the courses you’ve taken. I think three is quite enough for an entry-level employee.</li><li><strong>Do not strive to make a one-page resume.<br></strong>This is my personal view and a piece of advice from several people I’ve talked to. All online services say that a beginner’s resume must be one-page, but you should not strive for it too much.</li><li><strong>Don’t be afraid to ask for advice</strong>.<br>Do not hesitate to ask for advice — everyone started somewhere, and many (if not all) faced problems, so people usually treat this with understanding. Perhaps some friend or professor at your university can push you on a successful path. If you can’t ask for advice in person, use the Internet and the relevant sites/forums. Sometimes it’s just important to talk to someone when you feel stuck.</li></ul><p>And finally: <strong>never give up</strong>. I sent more than a hundred job applications (and this is far from the limit) before I received a response. <strong>It’s hard to find a first job</strong>, extremely hard sometimes, especially for immigrants or people changing career paths. But the second job will be easier to find, and the third one will find you by itself.</p><p>So good luck. Perhaps you will receive the desired offer today! So make an effort to do it.</p><h3>Thank you for reading!</h3><ul><li>I hope these materials were useful to you. <a href="https://medium.com/@andimid">Follow me on Medium</a> to get more articles like this.</li><li>If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via <a href="https://www.linkedin.com/in/andimid/">LinkedIn</a> or <a href="https://twitter.com/dimid_ml">Twitter</a>.</li><li>To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using <a href="https://medium.com/@andimid/membership">my referral link</a> (no extra charge for you).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1cd833cc452" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-resume-with-which-i-got-my-first-ml-internship-in-canada-d1cd833cc452">The Resume with which I Got My First ML Internship in Canada</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>