Renesas / opencv-lib

Dependents:   RZ_A2M_Mbed_samples

Embed: (wiki syntax)

« Back to documentation index

KNearest Class Reference

The class implements K-Nearest Neighbors model. More...

#include <ml.hpp>

Inherits cv::ml::StatModel.

Public Types

enum  Types
 

Implementations of KNearest algorithm.

More...
enum  Flags { , RAW_OUTPUT = 1 }
 

Predict options.

More...

Public Member Functions

virtual CV_WRAP int getDefaultK () const =0
 Default number of neighbors to use in predict method.
virtual CV_WRAP void setDefaultK (int val)=0
 

Default number of neighbors to use in predict method.


virtual CV_WRAP bool getIsClassifier () const =0
 Whether classification or regression model should be trained.
virtual CV_WRAP void setIsClassifier (bool val)=0
 

Whether classification or regression model should be trained.


virtual CV_WRAP int getEmax () const =0
 Parameter for KDTree implementation.
virtual CV_WRAP void setEmax (int val)=0
 

Parameter for KDTree implementation.


virtual CV_WRAP int getAlgorithmType () const =0
 Algorithm type, one of KNearest::Types.
virtual CV_WRAP void setAlgorithmType (int val)=0
 

Algorithm type, one of KNearest::Types.


virtual CV_WRAP float findNearest (InputArray samples, int k, OutputArray results, OutputArray neighborResponses=noArray(), OutputArray dist=noArray()) const =0
 Finds the neighbors and predicts responses for input vectors.
virtual CV_WRAP int getVarCount () const =0
 Returns the number of variables in training samples.
virtual CV_WRAP bool empty () const
 Returns true if the Algorithm is empty (e.g.
virtual CV_WRAP bool isTrained () const =0
 Returns true if the model is trained.
virtual CV_WRAP bool isClassifier () const =0
 Returns true if the model is classifier.
virtual CV_WRAP bool train (const Ptr< TrainData > &trainData, int flags=0)
 Trains the statistical model.
virtual CV_WRAP bool train (InputArray samples, int layout, InputArray responses)
 Trains the statistical model.
virtual CV_WRAP float calcError (const Ptr< TrainData > &data, bool test, OutputArray resp) const
 Computes error on the training or test dataset.
virtual CV_WRAP float predict (InputArray samples, OutputArray results=noArray(), int flags=0) const =0
 Predicts response(s) for the provided sample(s)
virtual CV_WRAP void clear ()
 Clears the algorithm state.
virtual void write (FileStorage &fs) const
 Stores algorithm parameters in a file storage.
virtual void read (const FileNode &fn)
 Reads algorithm parameters from a file storage.
virtual CV_WRAP void save (const String &filename) const
 Saves the algorithm to a file.
virtual CV_WRAP String getDefaultName () const
 Returns the algorithm string identifier.

Static Public Member Functions

static CV_WRAP Ptr< KNearestcreate ()
 Creates the empty model.
template<typename _Tp >
static Ptr< _Tp > train (const Ptr< TrainData > &data, int flags=0)
 Create and train model with default parameters.
template<typename _Tp >
static Ptr< _Tp > read (const FileNode &fn)
 Reads algorithm from the file node.
template<typename _Tp >
static Ptr< _Tp > load (const String &filename, const String &objname=String())
 Loads algorithm from the file.
template<typename _Tp >
static Ptr< _Tp > loadFromString (const String &strModel, const String &objname=String())
 Loads algorithm from a String.

Detailed Description

The class implements K-Nearest Neighbors model.

See also:
ml_intro_knn

Definition at line 406 of file ml.hpp.


Member Enumeration Documentation

enum Flags [inherited]

Predict options.

Enumerator:
RAW_OUTPUT 

makes the method return the raw results (the sum), not the class label

Reimplemented in DTrees.

Definition at line 303 of file ml.hpp.

enum Types

Implementations of KNearest algorithm.

Definition at line 467 of file ml.hpp.


Member Function Documentation

virtual CV_WRAP float calcError ( const Ptr< TrainData > &  data,
bool  test,
OutputArray  resp 
) const [virtual, inherited]

Computes error on the training or test dataset.

Parameters:
datathe training data
testif true, the error is computed over the test subset of the data, otherwise it's computed over the training subset of the data. Please note that if you loaded a completely different dataset to evaluate already trained classifier, you will probably want not to set the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so that the error is computed for the whole new set. Yes, this sounds a bit confusing.
respthe optional output responses.

The method uses StatModel::predict to compute the error. For regression models the error is computed as RMS, for classifiers - as a percent of missclassified samples (0-100%).

virtual CV_WRAP void clear (  ) [virtual, inherited]

Clears the algorithm state.

Reimplemented in DescriptorMatcher, and FlannBasedMatcher.

Definition at line 3030 of file core.hpp.

static CV_WRAP Ptr<KNearest> create (  ) [static]

Creates the empty model.

The static method creates empty KNearest classifier. It should be then trained using StatModel::train method.

virtual CV_WRAP bool empty (  ) const [virtual, inherited]

Returns true if the Algorithm is empty (e.g.

in the very beginning or after unsuccessful read

Reimplemented from Algorithm.

virtual CV_WRAP float findNearest ( InputArray  samples,
int  k,
OutputArray  results,
OutputArray  neighborResponses = noArray(),
OutputArray  dist = noArray() 
) const [pure virtual]

Finds the neighbors and predicts responses for input vectors.

Parameters:
samplesInput samples stored by rows. It is a single-precision floating-point matrix of `<number_of_samples> * k` size.
kNumber of used nearest neighbors. Should be greater than 1.
resultsVector with results of prediction (regression or classification) for each input sample. It is a single-precision floating-point vector with `<number_of_samples>` elements.
neighborResponsesOptional output values for corresponding neighbors. It is a single- precision floating-point matrix of `<number_of_samples> * k` size.
distOptional output distances from the input vectors to the corresponding neighbors. It is a single-precision floating-point matrix of `<number_of_samples> * k` size.

For each input vector (a row of the matrix samples), the method finds the k nearest neighbors. In case of regression, the predicted result is a mean value of the particular vector's neighbor responses. In case of classification, the class is determined by voting.

For each input vector, the neighbors are sorted by their distances to the vector.

In case of C++ interface you can use output pointers to empty matrices and the function will allocate memory itself.

If only a single input vector is passed, all output matrices are optional and the predicted value is returned by the method.

The function is parallelized with the TBB library.

virtual CV_WRAP int getAlgorithmType (  ) const [pure virtual]

Algorithm type, one of KNearest::Types.

See also:
setAlgorithmType
virtual CV_WRAP int getDefaultK (  ) const [pure virtual]

Default number of neighbors to use in predict method.

See also:
setDefaultK
virtual CV_WRAP String getDefaultName (  ) const [virtual, inherited]

Returns the algorithm string identifier.

This string is used as top level xml/yml node tag when the object is saved to a file or string.

virtual CV_WRAP int getEmax (  ) const [pure virtual]

Parameter for KDTree implementation.

See also:
setEmax
virtual CV_WRAP bool getIsClassifier (  ) const [pure virtual]

Whether classification or regression model should be trained.

See also:
setIsClassifier
virtual CV_WRAP int getVarCount (  ) const [pure virtual, inherited]

Returns the number of variables in training samples.

virtual CV_WRAP bool isClassifier (  ) const [pure virtual, inherited]

Returns true if the model is classifier.

virtual CV_WRAP bool isTrained (  ) const [pure virtual, inherited]

Returns true if the model is trained.

static Ptr<_Tp> load ( const String &  filename,
const String &  objname = String() 
) [static, inherited]

Loads algorithm from the file.

Parameters:
filenameName of the file to read.
objnameThe optional name of the node to read (if empty, the first top-level node will be used)

This is static template method of Algorithm. It's usage is following (in the case of SVM):

     Ptr<SVM> svm = Algorithm::load<SVM>("my_svm_model.xml");

In order to make this method work, the derived class must overwrite Algorithm::read(const FileNode& fn).

Definition at line 3074 of file core.hpp.

static Ptr<_Tp> loadFromString ( const String &  strModel,
const String &  objname = String() 
) [static, inherited]

Loads algorithm from a String.

Parameters:
strModelThe string variable containing the model you want to load.
objnameThe optional name of the node to read (if empty, the first top-level node will be used)

This is static template method of Algorithm. It's usage is following (in the case of SVM):

     Ptr<SVM> svm = Algorithm::loadFromString<SVM>(myStringModel);

Definition at line 3094 of file core.hpp.

virtual CV_WRAP float predict ( InputArray  samples,
OutputArray  results = noArray(),
int  flags = 0 
) const [pure virtual, inherited]

Predicts response(s) for the provided sample(s)

Parameters:
samplesThe input samples, floating-point matrix
resultsThe optional output matrix of results.
flagsThe optional flags, model-dependent. See cv::ml::StatModel::Flags.

Implemented in LogisticRegression.

static Ptr<_Tp> read ( const FileNode fn ) [static, inherited]

Reads algorithm from the file node.

This is static template method of Algorithm. It's usage is following (in the case of SVM):

     cv::FileStorage fsRead("example.xml", FileStorage::READ);
     Ptr<SVM> svm = Algorithm::read<SVM>(fsRead.root());

In order to make this method work, the derived class must overwrite Algorithm::read(const FileNode& fn) and also have static create() method without parameters (or with all the optional parameters)

Reimplemented in Feature2D, DescriptorMatcher, and FlannBasedMatcher.

Definition at line 3055 of file core.hpp.

virtual void read ( const FileNode fn ) [virtual, inherited]

Reads algorithm parameters from a file storage.

Reimplemented in Feature2D, DescriptorMatcher, and FlannBasedMatcher.

Definition at line 3038 of file core.hpp.

virtual CV_WRAP void save ( const String &  filename ) const [virtual, inherited]

Saves the algorithm to a file.

In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs).

virtual CV_WRAP void setAlgorithmType ( int  val ) [pure virtual]

Algorithm type, one of KNearest::Types.

See also:
getAlgorithmType
virtual CV_WRAP void setDefaultK ( int  val ) [pure virtual]

Default number of neighbors to use in predict method.

See also:
getDefaultK
virtual CV_WRAP void setEmax ( int  val ) [pure virtual]

Parameter for KDTree implementation.

See also:
getEmax
virtual CV_WRAP void setIsClassifier ( bool  val ) [pure virtual]

Whether classification or regression model should be trained.

See also:
getIsClassifier
virtual CV_WRAP bool train ( const Ptr< TrainData > &  trainData,
int  flags = 0 
) [virtual, inherited]

Trains the statistical model.

Parameters:
trainDatatraining data that can be loaded from file using TrainData::loadFromCSV or created with TrainData::create.
flagsoptional flags, depending on the model. Some of the models can be updated with the new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP).
static Ptr<_Tp> train ( const Ptr< TrainData > &  data,
int  flags = 0 
) [static, inherited]

Create and train model with default parameters.

The class must implement static `create()` method with no parameters or with all default parameter values

Definition at line 364 of file ml.hpp.

virtual CV_WRAP bool train ( InputArray  samples,
int  layout,
InputArray  responses 
) [virtual, inherited]

Trains the statistical model.

Parameters:
samplestraining samples
layoutSee ml::SampleTypes.
responsesvector of responses associated with the training samples.
virtual void write ( FileStorage fs ) const [virtual, inherited]

Stores algorithm parameters in a file storage.

Reimplemented in Feature2D, DescriptorMatcher, and FlannBasedMatcher.

Definition at line 3034 of file core.hpp.