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

55 lines
1.2 KiB
PHP
Raw Normal View History

<?php
2016-11-20 21:53:17 +00:00
declare(strict_types=1);
namespace Phpml\Dataset;
use Phpml\Exception\FileException;
2016-04-07 20:19:04 +00:00
class CsvDataset extends ArrayDataset
{
/**
* @var array
*/
protected $columnNames;
/**
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 FileException
*/
2016-04-07 20:35:49 +00:00
public function __construct(string $filepath, int $features, bool $headingRow = true)
{
if (!file_exists($filepath)) {
throw FileException::missingFile(basename($filepath));
}
2016-12-06 07:46:55 +00:00
if (false === $handle = fopen($filepath, 'rb')) {
throw FileException::cantOpenFile(basename($filepath));
2016-04-16 19:26:58 +00:00
}
2016-04-16 19:34:50 +00:00
if ($headingRow) {
$data = fgetcsv($handle, 1000, ',');
$this->columnNames = array_slice($data, 0, $features);
} else {
$this->columnNames = range(0, $features - 1);
2016-04-16 19:34:50 +00:00
}
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-16 19:26:58 +00:00
fclose($handle);
}
/**
* @return array
*/
public function getColumnNames()
{
return $this->columnNames;
}
}