En NumPy para calcular la array de covarianza de dos arrays dadas con la ayuda de numpy.cov() . En esto, pasaremos las dos arrays y devolverá la array de covarianza de dos arrays dadas.
Sintaxis: numpy.cov(m, y=Ninguno, rowvar=Verdadero, bias=Falso, ddof=Ninguno, fweights=Ninguno, aweights=Ninguno)
Ejemplo 1:
Python
import numpy as np array1 = np.array([0, 1, 1]) array2 = np.array([2, 2, 1]) # Original array1 print(array1) # Original array2 print(array2) # Covariance matrix print("\nCovariance matrix of the said arrays:\n", np.cov(array1, array2))
Producción:
[0 1 1] [2 2 1] Covariance matrix of the said arrays: [[ 0.33333333 -0.16666667] [-0.16666667 0.33333333]]
Ejemplo 2:
Python
import numpy as np array1 = np.array([2, 1, 1, 4]) array2 = np.array([2, 2, 1, 1]) # Original array1 print(array1) # Original array2 print(array2) # Covariance matrix print("\nCovariance matrix of the said arrays:\n", np.cov(array1, array2))
Producción:
[2 1 1 4] [2 2 1 1] Covariance matrix of the said arrays: [[ 2. -0.33333333] [-0.33333333 0.33333333]]
Ejemplo 3:
Python
import numpy as np array1 = np.array([1, 2]) array2 = np.array([1, 2]) # Original array1 print(array1) # Original array2 print(array2) # Covariance matrix print("\nCovariance matrix of the said arrays:\n", np.cov(array1, array2))
Producción
[1 2] [1 2] Covariance matrix of the said arrays: [[0.5 0.5] [0.5 0.5]]
Ejemplo 4:
Python
import numpy as np x = [1.23, 2.12, 3.34, 4.5] y = [2.56, 2.89, 3.76, 3.95] # find out covariance with respect # rows cov_mat = np.stack((x, y), axis = 1) print("shape of matrix x and y:", np.shape(cov_mat)) print("shape of covariance matrix:", np.shape(np.cov(cov_mat))) print(np.cov(cov_mat))
Producción
shape of matrix x and y: (4, 2) shape of covariance matrix: (4, 4) [[ 0.88445 0.51205 0.2793 -0.36575] [ 0.51205 0.29645 0.1617 -0.21175] [ 0.2793 0.1617 0.0882 -0.1155 ] [-0.36575 -0.21175 -0.1155 0.15125]]
Publicación traducida automáticamente
Artículo escrito por avengerjanus123 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA