libsvm_classifier.py :  » Math » Modular-toolkit-for-Data-Processing » MDP-2.6 » mdp » contrib » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Math » Modular toolkit for Data Processing 
Modular toolkit for Data Processing » MDP 2.6 » mdp » contrib » libsvm_classifier.py
import mdp
from mdp import numx

from svm_classifiers import _SVMClassifier,_LabelNormalizer

import svm as libsvm

class LibSVMClassifier(_SVMClassifier):
    """
    The LibSVMClassifier class acts as a wrapper around the LibSVM library
    for support vector machines.
        
    Information to the parameters can be found on
    http://www.csie.ntu.edu.tw/~cjlin/libsvm/
    """
    # The kernels and classifiers which LibSVM allows.
    kernels = ["RBF", "LINEAR", "POLY", "SIGMOID"]
    classifiers = ["C_SVC", "NU_SVC", "ONE_CLASS", "EPSILON_SVR", "NU_SVR"]

    def __init__(self, probability=True, input_dim=None, dtype=None):
        """
        probability -- Must be set to True, if algorithms based on probability
                       shall be used.
        """        
        self.kernel_type = libsvm.RBF
        self._probability = probability
        self._classification_type = "multi"
        super(LibSVMClassifier, self).__init__(input_dim=input_dim, dtype=dtype)

    def set_classifier(self, classifier):
        """
        Sets the classifier.
        
        classifier -- A string with the name of the classifier which 
                      should be used. Possible values are in 
                      self.classifiers
        """
        if classifier.upper() in self.classifiers:
            self.classifier_type = getattr(libsvm, classifier.upper())
        else:
            msg = "Classifier Type %s is unknown or not supported." % classifier
            raise TypeError(msg)

    def set_kernel(self, kernel):
        """
        Sets the kernel.
        
        kernel     -- A string with the name of the classifier which 
                      should be used. Possible values are in 
                      self.kernels
        """
        if kernel.upper() in self.kernels:
            self.kernel_type = getattr(libsvm, kernel.upper())
        else:
            msg = "Kernel Type %s is unknown or not supported." % kernel
            raise TypeError(msg)

    def _train_problem(self, labels, features, parameter):
        problem = libsvm.svm_problem(labels.tolist(), features.tolist())
        # Quieten libsvm
        # Method only available since libsvm 2.9 (on personal demand)
        try:
            libsvm.svmc.svm_set_quiet()
        except AttributeError:
            pass
        # Train
        model = libsvm.svm_model(problem, parameter)
        return model

    def _stop_training(self):
        super(LibSVMClassifier, self)._stop_training()
        self.normalizer = _LabelNormalizer(self.labels)
        
        if self._probability:
            prob = 1
        else:
            prob = 0
        self.parameter = libsvm.svm_parameter(svm_type=self.classifier_type,
                                              kernel_type=self.kernel_type,
                                              C=1, probability=prob)

        labels = self.normalizer.normalize(self.labels)
        features = self.data

        # Call svm training method.
        self.model = self._train_problem(labels, features, self.parameter)

    def _label(self, x):
        if isinstance(x, (list, tuple, numx.ndarray)):
            return numx.array([self.model.predict(xi) for xi in x]) 
        else:
            msg = "Data must be a sequence of vectors"
            raise mdp.NodeException(msg)

    def predict_probability(self, x):
        self._pre_execution_checks(x)
        if isinstance(x, (list, tuple, numx.ndarray)):
            return map(self.model.predict_probability, x)
        else:
            return self.model.predict_probability(x)

    def _prob(self, x):
        return [self.model.predict_probability(xi)[1] for xi in x]

    def _train(self, x, labels):
        super(LibSVMClassifier, self)._train(x, labels)

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.