Vectors creation using Numpy in Python

Vectors creation using Numpy in Python

·

2 min read

Hi there, it's Misba! I'm so glad you stopped by. I hope you'll enjoy reading my blog.

Introduction

In ML when we deal with a large set of Data, it is hard for us to implement math operations without using vectorization, it consumes lots of time, is not efficient, and is slow.

The Numpy operations use vectorization behind the scenes to make the code faster!

Let's explore how we can create vectors using NumPy.

What is Vector?

vector is a list of numbers, and vector algebra is operations performed on the numbers in the list.

in simple words,

vector is the numpy 1-D array.

In ML, vectors are used to encode the inputs, models, and outputs. By manipulating vectors, we can analyze and understand complex data sets.

Ways to create Vector

here are the common ways to create vectors in Numpy,

  1. From a Python List

import numpy as np 

#createn a list of numbers
my_list = [1,2,3,4,5]

#convert a list to a Numpy vector
my_vector = np.array(my_list)

#print the vector

print(my_vector)

#************** output : [1 2 3 4 5]
  1. With a specific data type

you can also specify the datatype of the element in your vector creation.

import numpy as np 

#create a vector of floats 
float_Vector = np.array([1.1,2.2,3.3],dtype=float)

#print the vector
print(float_vector)

#************* output = [1.1 2.2 3.3]
  1. Using Built-in Numpy functions

To generate vectors with specific vectors

  • np.zeros(shape) : creates a vector filled with zeros

  • np.ones(shape) : creates a vector filled with ones

  • np.arrange(start,stop,step): creates a vector with evenly spaced values within a specified range

    Shape : The shape of the resulting vector is inferred from the input object's length. For instance, if you provide a list with five elements, the vector will have a shape of (5,).

  1. np.zeros(shape)

     import numpy as np
    
     # Create a vector of five zeros
     zero_vector = np.zeros(5)
    
     # Print the vector
     print(zero_vector)
    
     #*************** output = [0. 0. 0. 0. 0.]
    
  2. np.ones(shape)

     import numpy as np
    
     # Create a vector of three ones
     one_vector = np.ones(3)
    
     # Print the vector
     print(one_vector)
    
     #*************** output = [1. 1. 1.]
    
  3. np.arrange(start,stop,step)

     import numpy as np
    
     # Create a vector with values from 1 to 6 (exclusive) with a step of 2
     my_arange_vector = np.arange(1, 7, 2)
    
     # Print the vector
     print(my_arange_vector)
    
     #*************** output = [1 3 5]
    

    Thanks for reading this article! If you have any feedback or questions, drop them in the comments and I'll get back to you.

    connect with me on Twitter, Linkedin, and Hashnode. Let's stay in touch :)!!