×

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 Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Python program to display ASCII value of the character

Python program to display ASCII value of the character The full form of ASCII is American Standard Code for Information Interchange. This example explains a program in Python to find the...

1 minute read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Difference between For Loop and While Loop in Python

What is the “For” loop? The “For” Loop is a commonly used control structure in programming that allows us to repeat a set of actions multiple times. The “For” loop is...

3 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Python any() Function

Python any() Function The any() function in Python returns a boolean value ‘True’ if any element of the iterable is true or if the iterable is empty, else it returns False. Syntax any(iterable) Parameter Iterable: An iterable object (list, tuple, dictionary) Return This...

1 minute read.

Python PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as...

3 minutes read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Anaconda python 3.7 download for windows 10 64-bit

Before installing Anaconda, you need to first know what Anaconda actually is. Anaconda is an IDE (Integrated development environment) platform used to code and executes python programs. Anaconda works both online...

3 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

Python Setup guide and installation

Python Installation guide Step by Step Python is widely used high-level programming language. The first version of Python was launched in 1991. Since then, Python has been gaining popularity. It is considered as...

4 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.