2016-04-06 20:38:08 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare (strict_types = 1);
|
|
|
|
|
|
|
|
namespace Phpml\Dataset;
|
|
|
|
|
|
|
|
use Phpml\Exception\DatasetException;
|
|
|
|
|
2016-04-07 20:19:04 +00:00
|
|
|
class CsvDataset extends ArrayDataset
|
2016-04-06 20:38:08 +00:00
|
|
|
{
|
|
|
|
/**
|
2016-04-07 20:35:49 +00:00
|
|
|
* @param string $filepath
|
|
|
|
* @param int $features
|
|
|
|
* @param bool $headingRow
|
2016-04-07 20:19:04 +00:00
|
|
|
*
|
|
|
|
* @throws DatasetException
|
2016-04-06 20:38:08 +00:00
|
|
|
*/
|
2016-04-07 20:35:49 +00:00
|
|
|
public function __construct(string $filepath, int $features, bool $headingRow = true)
|
2016-04-06 20:38:08 +00:00
|
|
|
{
|
|
|
|
if (!file_exists($filepath)) {
|
|
|
|
throw DatasetException::missingFile(basename($filepath));
|
|
|
|
}
|
|
|
|
|
2016-04-16 19:41:37 +00:00
|
|
|
if (false === $handle = fopen($filepath, 'r')) {
|
2016-04-16 19:26:58 +00:00
|
|
|
throw DatasetException::cantOpenFile(basename($filepath));
|
|
|
|
}
|
2016-04-16 19:34:50 +00:00
|
|
|
|
|
|
|
if ($headingRow) {
|
|
|
|
fgets($handle);
|
|
|
|
}
|
|
|
|
|
2016-04-16 19:26:58 +00:00
|
|
|
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
|
|
|
|
$this->samples[] = array_slice($data, 0, $features);
|
2016-06-16 21:56:15 +00:00
|
|
|
$this->targets[] = $data[$features];
|
2016-04-06 20:38:08 +00:00
|
|
|
}
|
2016-04-16 19:26:58 +00:00
|
|
|
fclose($handle);
|
2016-04-06 20:38:08 +00:00
|
|
|
}
|
|
|
|
}
|