Python - K Matrix Initialization


Matrix is a popular data representation technique in mathematics, machine modeling, etc. They are designed to deal with linear functions. Matrix initialization is a process to fill up the elements (rows and columns) of the matrix with either random or some predetermined values. After initialization there should be no undefined entries in the matrix. Initializing the matrix is one of the essential tasks in several fields, like competitive programming, machine and deep learning algorithms. In this article, we will learn how to initialize the matrix using various methods like loops, Numpy arrays, etc. We would also explore different types of initialization, like zero initialization, constraint initializations, etc.

Defining Custom Logic

Matrix initialization with any value k can be done with several looping statements like while loop, for loop, etc. We need to define our matrix and the value of k. Next, we need to iterate over the rows and columns and set the value at that position to k.

Example

In the following code, we have first created the custom function named initialized_matrix, which takes the number of rows, columns, and k as the parameters. We initialized a matrix with 0 dimensions. Next, we iterated over the rows, and for each row, we appended the value k to the cells of the matrix. Finally, we returned the resulting matrix.

def initialize_matrix(rows, columns, k=0):
    matrix = []
    for _ in range(rows):
        row = [k] * columns
        matrix.append(row)
    return matrix
rows = 5
columns = 5
k = -1
matrix = initialize_matrix(rows, columns, k)
print(f"The initialized matrix with {rows} rows and {columns} columns with initial values as {k} is:")
for row in matrix:
    print(row)

Output

The initialized matrix with 5 rows and 5 columns with initial values as -1 is:
[-1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1]

Zero Initialization With Numpy Array

Initializing the matrix with zero as the elements is one of the most common tasks in several programming techniques. This provides a starting point for computation and serves as a baseline for the operations. This is particularly useful when no prior information about the matrix is available, and we assume that the values of the matrix would be a positive number. Setting all the elements to zero also removes bias for any rows or columns.

Example

We used the Numpy array in the following code to initialize the matrix. We defined a function called initialize_matrix which takes the rows and columns as the parameters and returns the filled matrix. We used the zeros function, which takes the number of rows and columns as the parameters and fills them with 0.

import numpy as np
def initialize_k_matrix(rows, columns):
    k_matrix = np.zeros((rows, columns))
    return k_matrix
rows = 3
columns = 3
k_matrix = initialize_k_matrix(rows, columns)
print(f"Our Initialized matrix is: \n {k_matrix}")

Output

Our Initialized matrix is: 
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Initialization With One With Numpy Array

Another popular initialization is to initialize the matrix with one. This is useful when we want to set the base to be a whole number. In most cases, this is useful when we are certain that the values of the elements of the matrix won't be below 1. Numpy provides the Numpy function-” ones”, which takes the dimension of the array and returnees the array with all the elements filled with one.

Example

In the following example, we have first imported the library named Numpy. The initialize_matrix function takes the rows and columns as the parameters. We used the "ones" method of Numpy, which takes the dimension of the array in the form of a tuple and returns the array with all the elements filled with one.

import numpy as np
def initialize_k_matrix(rows, columns):
    k_matrix = np.ones((rows, columns))
    return k_matrix
rows = 5
columns = 4
k_matrix = initialize_k_matrix(rows, columns)
print(f"Our Initialized matrix is: \n {k_matrix}")

Output

Our Initialized matrix is: 
 [[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]

Random Initialization With Numpy Array

Random initialization is one of the most widely used techniques in deep learning. Random initialization means the initialization of the elements of the matrix with random numbers. In practice, they prove to give better results compared to the initialization with ones or zeros. However, in competitive coding, etc., this has zero to no use.

Example

In the following example, we used the “randint” method of Numpy to initialize the matrix with random numbers. We have used the “randint” method, which produces only integer numbers. However, you can choose other methods to initialize with floating point numbers, etc. k, and n signifies the range from which we need to pick up the random numbers.

import numpy as np
def initialize_k_matrix(rows, columns, k, n):
    k_matrix = np.random.randint(k, n, size=(rows, columns))
    return k_matrix

rows = 5
columns = 4
k = 19
n = 25
k_matrix = initialize_k_matrix(rows, columns, k, n)
print(f"Our Initialized matrix is: \n{k_matrix}")

Output

Our Initialized matrix is: 
[[22 21 23 21]
 [22 22 21 23]
 [20 20 19 24]
 [22 21 21 24]
 [21 21 23 20]]

Constraint Initialization

Constraint initialization is used to initialize matrices with specific constraints or properties. It involves setting the matrix's initial values to satisfy certain predefined conditions or constraints. For example, while dealing with optimization problems, we can utilize constraint initialization to ensure that the matrix satisfies certain linear or non−linear constraints. In machine learning and deep learning, constraint initialization is useful to weigh the metrics and impose some bounds to enforce sparsity.

Example

In the following code, we used the "full" method of the Numpy library to fill the matrix with specific values. We have created a function named initialize_k_matrix which takes the number of rows, columns, and values as the parameter. We used the "full" method of Numpy to fill the matrix with the values. Next, we returned the matrix.

import numpy as np

def initialize_k_matrix(rows, columns, value):
    k_matrix = np.full((rows, columns), value)
    return k_matrix
rows = 2
columns = 2
value = 5
k_matrix = initialize_k_matrix(rows, columns, value)
print(f"Our Initialized matrix is: \n{k_matrix}")

Output

Our Initialized matrix is: 
[[5 5]
 [5 5]]

Identity Initialization

Identity initialization is a technique used to initialize matrices with the identity matrix. The identity matrix is a square matrix where all diagonal elements are set to 1, and all off−diagonal elements are set to 0. It is denoted by the symbol "I" or "I_n" for an n x n identity matrix. When multiplied with another matrix, the identity matrix will give the same matrix.

Example

In the following code, we have used the Numpy library of Python to initialize the matrix. We used the eye method of the Numpy library to initialize the matrix. We passed the size of the matrix to the method. Note that since the identity matrix is always square, the number of rows equals the number of columns.

import numpy as np
def initialize_k_matrix(size):
    k_matrix = np.eye(size)
    return k_matrix
size = 3
k_matrix = initialize_k_matrix(size)
print(f"Our Initialized matrix is: \n{k_matrix}")

Output

Our Initialized matrix is: 
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Diagonal Initialization

Diagonal initialization is used to initialize matrices where only the diagonal elements have non−zero values. In this approach, the off−diagonal elements are set to zero, while the diagonal elements can have different values depending on the specific requirements. This is very useful in Electrical engineering, algebra, signal processing, etc., while dealing with eigenvalues, eigenvectors, etc. Numpy provides the "diag" method to implement it.

Example

import numpy as np

def initialize_k_matrix(diagonal_values):
    k_matrix = np.diag(diagonal_values)
    return k_matrix
diagonal_values = [1, 2, 3]
k_matrix = initialize_k_matrix(diagonal_values)
print(f"Our Initialized matrix is: \n{k_matrix}")

Output

Our Initialized matrix is: 
[[1 0 0]
 [0 2 0]
 [0 0 3]]

Conclusion

In this article, we understood how to initialize a matrix using different methods in Python. We can write our custom logic using the while loops, for loops, etc., or we can use the in−built functions available in Python. Several other libraries like Numpy also provide in−built methods to initialize the matrix with ones, zeros, random numbers, etc.

Updated on: 18-Jul-2023

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements