Skip to content
Advertisement

How to prepare data outputted from sql in php to run through the PHP machine learning Library

I am playing around with the LeastSquares regression algorithm from the PHP ML library. I can successfully run the code with the example given but when I try to run data from my database I get a blank screen returned and no error logs on the server.

Here is the working example php file from the ML library:

$samples = [[50000, 2017], [40000, 2015], [75000, 2014], [30000, 2016]];   
$targets = [15000,13000,14500,14000];

regression = new LeastSquares();
$regression->train($samples, $targets);

echo $regression->predict([60000, 2015]);
// returns 4094.82

Here is myScript

$sql = "SELECT price, mileage, year From table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {

        // The output I am looking for is [[mileage, year],[mileage, year]..] & [price, price,..]

        $mileage = $row['mileage'];

        $year = $row['year'];
   
        $price = $row['price'];

    }
}


regression = new LeastSquares();
$regression->train($samples, $targets);

echo $regression->predict([60000, 2015]);

I am trying to recreate the $samples and $targets variables with values from my DB table but I am not preparing it correctly.I tried preg_replace to create a comma separated string but that didnt work, I suspect it’s because it’s a string and not integer values but Im not exactly sure. I wrote the example shown so might be a syntax error but im just trying to figure out the correct way to prepare the array values like the ML library gives.

When I do

var_dump($samples);

var_dump($targets);

I get

array(4) { [0]=> array(2) { [0]=> int(50000) [1]=> int(2017) } [1]=> array(2) { [0]=> int(40000) [1]=> int(2015) } [2]=> array(2) { [0]=> int(75000) [1]=> int(2014) } [3]=> array(2) { [0]=> int(30000) [1]=> int(2016) } }


array(4) { [0]=> int(15000) [1]=> int(13000) [2]=> int(14500) [3]=> int(14000) }

So that would be what I am trying to achieve with my SQL output

Advertisement

Answer

You just need to push the values you are reading from the database into the $samples and $targets arrays in your loop. It may also be necessary to convert them to integers, I’ve included that code too.

$sql = "SELECT price, mileage, year From table";
$result = $conn->query($sql);
$samples = array();
$targets = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $mileage = (int)$row['mileage'];
        $year = (int)$row['year'];
        $samples[] = array($mileage, $year);
        $price = (int)$row['price'];
        $targets[] = array($price);
    }
}

Note that without an else clause, the if ($result->num_rows > 0) { clause serves no useful purpose in this code as the while loop will not do anything if $result->num_rows == 0 (i.e. there are no rows in the result set).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement