Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phpml\Exception\MatrixException Message: Matrix is singular

I'm making a program that will predict the next year's collection from the database using php-ml.

and I'm getting this error.

Phpml\Exception\MatrixException Message: Matrix is singular

Im using this functions

use Phpml\Regression\LeastSquares;

use \Phpml\Math\Matrix;

use \Phpml\Math\Set;

newbie here.

Regression_controller

public function index()
{
    $this->load->model("regression_model") ;
    $array = $this->regression_model->display_data();
    $targets = $this->regression_model->display_data2();

    $matrix = new Matrix($array);
    $set = new Set($targets);

    $arraytrix = $matrix->toArray(); 
    $arrayset = $set->toArray();

    $col[] = array_column($arraytrix, 'year');
    $col2[] = array_column($arrayset, 'total');

    var_dump($col);
    var_dump($col2);

    $regression = new LeastSquares();
    $regression->train($col, $col2);

    $predicted = $regression->predict([2018]);

    var_dump($predicted);

    $this->load->view('regression');

}

Regression_model

function display_data()
{
    $query1 = $this->db->query("SELECT year from total_year");
    return $query1->result_array();

}
function display_data2()
{
    $query1 = $this->db->query("SELECT total from total_year");
    return $query1->result_array();
}
like image 221
stephoroi Avatar asked Dec 30 '25 19:12

stephoroi


1 Answers

The problem arises when all the values of a dataset attribute are similar in all records.

$samples = [ [1000,3,145], [1000,5,135], [1000,4,143], [1000,3,123]];

$targets = [ 4, 1, 3, 2];

$regression->train($samples, $targets);

In the above sample, the first values of all records ar equal to 1000. Therefore, when $regression->train($samples, $targets) is executed it sees attribute count of $sample is 2 instead of 3, which creates a mismatch between array dimension which is 3 x 4 not 2 x 4.

like image 109
Tharindu Sathischandra Avatar answered Jan 02 '26 11:01

Tharindu Sathischandra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!