Wednesday 19 July 2017

Data Science & Machine Learning - 3.3 NumPy & Random Arrays

Hi friends,

In the previous post under Data Science & Machine Learning, we discussed various ways to create NumPy Arrays using the NumPy library in Python. In this post, we'll see several ways to create NumPy arrays of random numbers. So, let's see some of the NumPy methods to generate random values.

Note: All the commands discussed below are run in the Jupyter Notebook environment. See this post on Jupyter Notebook to know about it in detail.

Also, do remember to import the NumPy library before executing the commands.

NumPy & Random Arrays

  1. Using NumPy's rand() function: It generates a list of random numbers following the uniform distribution over 0 to 1. So, if we want a NumPy array of ten uniformly distributed random variables between 0 to 1, we do the following:


  2. We can also generate a 2-D vector by passing two integers to the rand() function as shown below:



  3. Using NumPy's randn() function: To generate the list of random variables following the standard normal distribution, use the NumPy's randn() method:


  4. The above result represents five random numbers following standard normal distribution centered around zero. Passing the two parameters similar to above will generate a 2-D vector of required dimensions. 

  5. Using NumPy's randint() function: The randint() method generates an NumPy Array of random integers within the given range. It takes three integers as input, namely, the start point, the end point and the number of random integers to be generated. Here is a usage of the same:


  6. The above method generates five random integers in the range 1 to 20, with 1 being inclusive and 20 exclusive. Further, without the third parameter, it generates only a single integer in the given range.


These are the standard ways to generate random numbers using the NumPy library. However, there are many more ways to generate random arrays which you can check out by pressing the Tab key after typing np.random.r.


With this, we also end this post here on generating NumPy Arrays with random numbers. In the next post, we will learn various ways to index NumPy arrays
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive