This article was written by Vasudev.
Lets get started quickly. Numpy is a math library for python. It enables us to do computation efficiently and effectively. It is better than regular python because of it’s amazing capabilities.
In this article I’m just going to introduce you to the basics of what is mostly required for machine learning and datascience. I’m not going to cover everything that’s possible with numpy library. This is the part one of numpy tutorial series.
A small illustrated summary of NumPy indexing and slicing (see here for details)
The first thing I want to introduce you to is the way you import it.
Okay, now we’re telling python that “np” is the official reference to numpy from further on.
Let’s create python array and np array.
If I were to print them, I wouldn’t see much difference.
Okay, but why do I have to use an np array instead of a regular array?
The answer is that np arrays are better interms of faster computation and ease of manipulation.
Let’s proceed further with more cool stuff. Wait, there was nothing cool we saw yet! Okay, here’s something:
What arange([start],stop,[step]) does is that it arranges numbers from starting to stop, in steps of step. Here is what it means for np.arange(0,10,2):
return an np list starting from 0 all the way upto 10 but don’t include 10 and increment numbers by 2 each time.
So, that’s how we get :
important thing remember here is that the stopping number is not going to be included in the list.
Before I proceed further, I’ll have to warn you that this “array” is interchangeably called “matrix” or also “vector”. So don’t get panicked when I say for example “Matrix shape is 2 X 3”. All it means is that array looks something like this:
Now, Let’s talk about the shape of a default np array.
Shape is an attribute for np array. When a default array, say for example A is called with shape, here is how it looks.
This is a rank 1 matrix(array), where it just has 9 elements in a row.
Ideally it should be a 1 X 9 matrix right?
I agree with you, so that’s where reshape() comes into play. It is a method that changes the dimensions of your original matrix into your desired dimension.
Let’s look at reshape in action. You can pass a tuple of whatever dimension you want as long as the reshaped matrix and original matrix have the same number of elements.
Notice that reshape returns a multi-dim matrix. Two square brackets in the beginning indicate that. [[1, 2, 3, 4, 5, 6, 7, 8, 9]] is a potentially multi-dim matrix as opposed to [1, 2, 3, 4, 5, 6, 7, 8, 9].
If I look at B’s shape, it’s going to be (3,3):