SciPy - khatri_rao() Function



SciPy's Khatri-rao() method calculates the Khatri-rao product of two input matrices A and B. This product involves a column-wise Kronecker product. Each column in the result comes from the Kronecker product of matching columns in A and B.

A matrix with dimensions (m,n) and B matrix with dimensions (p,n) will produce a Khatri-rao product A()B with dimensions (mp,n).

People often use this in tensor decomposition, signal processing, and multi-linear algebra.

Syntax

The syntax for the Scipy Khatri-rao method is as follows −

.khatri_rao(a, b)

Parameters

This method accepts the following parameters −

  • a,b − The input matrices A and B. Both matrices must have the same number of columns.

Return Value

A 2D array representing the Khatri-Rao product of a and b.

Example 1

This is the basic example that shows how to use the Khatri-rao() method. We make two matrices, 'A' and 'B' then figure out their Khatri-rao () product.

import numpy as np
from scipy.linalg import khatri_rao

# Define matrices A and B
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Compute the Khatri-Rao product
result = khatri_rao(A, B)

print("Khatri-Rao Product:")
print(result)

When we run above program, it produces following result

Khatri-Rao Product:
[[ 5 12]
 [ 7 16]
 [15 24]
 [21 32]]

Example 2

The Khatri-Rao product plays a key role in tensor decomposition methods like CP decomposition. This method breaks down a large tensor into simpler parts (rank-1 tensors). It helps to create middle-step matrices by joining information from different dimensions. This makes it easier to show and study complex high-dimensional data.

import numpy as np
from scipy.linalg import khatri_rao

# Define factor matrices
A = np.array([[1, 0.5], [0.2, 0.3]])
B = np.array([[2, 1.2], [0.4, 0.7]])

# Compute the Khatri-Rao product
factor_product = khatri_rao(A, B)

print("Factor Matrix Product:\n", factor_product)

Following is an output of the above code

Factor Matrix Product:
 [[2.   0.6 ]
 [0.4  0.35]
 [0.4  0.36]
 [0.08 0.21]] 
scipy_linalg.htm
Advertisements