Matrix Tutorial for AI programming

SPVM has Matrix modules.

Float Matrix

Corresponding modules are SPVM::AI::Util, SPVM::AI::Util::FloatMatrix.

These modules have matrix elements, number of rows, and number of columns as fields.

These modules also have methods to do additions, subtractions, multiplications, scalar multiplys, transpositions, and string conversions.

Matrix Examples

You can find a sample matrix here.

Matrix Examples

Matrix Tutorial

When do we use a numerci matrix?

One example is when you want to solve a system of simultaneous equations.

Solving simultaneous equations using a matrix can also be used in deep learning calculations.

Let's calculate the matrix using the float type in anticipation of calculating with CUDA.

The following is a Perl program. Calling SPVM subroutine.

use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/lib";

use SPVM 'MyMatrix';

MyMatrix->add_float_matrix;

MyMatrix->sub_float_matrix;

MyMatrix->scamal_float_matrix;

MyMatrix->mal_float_matrix;

The following are SPVM modules.

The addition, subtract, multiply, scalar multiply, and convert matrix to string.

Note that the SPVM matrix module is column-major.

package MyMatrix {
  use SPVM::AI::Util;
  
  sub add_float_matrix : void () {
    # 1 3 5
    # 2 4 6
    my $mat1 = SPVM::AI::Util->mat_newf([1f, 2f, 3f, 4f, 5f, 6f], 2, 3);
    
    # 2 4 6
    # 3 5 7
    my $mat2 = SPVM::AI::Util->mat_newf([2f, 3f, 4f, 5f, 6f, 7f], 2, 3);
    
    my $mat3 = SPVM::AI::Util->mat_addf($mat1, $mat2);
    
    print SPVM::AI::Util->mat_strf($mat3) . "\n";
  }

  sub sub_float_matrix : void () {
    # 1 3 5
    # 2 4 6
    my $mat1 = SPVM::AI::Util->mat_newf([1f, 2f, 3f, 4f, 5f, 6f], 2, 3);
    
    # 2 4 6
    # 3 5 7
    my $mat2 = SPVM::AI::Util->mat_newf([2f, 3f, 4f, 5f, 6f, 7f], 2, 3);
    
    my $mat3 = SPVM::AI::Util->mat_subf($mat1, $mat2);
    
    print SPVM::AI::Util->mat_strf($mat3) . "\n";
  }

  sub scamul_float_matrix : void () {
    # 1 3 5
    # 2 4 6
    my $mat1 = SPVM::AI::Util->mat_newf([1f, 2f, 3f, 4f, 5f, 6f], 2, 3);
    
    my $mat3 = SPVM::AI::Util->mat_scamulf(3f, $mat1);
    
    print SPVM::AI::Util->mat_strf($mat3) . "\n";
  }

  sub mul_float_matrix : void () {
    # 1 3 5
    # 2 4 6
    my $mat1 = SPVM::AI::Util->mat_newf([1f, 2f, 3f, 4f, 5f, 6f], 2, 3);
    
    # 2 5
    # 3 6
    # 4 7
    my $mat2 = SPVM::AI::Util->mat_newf([2f, 3f, 4f, 5f, 6f, 7f], 3, 2);
    
    my $mat3 = SPVM::AI::Util->mat_mulf($mat1, $mat2);
    
    print SPVM::AI::Util->mat_strf($mat3) . "\n";
  }
}

Output are:

3 7 11
5 9 13

-1 -1 -1
-1 -1 -1

3 9 15
6 12 18

31 58
40 76