public function train() { $svm = new SVM(); $svm->setOptions(array(SVM::OPT_KERNEL_TYPE => SVM::KERNEL_LINEAR)); $trainings = CM_Db_Db::select('cm_svmtraining', array('class', 'values'), array('svmId' => $this->getId()))->fetchAll(); $problem = array(); $classCounts = array(); foreach ($trainings as $training) { $class = $training['class']; $values = unserialize($training['values']); if (!isset($classCounts[$class])) { $classCounts[$class] = 0; } $classCounts[$class]++; $problem[] = array_merge(array(0 => $class), $values); } $weights = array(); foreach ($classCounts as $class => $count) { $weights[$class] = min($classCounts) / $count; } if (empty($weights)) { $weights = null; } $this->_model = $svm->train($problem, $weights); $this->_model->save($this->_getFilePath()); }
/** * @param DataSourceInterface $dataSource * @param SVMModel $model * @param Document\NormalizerInterface $documentNormalizer * @param TokenizerInterface $tokenizer * @param Token\NormalizerInterface $tokenNormalizer * @param \SVM $svm * @param null $threshold */ public function __construct(DataSourceInterface $dataSource, SVMModel $model = null, Document\NormalizerInterface $documentNormalizer = null, TokenizerInterface $tokenizer = null, Token\NormalizerInterface $tokenNormalizer = null, \SVM $svm = null, $threshold = null) { $this->dataSource = $dataSource; $this->model = $model ?: new SVMModel(); $this->documentNormalizer = $documentNormalizer ?: new Document\Lowercase(); $this->tokenizer = $tokenizer ?: new Word(); $this->tokenNormalizer = $tokenNormalizer; if (!$svm) { $svm = new \SVM(); $svm->setOptions(array(\SVM::OPT_KERNEL_TYPE => \SVM::KERNEL_LINEAR)); } $this->svm = $svm; if ($threshold) { $this->setThreshold($threshold); } }
foreach ($data as $el) { if ($el[0] == 1) { $plus[] = $el; } else { $minus[] = $el; } } $SVMProblems = array(); for ($i = 0; $i < 10; $i++) { shuffle($plus); shuffle($minus); $problem = array_merge(array_slice($plus, 0, count($plus) / 2), array_slice($minus, count($minus) / 2)); $testProblem = array_merge(array_slice($plus, count($plus) / 2), array_slice($minus, 0, count($minus) / 2)); // SVM object $svm = new SVM(); $svm->setOptions(array(SVM::OPT_TYPE => SVM::C_SVC, SVM::OPT_KERNEL_TYPE => SVM::KERNEL_LINEAR)); $model = $svm->train($problem); $target = array(); foreach ($testProblem as $p) { unset($p[0]); $target[] = $model->predict($p); } $SVMProblems[] = new SVMProblem($testProblem, $target); } ?> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1">