php-ml/src/Phpml/Dataset/CsvDataset.php

43 lines
982 B
PHP
Raw Normal View History

<?php
declare (strict_types = 1);
namespace Phpml\Dataset;
use Phpml\Exception\DatasetException;
2016-04-07 20:19:04 +00:00
class CsvDataset extends ArrayDataset
{
/**
* @var string
*/
protected $filepath;
/**
2016-04-07 20:19:04 +00:00
* @param string|null $filepath
*
* @throws DatasetException
*/
2016-04-07 20:19:04 +00:00
public function __construct(string $filepath = null)
{
if (!file_exists($filepath)) {
throw DatasetException::missingFile(basename($filepath));
}
$row = 0;
if (($handle = fopen($filepath, 'r')) !== false) {
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
++$row;
if ($row == 1) {
continue;
}
$this->samples[] = array_slice($data, 0, 4);
2016-04-07 20:12:36 +00:00
$this->labels[] = $data[4];
}
fclose($handle);
} else {
throw DatasetException::cantOpenFile(basename($filepath));
}
}
}