×

Covariance in Python

Covariance is defined as the estimate of the difference of change between two variables or more variables. It defines the changes of two variables together.
In Python, The covariance can be calculated between two Numpy arrays by using the numpy.cov(a1,a2) function.
Here, a1 expresses the set of values of the first variable, and a2 expresses the set of values of the second variable.

A 2D array is returned by the numpy.cov() function. The value at index[0][0] is the covariance between a1 and a1 and the index[0][1] value is the covariance between a1 and a2.
Index[1][0] the value is the covariance between a2 and a1 and the index[1][1] value is the covariance between a2 and a2.

Example:

import numpy as np

array1 = np.array([3,1,4])

array2 = np.array([5,1,3])

covariance = np.cov(array1, array2)[0][1]

print(covariance)

Output:

2.0

Now, we will see the two equal length vectors with one increasing and the other decreasing.
It returns the square covariance matrix and access covariance for the two variables as [0,1].

Example:

from numpy import cov

x = np.array([2,4,1,6,2,1,7,5,8])

print(x)

y = np.array([7,2,3,1,8,6,2,3,4])

print(y)

Sigma = cov(x,y)[0,1]

print(Sigma)

Output:

[2,4,1,6,2,1,7,5,8]

[7,2,3,1,8,6,2,3,4]

-3.75

Covariance Matrix

The covariance matrix is defined as the symmetric matrix and square matrix. The covariance between two or more two arbitrary variables is described.
The covariance matrix element Cij is the covariance of xi and xj. The element Cii is the variance of xi.

  • If COV(xi, xj) = 0 then variables are discrete.
  • If COV(xi, xj) > 0 then variables are positively discrete.
  • If COV(xi, xj) > < 0 then variables are negatively discrete.

Syntax: 

numpy.cov( )

Example 1:

import numpy as np

x = np.array([[3, 1, 4], [7, 3, 8], [1, 5, 7]])

print("Array shape:\n", np.shape(x))

print("Covarinace matrix of x:\n", np.cov(x))

Output:

Array shape:

(3, 3)

Covarinace matrix of x:

[[2.33333333 4. 0.66666667]

[4. 7. 0. ]

[0.66666667 0. 9.33333333]]

Example 2:

import numpy as np

x = [1.21, 2.33, 3.21, 4.56]

y = [2.87, 2.78, 3.43, 3.65]

cov_mat = np.stack((x, y), axis = 0)

print(np.cov(cov_mat))

Output:

[[2.00389167 0.536775 ]

[0.536775 0.179825 ]]

Example 3:

import numpy as np

x = [1.21, 2.33, 3.21, 4.56]

y = [2.87, 2.78, 3.43, 3.65]

cov_mat = np.stack((x, y), axis = 1)

print("matrix x and y:", np.shape(cov_mat))

print("covariance matrix:", np.shape(np.cov(cov_mat)))

print(np.cov(cov_mat))

Output:

matrix x and y: (4, 2)

covariance matrix: (4, 4)

[[ 1.3778 0.3735 0.1826 -0.7553 ]

[ 0.3735 0.10125 0.0495 -0.20475]

[ 0.1826 0.0495 0.0242 -0.1001 ]

[-0.7553 -0.20475 -0.1001 0.41405]]

Straight Covariance Matrix

The structured relation in a matrix of random variables is separated by the tool provided by the covariance matrix. It is used for decorrelating the variables and practiced as a transform to other variables. It is referred to as the key element utilized in the PCA(Principal component analysis).

Now, we take an example of two 9 element vectors and calculating the straight covariance matrix.

Example:

from numpy import array

from numpy import cov

x = np.array([2,4,1,6,2,1,7,5,8])

print(x)

y = np.array([7,2,3,1,8,6,2,3,4])

print(y)

Sigma = cov(x,y)

print(Sigma)

Output:

[2,4,1,6,2,1,7,5,8]

[7,2,3,1,8,6,2,3,4]

[[ 7. -3.75]

[-3.75 6. ]]

Conclusion

In the above article, we have learned about the covariance in Python with which we can determine the differences between the variables.


Related Topics

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Python program to find factorial of a given number

Python program to find factorial of a given number Factorial is a non-negative integer. It is the product of all positive integers from 1 to the number we are going to...

3 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

Python next() function

Python next() function The next() function in Python retrieves the next item from the iterator.  Syntax next(iterator[, default]) Parameter iterable: It is a required parameter which represents an iterable object. default: This parameter represents a default value to...

1 minute read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Python Seaborn

Seaborn is an open-source library in Python that is used for data visualization and plotting graphs. The plots are used for the Visualization of data. It is built on top...

10 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Python tuple() function

Python tuple() function The tuple() function in Python creates a tuple object. Syntax tuple([iterable]) Parameter Iterable: This parameter represents a sequence, collection or an iterator object. Return This function returns a tuple object. Example 1 # Python Program explaining #...

1 minute read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.