<?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 Mfundo Monchwe on Medium]]></title>
        <description><![CDATA[Stories by Mfundo Monchwe on Medium]]></description>
        <link>https://medium.com/@diditmfundo?source=rss-75bd903fd715------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fr6wBI-czpXjGe9IviGQtg.jpeg</url>
            <title>Stories by Mfundo Monchwe on Medium</title>
            <link>https://medium.com/@diditmfundo?source=rss-75bd903fd715------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:29:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diditmfundo/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[Vectorization over Loops? Python]]></title>
            <link>https://medium.com/@diditmfundo/vectorization-over-loops-python-cd1f445287f?source=rss-75bd903fd715------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd1f445287f</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[vectorization]]></category>
            <category><![CDATA[loops-in-python]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mfundo Monchwe]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 10:57:19 GMT</pubDate>
            <atom:updated>2023-04-09T11:29:21.426Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction: Loops vs Vectorization in Python ( A Comparison)</strong></p><p>Are you a beginner, intermediate, or expert? Surely you have worked with data in Python, you’re likely familiar with the concept of loops. Loops are used to iterate over a collection of data and perform some operation on each element of the collection. While loops can be useful for simple tasks and small datasets, they can become slow and inefficient for larger data sets or more complex operations.</p><p>Vectorization, on the other hand, is a technique used to perform computations on entire arrays or matrices at once, rather than iterating over them element by element (i.e. loops). This approach can be much faster and more efficient than loops, making it a popular choice for data analysis and scientific computing in Python.</p><p>In this article, we’ll take a closer look at loops and vectorization in Python, including their advantages and disadvantages, and provide some examples of when each approach might be best suited for a given task. If you’re new to Python or a seasoned pro, read on to learn more about these two powerful tools for data processing and analysis :).</p><p><strong>A. Explanation of for and while loops in Python</strong></p><p>Python has two types of loops: for and while . for loops are used to iterate over a sequence (such as a list or string), while while loops are used to repeat a block of code as long as a certain condition is met.</p><p>Below is an example of using a for loop to iterate over a list of numbers and print each number:</p><pre>numbers = [1,2,3,4,5]<br>for number in numbers:<br>    print(number)</pre><p>In this example, we define a list of numbers and use a for loop to iterate over each number in the list and print it to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*QXb7UwQzgcZX7whQ0A3lrg.png" /><figcaption>The output of the above example</figcaption></figure><p>Example of using a while loop to repeat a block of code until a certain condition is met:</p><pre>count = 0<br>while count &lt; 5:<br>    print(count)<br>    count += 1</pre><p>In this example, we define a variable count and use a while loop to print the value of count to the console until it reaches a value of 5. Note that we increment the value of count within the loop using the += operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*UGAA-L4UPzVgUZQa5s3Faw.png" /><figcaption>Example 2-while loop</figcaption></figure><p>Loops are the fundamental concept in programming and very essential for performing operations on the collection of data. However, they become slow and inefficient for larger data sets or more complex operations. That’s where vectorization comes in- we’ll explore this technique in the next section.</p><p><strong>B. Explanation of vectorization in Python</strong></p><p>Vectorization is a technique used to perform computation on entire arrays or matrices at once, rather than iterating over them element by element. This approach can be much faster and more efficient than loops, making it a popular choice for data analysis and scientific computing in Python.</p><p>Vectorization is supported by many popular libraries in Python, including NumPy, SciPy, and Pandas. These libraries provide powerful tools for working with large data sets and performing complex computations with minimal code.</p><p>Below is an example of using NumPy to perform vectorized arithmetic operations on arrays:</p><figure><img alt="Output of the below code" src="https://cdn-images-1.medium.com/max/430/1*pCHM-4njN4ysKecKI0KZFg.png" /></figure><pre>import numpy as np<br><br># Create two arrays of random integers<br>array1 = np.random.randint(0, 10, size=(3, 3))<br>array2 = np.random.randint(0, 10, size=(3, 3))<br><br># Perform vectorized arithmetic operations<br>sum_array = array1 + array2 #alternative np.add(array1,array2)<br>diff_array = array1 - array2 #alternative np.subtract(array1,array2)<br>prod_array = array1 * array2 #alternative np.multiply(array1,array2)<br>div_array = array1 / array2 #alternative np.divide(array1,array2)<br><br># Print the results<br>print(&quot;Sum array:\n&quot;, sum_array)<br>print(&quot;Difference array:\n&quot;, diff_array)<br>print(&quot;Product array:\n&quot;, prod_array)<br>print(&quot;Division array:\n&quot;, div_array)</pre><p>In the above example, utilized Numpy to create two arrays of random integers and performed vectorized arithmetic operations on them. Note how we perform the operations using the usual arithmetic operators, but apply them to the entire array rather than individual elements.</p><p>Vectorization can be a powerful tool for data processing and analysis in Python. However, it may not always be the best approach for every task.</p><p><strong>C. Optimizing Vectorized Code in Python</strong></p><p>While vectorization can provide significant performance gains, there are still some factors that can affect the speed and efficiency of vectorized code. Here are some tips on how to optimize vectorized code for performance:</p><ol><li>Avoid unnecessary operations: Vectorized operations can be faster than loops, but they still require computational resources. To improve performance, try to avoid unnecessary operations and focus only on the necessary calculations.</li><li>Use built-in functions: Python provides a wide range of built-in functions and libraries for vectorized operations. Using these functions can be more efficient than writing your own code from scratch.</li><li>Choose the right data types: Choosing the right data types for your variables can also affect the performance of vectorized code. For example, using integer types instead of floating-point types can be faster for certain operations.</li><li>Avoid memory allocation: Allocating memory can be a time-consuming process, especially for large datasets. To optimize performance, try to avoid unnecessary memory allocation and reuse existing memory wherever possible.</li><li>Parallelization: Some vectorized operations can be parallelized to take advantage of multiple cores or processors. Using parallelization techniques such as multithreading or multiprocessing can further improve the performance of vectorized code.</li></ol><p><strong>The example below demonstrates optimization by avoiding unnecessary operations:</strong></p><pre>import numpy as np<br><br># Generate some random data<br>array1 = np.random.rand(10000)<br>array2 = np.random.rand(10000)<br><br># Compute the dot product using NumPy<br>dot_product = np.dot(array1, array2)<br><br># Optimize by using a more efficient data type<br>array1 = array1.astype(np.float32)<br>array2 = array2.astype(np.float32)<br>dot_product = np.dot(array1, array2)<br><br># Optimize by avoiding unnecessary operations<br>sum_array1 = np.sum(array1)<br>sum_array2 = np.sum(array2)<br>dot_product = np.dot(sum_array1, sum_array2)<br><br># Optimize by parallelizing the operation<br>import multiprocessing as mp<br><br>def dot_product_worker(array1, array2, start, end, result_queue):<br>    result = np.dot(array1[start:end], array2[start:end])<br>    result_queue.put(result)<br><br>array_size = len(array1)<br>num_workers = mp.cpu_count()<br>chunk_size = array_size // num_workers<br>result_queue = mp.Queue()<br><br>workers = [mp.Process(target=dot_product_worker, args=(array1, array2, i*chunk_size, (i+1)*chunk_size, result_queue)) for i in range(num_workers)]<br>for worker in workers:<br>    worker.start()<br><br>dot_product_parts = [result_queue.get() for i in range(num_workers)]<br>dot_product = sum(dot_product_parts)</pre><p>In this example, we first generate two arrays of 10000 random numbers using NumPy’s rand() function. We then compute the dot product using NumPy&#39;s dot() function.</p><p>To optimize the code, we first change the data type of the arrays to np.float32, which is a more efficient data type for certain operations. We then optimize further by avoiding unnecessary operations, such as computing the sum of each array separately and then taking the dot product of the sums instead of the arrays themselves.</p><p>Finally, we parallelize the dot product operation using the multiprocessing library, which allows us to take advantage of multiple cores or processors to further improve performance. We split the arrays into chunks and compute the dot product of each chunk in parallel, then combine the results to get the final dot product.</p><p><strong>Visualization of time used between loops and vectorization</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*j_MnLvJbAG4VDJQ5OcclvQ.png" /><figcaption>Comparison of Vectorized vs Loop-based Function.</figcaption></figure><p>The above plot indicates how each function takes to output, and given the plot, it is clear that vectorized function takes less compared to loop-based. This proves if given large data loops will take much longer compared to vectorized functions.</p><p><strong>Memory display between vectorized and loop-based</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*5LS1hQ6jgl96A6arxHylpg.png" /><figcaption>Memory Usage(MiB) used Vectorized and Loop-based</figcaption></figure><p>The plot above is evident enough and still proofs the theory of this article, as to why vectorization is more efficient than loop-based for large-scale data and scientific programming in Python.</p><p>Conclusion</p><p>In this article, we explored both loops and vectorization differences in Python and discussed the factors to consider when selecting between the two. Loops offer flexibility and ease of implementation but may be slower and less efficient for large datasets or complex computations. On the other hand, vectorization provides significant performance gains for large-scale operations and enables the use of optimized libraries, but may require more advanced knowledge and may not always be applicable to all use cases.</p><p>Ultimately, I believe the choice between loops and vectorization depends on the specific needs of the project and the trade-offs between performance, readability, and maintainability. By Understanding the strengths and limitations of each approach, programmers can make informed decisions and optimize their code for the best results.</p><p>I hope that this article has provided a useful introduction to the topic of loops and vectorization in Python, and believe that it encourages readers to explore further and experiment with their own code. Best of luck, and never stop reading and practicing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd1f445287f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Linear Regression and Bayesian linear regression]]></title>
            <link>https://medium.com/@diditmfundo/a-comprehensive-guide-to-linear-regression-and-bayesian-linear-regression-9a98fafae55a?source=rss-75bd903fd715------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a98fafae55a</guid>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Mfundo Monchwe]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 10:00:21 GMT</pubDate>
            <atom:updated>2023-04-08T10:09:30.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*UHKdDjZV_p-RbZyI4sPaiw.png" /><figcaption>Linear Regression vs Bayesian linear regression</figcaption></figure><p>Linear regression is a powerful statistical method that helps in finding the relationship between one or more independent variables and a dependent variable. It is one of the simplest and most widely used methods in statistics and data analysis. On the other hand, Bayesian linear regression is a variation of linear regression that incorporates prior knowledge about the parameters in the model to provide a more accurate and robust estimate of the relationship between the variables.</p><p><strong>Linear Regression</strong></p><p>Advantages of Linear Regression:</p><ol><li><strong><em>Simple and easy to understand: </em></strong>Linear regression is a straightforward method that is easy to grasp and apply. It provides a clear relationship between independent and dependent variables, making it a popular choice among researchers and practitioners.</li><li><strong><em>Versatile:</em></strong> Linear regression can be used for both continuous and categorical data, making it a versatile tool in data analysis. It can also handle large datasets with ease, which is useful in real-world applications.</li></ol><p>Disadvantages of Linear regression:</p><ol><li><strong><em>Assumption of linear relationship:</em></strong> One of the main drawbacks of linear regression is that it assumes a linear relationship between the variables. However, this may not always hold true, especially when dealing with complex or nonlinear data.</li><li><strong><em>Sensitivity to outliers:</em></strong> Linear regression is sensitive to outliers, which can skew the results and lead to inaccurate conclusions.</li><li><strong><em>Handling of missing data:</em></strong> Linear regression cannot handle missing data well, and this can affect the accuracy of the model.</li><li><strong><em>Non-normal distribution: </em></strong>Linear regression is not suitable for non-normal distributions, and this can lead to inaccurate results.</li></ol><p><strong>Bayesian Linear regression</strong></p><p>Advantages of Bayesian linear regression:</p><ol><li><strong><em>Incorporation of prior knowledge:</em></strong> Bayesian linear regression incorporates prior knowledge about the parameters in the model, which can improve the accuracy of the results. This makes it a powerful tool in data analysis, especially when dealing with complex or uncertain data.</li><li><strong><em>Posterior distribution:</em></strong> Bayesian linear regression provides a posterior distribution of the parameters, which can help with uncertainty quantification. This makes it easier to interpret and draw conclusions from the results.</li><li><strong><em>Handling of missing data</em></strong>: Bayesian linear regression can handle missing data well, which is a significant advantage over other methods.</li><li><strong><em>Non-normal distribution: </em></strong>Bayesian linear regression can handle non-normal distributions well, which makes it more suitable for real-world applications.</li></ol><p>Disadvantages of Bayesian linear regression:</p><ol><li><strong><em>Computational intensity: </em></strong>Bayesian linear regression can be computationally intensive, especially for large datasets. This can make it challenging to apply in some cases.</li><li><strong><em>Subjectivity in specifying prior distributions:</em></strong> Bayesian linear regression requires specifying prior distributions, which can be subjective and influence the results. This makes it crucial to choose appropriate priors and be aware of their potential impact on the final results.</li><li><strong><em>Expertise required</em></strong><em>:</em> Bayesian linear regression requires more expertise to set up and interpret the model compared to linear regression. This means that beginners may need to invest more time and effort to become proficient in this method.</li></ol><p><strong>Conclusion</strong></p><p>In conclusion, linear regression and Bayesian linear regression are powerful statistical methods that can help in finding the relationship between variables. While both methods have their advantages and disadvantages, they are essential tools in data analysis and can provide valuable insights into complex real-world problems. As a beginner, it is essential to understand the strengths and weaknesses of both methods to choose the appropriate method for your data analysis needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a98fafae55a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install PyMC3]]></title>
            <link>https://medium.com/@diditmfundo/how-to-install-pymc3-3-11-4-c4b86266153d?source=rss-75bd903fd715------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4b86266153d</guid>
            <category><![CDATA[installation]]></category>
            <category><![CDATA[pymc3]]></category>
            <dc:creator><![CDATA[Mfundo Monchwe]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 16:21:59 GMT</pubDate>
            <atom:updated>2023-03-30T03:38:01.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*zqGVY98PlHGmOuBGrnSqRQ.png" /></figure><p>Ever had issues like compilation error code or theano-pymc is broken ?</p><p>Well, I have good news for you, I might have the solution that you really need, to work on your pc.</p><p>This tutorial assumes, you already downloaded jupyter notebook or jupyterlab installed.</p><p><strong>Brief Background about PyMC3</strong></p><p>PyMC3 is a Python package for Bayesian statistical modeling and probabilistic machine learning. It provides a powerful and flexible framework for building complex statistical models that use Monte chain Monte Carlo (MCMC) and Variational Inferences (VI) algorithms and are widely used in fields such as computer science, engineering, finance, and others. For more about this package click the link below:</p><p><a href="https://www.pymc.io/projects/docs/en/latest/learn/core_notebooks/pymc_overview.html">https://www.pymc.io/projects/docs/en/latest/learn/core_notebooks/pymc_overview.html</a></p><p>Without wasting any time let’s get started 😇</p><p><strong>Step 1. Create new environment</strong></p><p>To avoid conflict dependencies, open Anaconda or a terminal prompt and create a new environment by running the following command:</p><pre>conda create --name pymc3_env</pre><p>Please note pymc3_env is a name of the environment, you are allowed to suggest your own name.</p><p><strong>Step 2: Activate the Environment</strong></p><pre>conda activate pymc3_env</pre><p>It is important that you run the following commands in the specified environment.</p><p><strong>Step 3: Install PyMC3</strong></p><pre>conda install pymc3</pre><p>Please note that this step is crucial. Making a mistake here could compromise the environment. I highly suggest that you use conda instead of pipfor the purpose of this tutorial. This should install the latest version in the pymc3 version</p><p><strong>Step 4: Install the Jupyter Kernel</strong></p><p>If you are using jupyter Lab, you need to install the kernel by entering the following command:</p><pre>conda install ipykernel</pre><p><strong>Step 5: Activate the Kernel</strong></p><pre>python -m install --user --name=pymc3_env</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*nlwF6-anCdrV-dCAj5rNaA.png" /><figcaption>PyMC3 Environment Successfully installed.</figcaption></figure><p><strong>Conclusion</strong></p><p>Congratulations! You have successfully installed PyMc3–3.11.4 and are now ready to work on it! A humble thanks to the <a href="https://medium.com/u/7c6b7b6803cd">PyMC Developers</a> for developing this library. Please feel free to connect with me on LinkedIn</p><p><a href="https://www.linkedin.com/in/mfundo-monchwe-48883314a/">https://www.linkedin.com/in/mfundo-monchwe-48883314a/</a></p><p>For the next content, we will be using Pymc3 in our code stay tuned for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4b86266153d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>