mirror of https://github.com/opencv/opencv.git
parent
10b60f8d16
commit
c20ff6ce19
31 changed files with 11907 additions and 9058 deletions
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,792 @@ |
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
#include "old_ml_precomp.hpp" |
||||
#include <ctype.h> |
||||
|
||||
#define MISS_VAL FLT_MAX |
||||
#define CV_VAR_MISS 0 |
||||
|
||||
CvTrainTestSplit::CvTrainTestSplit() |
||||
{ |
||||
train_sample_part_mode = CV_COUNT; |
||||
train_sample_part.count = -1; |
||||
mix = false; |
||||
} |
||||
|
||||
CvTrainTestSplit::CvTrainTestSplit( int _train_sample_count, bool _mix ) |
||||
{ |
||||
train_sample_part_mode = CV_COUNT; |
||||
train_sample_part.count = _train_sample_count; |
||||
mix = _mix; |
||||
} |
||||
|
||||
CvTrainTestSplit::CvTrainTestSplit( float _train_sample_portion, bool _mix ) |
||||
{ |
||||
train_sample_part_mode = CV_PORTION; |
||||
train_sample_part.portion = _train_sample_portion; |
||||
mix = _mix; |
||||
} |
||||
|
||||
////////////////
|
||||
|
||||
CvMLData::CvMLData() |
||||
{ |
||||
values = missing = var_types = var_idx_mask = response_out = var_idx_out = var_types_out = 0; |
||||
train_sample_idx = test_sample_idx = 0; |
||||
header_lines_number = 0; |
||||
sample_idx = 0; |
||||
response_idx = -1; |
||||
|
||||
train_sample_count = -1; |
||||
|
||||
delimiter = ','; |
||||
miss_ch = '?'; |
||||
//flt_separator = '.';
|
||||
|
||||
rng = &cv::theRNG(); |
||||
} |
||||
|
||||
CvMLData::~CvMLData() |
||||
{ |
||||
clear(); |
||||
} |
||||
|
||||
void CvMLData::free_train_test_idx() |
||||
{ |
||||
cvReleaseMat( &train_sample_idx ); |
||||
cvReleaseMat( &test_sample_idx ); |
||||
sample_idx = 0; |
||||
} |
||||
|
||||
void CvMLData::clear() |
||||
{ |
||||
class_map.clear(); |
||||
|
||||
cvReleaseMat( &values ); |
||||
cvReleaseMat( &missing ); |
||||
cvReleaseMat( &var_types ); |
||||
cvReleaseMat( &var_idx_mask ); |
||||
|
||||
cvReleaseMat( &response_out ); |
||||
cvReleaseMat( &var_idx_out ); |
||||
cvReleaseMat( &var_types_out ); |
||||
|
||||
free_train_test_idx(); |
||||
|
||||
total_class_count = 0; |
||||
|
||||
response_idx = -1; |
||||
|
||||
train_sample_count = -1; |
||||
} |
||||
|
||||
|
||||
void CvMLData::set_header_lines_number( int idx ) |
||||
{ |
||||
header_lines_number = std::max(0, idx); |
||||
} |
||||
|
||||
int CvMLData::get_header_lines_number() const |
||||
{ |
||||
return header_lines_number; |
||||
} |
||||
|
||||
static char *fgets_chomp(char *str, int n, FILE *stream) |
||||
{ |
||||
char *head = fgets(str, n, stream); |
||||
if( head ) |
||||
{ |
||||
for(char *tail = head + strlen(head) - 1; tail >= head; --tail) |
||||
{ |
||||
if( *tail != '\r' && *tail != '\n' ) |
||||
break; |
||||
*tail = '\0'; |
||||
} |
||||
} |
||||
return head; |
||||
} |
||||
|
||||
|
||||
int CvMLData::read_csv(const char* filename) |
||||
{ |
||||
const int M = 1000000; |
||||
const char str_delimiter[3] = { ' ', delimiter, '\0' }; |
||||
FILE* file = 0; |
||||
CvMemStorage* storage; |
||||
CvSeq* seq; |
||||
char *ptr; |
||||
float* el_ptr; |
||||
CvSeqReader reader; |
||||
int cols_count = 0; |
||||
uchar *var_types_ptr = 0; |
||||
|
||||
clear(); |
||||
|
||||
file = fopen( filename, "rt" ); |
||||
|
||||
if( !file ) |
||||
return -1; |
||||
|
||||
std::vector<char> _buf(M); |
||||
char* buf = &_buf[0]; |
||||
|
||||
// skip header lines
|
||||
for( int i = 0; i < header_lines_number; i++ ) |
||||
{ |
||||
if( fgets( buf, M, file ) == 0 ) |
||||
{ |
||||
fclose(file); |
||||
return -1; |
||||
} |
||||
} |
||||
|
||||
// read the first data line and determine the number of variables
|
||||
if( !fgets_chomp( buf, M, file )) |
||||
{ |
||||
fclose(file); |
||||
return -1; |
||||
} |
||||
|
||||
ptr = buf; |
||||
while( *ptr == ' ' ) |
||||
ptr++; |
||||
for( ; *ptr != '\0'; ) |
||||
{ |
||||
if(*ptr == delimiter || *ptr == ' ') |
||||
{ |
||||
cols_count++; |
||||
ptr++; |
||||
while( *ptr == ' ' ) ptr++; |
||||
} |
||||
else |
||||
ptr++; |
||||
} |
||||
|
||||
cols_count++; |
||||
|
||||
if ( cols_count == 0) |
||||
{ |
||||
fclose(file); |
||||
return -1; |
||||
} |
||||
|
||||
// create temporary memory storage to store the whole database
|
||||
el_ptr = new float[cols_count]; |
||||
storage = cvCreateMemStorage(); |
||||
seq = cvCreateSeq( 0, sizeof(*seq), cols_count*sizeof(float), storage ); |
||||
|
||||
var_types = cvCreateMat( 1, cols_count, CV_8U ); |
||||
cvZero( var_types ); |
||||
var_types_ptr = var_types->data.ptr; |
||||
|
||||
for(;;) |
||||
{ |
||||
char *token = NULL; |
||||
int type; |
||||
token = strtok(buf, str_delimiter); |
||||
if (!token) |
||||
break; |
||||
for (int i = 0; i < cols_count-1; i++) |
||||
{ |
||||
str_to_flt_elem( token, el_ptr[i], type); |
||||
var_types_ptr[i] |= type; |
||||
token = strtok(NULL, str_delimiter); |
||||
if (!token) |
||||
{ |
||||
fclose(file); |
||||
delete [] el_ptr; |
||||
return -1; |
||||
} |
||||
} |
||||
str_to_flt_elem( token, el_ptr[cols_count-1], type); |
||||
var_types_ptr[cols_count-1] |= type; |
||||
cvSeqPush( seq, el_ptr ); |
||||
if( !fgets_chomp( buf, M, file ) ) |
||||
break; |
||||
} |
||||
fclose(file); |
||||
|
||||
values = cvCreateMat( seq->total, cols_count, CV_32FC1 ); |
||||
missing = cvCreateMat( seq->total, cols_count, CV_8U ); |
||||
var_idx_mask = cvCreateMat( 1, values->cols, CV_8UC1 ); |
||||
cvSet( var_idx_mask, cvRealScalar(1) ); |
||||
train_sample_count = seq->total; |
||||
|
||||
cvStartReadSeq( seq, &reader ); |
||||
for(int i = 0; i < seq->total; i++ ) |
||||
{ |
||||
const float* sdata = (float*)reader.ptr; |
||||
float* ddata = values->data.fl + cols_count*i; |
||||
uchar* dm = missing->data.ptr + cols_count*i; |
||||
|
||||
for( int j = 0; j < cols_count; j++ ) |
||||
{ |
||||
ddata[j] = sdata[j]; |
||||
dm[j] = ( fabs( MISS_VAL - sdata[j] ) <= FLT_EPSILON ); |
||||
} |
||||
CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); |
||||
} |
||||
|
||||
if ( cvNorm( missing, 0, CV_L1 ) <= FLT_EPSILON ) |
||||
cvReleaseMat( &missing ); |
||||
|
||||
cvReleaseMemStorage( &storage ); |
||||
delete []el_ptr; |
||||
return 0; |
||||
} |
||||
|
||||
const CvMat* CvMLData::get_values() const |
||||
{ |
||||
return values; |
||||
} |
||||
|
||||
const CvMat* CvMLData::get_missing() const |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::get_missing" ); |
||||
__BEGIN__; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
|
||||
__END__; |
||||
|
||||
return missing; |
||||
} |
||||
|
||||
const std::map<cv::String, int>& CvMLData::get_class_labels_map() const |
||||
{ |
||||
return class_map; |
||||
} |
||||
|
||||
void CvMLData::str_to_flt_elem( const char* token, float& flt_elem, int& type) |
||||
{ |
||||
|
||||
char* stopstring = NULL; |
||||
flt_elem = (float)strtod( token, &stopstring ); |
||||
assert( stopstring ); |
||||
type = CV_VAR_ORDERED; |
||||
if ( *stopstring == miss_ch && strlen(stopstring) == 1 ) // missed value
|
||||
{ |
||||
flt_elem = MISS_VAL; |
||||
type = CV_VAR_MISS; |
||||
} |
||||
else |
||||
{ |
||||
if ( (*stopstring != 0) && (*stopstring != '\n') && (strcmp(stopstring, "\r\n") != 0) ) // class label
|
||||
{ |
||||
int idx = class_map[token]; |
||||
if ( idx == 0) |
||||
{ |
||||
total_class_count++; |
||||
idx = total_class_count; |
||||
class_map[token] = idx; |
||||
} |
||||
flt_elem = (float)idx; |
||||
type = CV_VAR_CATEGORICAL; |
||||
} |
||||
} |
||||
} |
||||
|
||||
void CvMLData::set_delimiter(char ch) |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::set_delimited" ); |
||||
__BEGIN__; |
||||
|
||||
if (ch == miss_ch /*|| ch == flt_separator*/) |
||||
CV_ERROR(CV_StsBadArg, "delimited, miss_character and flt_separator must be different"); |
||||
|
||||
delimiter = ch; |
||||
|
||||
__END__; |
||||
} |
||||
|
||||
char CvMLData::get_delimiter() const |
||||
{ |
||||
return delimiter; |
||||
} |
||||
|
||||
void CvMLData::set_miss_ch(char ch) |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::set_miss_ch" ); |
||||
__BEGIN__; |
||||
|
||||
if (ch == delimiter/* || ch == flt_separator*/) |
||||
CV_ERROR(CV_StsBadArg, "delimited, miss_character and flt_separator must be different"); |
||||
|
||||
miss_ch = ch; |
||||
|
||||
__END__; |
||||
} |
||||
|
||||
char CvMLData::get_miss_ch() const |
||||
{ |
||||
return miss_ch; |
||||
} |
||||
|
||||
void CvMLData::set_response_idx( int idx ) |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::set_response_idx" ); |
||||
__BEGIN__; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
|
||||
if ( idx >= values->cols) |
||||
CV_ERROR( CV_StsBadArg, "idx value is not correct" ); |
||||
|
||||
if ( response_idx >= 0 ) |
||||
chahge_var_idx( response_idx, true ); |
||||
if ( idx >= 0 ) |
||||
chahge_var_idx( idx, false ); |
||||
response_idx = idx; |
||||
|
||||
__END__; |
||||
} |
||||
|
||||
int CvMLData::get_response_idx() const |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::get_response_idx" ); |
||||
__BEGIN__; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
__END__; |
||||
return response_idx; |
||||
} |
||||
|
||||
void CvMLData::change_var_type( int var_idx, int type ) |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::change_var_type" ); |
||||
__BEGIN__; |
||||
|
||||
int var_count = 0; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
|
||||
var_count = values->cols; |
||||
|
||||
if ( var_idx < 0 || var_idx >= var_count) |
||||
CV_ERROR( CV_StsBadArg, "var_idx is not correct" ); |
||||
|
||||
if ( type != CV_VAR_ORDERED && type != CV_VAR_CATEGORICAL) |
||||
CV_ERROR( CV_StsBadArg, "type is not correct" ); |
||||
|
||||
assert( var_types ); |
||||
if ( var_types->data.ptr[var_idx] == CV_VAR_CATEGORICAL && type == CV_VAR_ORDERED) |
||||
CV_ERROR( CV_StsBadArg, "it`s impossible to assign CV_VAR_ORDERED type to categorical variable" ); |
||||
var_types->data.ptr[var_idx] = (uchar)type; |
||||
|
||||
__END__; |
||||
|
||||
return; |
||||
} |
||||
|
||||
void CvMLData::set_var_types( const char* str ) |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::set_var_types" ); |
||||
__BEGIN__; |
||||
|
||||
const char* ord = 0, *cat = 0; |
||||
int var_count = 0, set_var_type_count = 0; |
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
|
||||
var_count = values->cols; |
||||
|
||||
assert( var_types ); |
||||
|
||||
ord = strstr( str, "ord" ); |
||||
cat = strstr( str, "cat" ); |
||||
if ( !ord && !cat ) |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
|
||||
if ( !ord && strlen(cat) == 3 ) // str == "cat"
|
||||
{ |
||||
cvSet( var_types, cvScalarAll(CV_VAR_CATEGORICAL) ); |
||||
return; |
||||
} |
||||
|
||||
if ( !cat && strlen(ord) == 3 ) // str == "ord"
|
||||
{ |
||||
cvSet( var_types, cvScalarAll(CV_VAR_ORDERED) ); |
||||
return; |
||||
} |
||||
|
||||
if ( ord ) // parse ord str
|
||||
{ |
||||
char* stopstring = NULL; |
||||
if ( ord[3] != '[') |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
|
||||
ord += 4; // pass "ord["
|
||||
do |
||||
{ |
||||
int b1 = (int)strtod( ord, &stopstring ); |
||||
if ( *stopstring == 0 || (*stopstring != ',' && *stopstring != ']' && *stopstring != '-') ) |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
ord = stopstring + 1; |
||||
if ( (stopstring[0] == ',') || (stopstring[0] == ']')) |
||||
{ |
||||
if ( var_types->data.ptr[b1] == CV_VAR_CATEGORICAL) |
||||
CV_ERROR( CV_StsBadArg, "it`s impossible to assign CV_VAR_ORDERED type to categorical variable" ); |
||||
var_types->data.ptr[b1] = CV_VAR_ORDERED; |
||||
set_var_type_count++; |
||||
} |
||||
else |
||||
{ |
||||
if ( stopstring[0] == '-') |
||||
{ |
||||
int b2 = (int)strtod( ord, &stopstring); |
||||
if ( (*stopstring == 0) || (*stopstring != ',' && *stopstring != ']') ) |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
ord = stopstring + 1; |
||||
for (int i = b1; i <= b2; i++) |
||||
{ |
||||
if ( var_types->data.ptr[i] == CV_VAR_CATEGORICAL) |
||||
CV_ERROR( CV_StsBadArg, "it`s impossible to assign CV_VAR_ORDERED type to categorical variable" ); |
||||
var_types->data.ptr[i] = CV_VAR_ORDERED; |
||||
} |
||||
set_var_type_count += b2 - b1 + 1; |
||||
} |
||||
else |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
|
||||
} |
||||
} |
||||
while (*stopstring != ']'); |
||||
|
||||
if ( stopstring[1] != '\0' && stopstring[1] != ',') |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
} |
||||
|
||||
if ( cat ) // parse cat str
|
||||
{ |
||||
char* stopstring = NULL; |
||||
if ( cat[3] != '[') |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
|
||||
cat += 4; // pass "cat["
|
||||
do |
||||
{ |
||||
int b1 = (int)strtod( cat, &stopstring ); |
||||
if ( *stopstring == 0 || (*stopstring != ',' && *stopstring != ']' && *stopstring != '-') ) |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
cat = stopstring + 1; |
||||
if ( (stopstring[0] == ',') || (stopstring[0] == ']')) |
||||
{ |
||||
var_types->data.ptr[b1] = CV_VAR_CATEGORICAL; |
||||
set_var_type_count++; |
||||
} |
||||
else |
||||
{ |
||||
if ( stopstring[0] == '-') |
||||
{ |
||||
int b2 = (int)strtod( cat, &stopstring); |
||||
if ( (*stopstring == 0) || (*stopstring != ',' && *stopstring != ']') ) |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
cat = stopstring + 1; |
||||
for (int i = b1; i <= b2; i++) |
||||
var_types->data.ptr[i] = CV_VAR_CATEGORICAL; |
||||
set_var_type_count += b2 - b1 + 1; |
||||
} |
||||
else |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
|
||||
} |
||||
} |
||||
while (*stopstring != ']'); |
||||
|
||||
if ( stopstring[1] != '\0' && stopstring[1] != ',') |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
} |
||||
|
||||
if (set_var_type_count != var_count) |
||||
CV_ERROR( CV_StsBadArg, "types string is not correct" ); |
||||
|
||||
__END__; |
||||
} |
||||
|
||||
const CvMat* CvMLData::get_var_types() |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::get_var_types" ); |
||||
__BEGIN__; |
||||
|
||||
uchar *var_types_out_ptr = 0; |
||||
int avcount, vt_size; |
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
|
||||
assert( var_idx_mask ); |
||||
|
||||
avcount = cvFloor( cvNorm( var_idx_mask, 0, CV_L1 ) ); |
||||
vt_size = avcount + (response_idx >= 0); |
||||
|
||||
if ( avcount == values->cols || (avcount == values->cols-1 && response_idx == values->cols-1) ) |
||||
return var_types; |
||||
|
||||
if ( !var_types_out || ( var_types_out && var_types_out->cols != vt_size ) ) |
||||
{ |
||||
cvReleaseMat( &var_types_out ); |
||||
var_types_out = cvCreateMat( 1, vt_size, CV_8UC1 ); |
||||
} |
||||
|
||||
var_types_out_ptr = var_types_out->data.ptr; |
||||
for( int i = 0; i < var_types->cols; i++) |
||||
{ |
||||
if (i == response_idx || !var_idx_mask->data.ptr[i]) continue; |
||||
*var_types_out_ptr = var_types->data.ptr[i]; |
||||
var_types_out_ptr++; |
||||
} |
||||
if ( response_idx >= 0 ) |
||||
*var_types_out_ptr = var_types->data.ptr[response_idx]; |
||||
|
||||
__END__; |
||||
|
||||
return var_types_out; |
||||
} |
||||
|
||||
int CvMLData::get_var_type( int var_idx ) const |
||||
{ |
||||
return var_types->data.ptr[var_idx]; |
||||
} |
||||
|
||||
const CvMat* CvMLData::get_responses() |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::get_responses_ptr" ); |
||||
__BEGIN__; |
||||
|
||||
int var_count = 0; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
var_count = values->cols; |
||||
|
||||
if ( response_idx < 0 || response_idx >= var_count ) |
||||
return 0; |
||||
if ( !response_out ) |
||||
response_out = cvCreateMatHeader( values->rows, 1, CV_32FC1 ); |
||||
else |
||||
cvInitMatHeader( response_out, values->rows, 1, CV_32FC1); |
||||
cvGetCol( values, response_out, response_idx ); |
||||
|
||||
__END__; |
||||
|
||||
return response_out; |
||||
} |
||||
|
||||
void CvMLData::set_train_test_split( const CvTrainTestSplit * spl) |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::set_division" ); |
||||
__BEGIN__; |
||||
|
||||
int sample_count = 0; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
|
||||
sample_count = values->rows; |
||||
|
||||
float train_sample_portion; |
||||
|
||||
if (spl->train_sample_part_mode == CV_COUNT) |
||||
{ |
||||
train_sample_count = spl->train_sample_part.count; |
||||
if (train_sample_count > sample_count) |
||||
CV_ERROR( CV_StsBadArg, "train samples count is not correct" ); |
||||
train_sample_count = train_sample_count<=0 ? sample_count : train_sample_count; |
||||
} |
||||
else // dtype.train_sample_part_mode == CV_PORTION
|
||||
{ |
||||
train_sample_portion = spl->train_sample_part.portion; |
||||
if ( train_sample_portion > 1) |
||||
CV_ERROR( CV_StsBadArg, "train samples count is not correct" ); |
||||
train_sample_portion = train_sample_portion <= FLT_EPSILON || |
||||
1 - train_sample_portion <= FLT_EPSILON ? 1 : train_sample_portion; |
||||
train_sample_count = std::max(1, cvFloor( train_sample_portion * sample_count )); |
||||
} |
||||
|
||||
if ( train_sample_count == sample_count ) |
||||
{ |
||||
free_train_test_idx(); |
||||
return; |
||||
} |
||||
|
||||
if ( train_sample_idx && train_sample_idx->cols != train_sample_count ) |
||||
free_train_test_idx(); |
||||
|
||||
if ( !sample_idx) |
||||
{ |
||||
int test_sample_count = sample_count- train_sample_count; |
||||
sample_idx = (int*)cvAlloc( sample_count * sizeof(sample_idx[0]) ); |
||||
for (int i = 0; i < sample_count; i++ ) |
||||
sample_idx[i] = i; |
||||
train_sample_idx = cvCreateMatHeader( 1, train_sample_count, CV_32SC1 ); |
||||
*train_sample_idx = cvMat( 1, train_sample_count, CV_32SC1, &sample_idx[0] ); |
||||
|
||||
CV_Assert(test_sample_count > 0); |
||||
test_sample_idx = cvCreateMatHeader( 1, test_sample_count, CV_32SC1 ); |
||||
*test_sample_idx = cvMat( 1, test_sample_count, CV_32SC1, &sample_idx[train_sample_count] ); |
||||
} |
||||
|
||||
mix = spl->mix; |
||||
if ( mix ) |
||||
mix_train_and_test_idx(); |
||||
|
||||
__END__; |
||||
} |
||||
|
||||
const CvMat* CvMLData::get_train_sample_idx() const |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::get_train_sample_idx" ); |
||||
__BEGIN__; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
__END__; |
||||
|
||||
return train_sample_idx; |
||||
} |
||||
|
||||
const CvMat* CvMLData::get_test_sample_idx() const |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::get_test_sample_idx" ); |
||||
__BEGIN__; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
__END__; |
||||
|
||||
return test_sample_idx; |
||||
} |
||||
|
||||
void CvMLData::mix_train_and_test_idx() |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::mix_train_and_test_idx" ); |
||||
__BEGIN__; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
__END__; |
||||
|
||||
if ( !sample_idx) |
||||
return; |
||||
|
||||
if ( train_sample_count > 0 && train_sample_count < values->rows ) |
||||
{ |
||||
int n = values->rows; |
||||
for (int i = 0; i < n; i++) |
||||
{ |
||||
int a = (*rng)(n); |
||||
int b = (*rng)(n); |
||||
int t; |
||||
CV_SWAP( sample_idx[a], sample_idx[b], t ); |
||||
} |
||||
} |
||||
} |
||||
|
||||
const CvMat* CvMLData::get_var_idx() |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::get_var_idx" ); |
||||
__BEGIN__; |
||||
|
||||
int avcount = 0; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
|
||||
assert( var_idx_mask ); |
||||
|
||||
avcount = cvFloor( cvNorm( var_idx_mask, 0, CV_L1 ) ); |
||||
int* vidx; |
||||
|
||||
if ( avcount == values->cols ) |
||||
return 0; |
||||
|
||||
if ( !var_idx_out || ( var_idx_out && var_idx_out->cols != avcount ) ) |
||||
{ |
||||
cvReleaseMat( &var_idx_out ); |
||||
var_idx_out = cvCreateMat( 1, avcount, CV_32SC1); |
||||
if ( response_idx >=0 ) |
||||
var_idx_mask->data.ptr[response_idx] = 0; |
||||
} |
||||
|
||||
vidx = var_idx_out->data.i; |
||||
|
||||
for(int i = 0; i < var_idx_mask->cols; i++) |
||||
if ( var_idx_mask->data.ptr[i] ) |
||||
{ |
||||
*vidx = i; |
||||
vidx++; |
||||
} |
||||
|
||||
__END__; |
||||
|
||||
return var_idx_out; |
||||
} |
||||
|
||||
void CvMLData::chahge_var_idx( int vi, bool state ) |
||||
{ |
||||
change_var_idx( vi, state ); |
||||
} |
||||
|
||||
void CvMLData::change_var_idx( int vi, bool state ) |
||||
{ |
||||
CV_FUNCNAME( "CvMLData::change_var_idx" ); |
||||
__BEGIN__; |
||||
|
||||
int var_count = 0; |
||||
|
||||
if ( !values ) |
||||
CV_ERROR( CV_StsInternal, "data is empty" ); |
||||
|
||||
var_count = values->cols; |
||||
|
||||
if ( vi < 0 || vi >= var_count) |
||||
CV_ERROR( CV_StsBadArg, "variable index is not correct" ); |
||||
|
||||
assert( var_idx_mask ); |
||||
var_idx_mask->data.ptr[vi] = state; |
||||
|
||||
__END__; |
||||
} |
||||
|
||||
/* End of file. */ |
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,376 @@ |
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
#ifndef __OPENCV_PRECOMP_H__ |
||||
#define __OPENCV_PRECOMP_H__ |
||||
|
||||
#include "opencv2/core.hpp" |
||||
#include "old_ml.hpp" |
||||
#include "opencv2/core/core_c.h" |
||||
#include "opencv2/core/utility.hpp" |
||||
|
||||
#include "opencv2/core/private.hpp" |
||||
|
||||
#include <assert.h> |
||||
#include <float.h> |
||||
#include <limits.h> |
||||
#include <math.h> |
||||
#include <stdlib.h> |
||||
#include <stdio.h> |
||||
#include <string.h> |
||||
#include <time.h> |
||||
|
||||
#define ML_IMPL CV_IMPL |
||||
#define __BEGIN__ __CV_BEGIN__ |
||||
#define __END__ __CV_END__ |
||||
#define EXIT __CV_EXIT__ |
||||
|
||||
#define CV_MAT_ELEM_FLAG( mat, type, comp, vect, tflag ) \ |
||||
(( tflag == CV_ROW_SAMPLE ) \
|
||||
? (CV_MAT_ELEM( mat, type, comp, vect )) \
|
||||
: (CV_MAT_ELEM( mat, type, vect, comp ))) |
||||
|
||||
/* Convert matrix to vector */ |
||||
#define ICV_MAT2VEC( mat, vdata, vstep, num ) \ |
||||
if( MIN( (mat).rows, (mat).cols ) != 1 ) \
|
||||
CV_ERROR( CV_StsBadArg, "" ); \
|
||||
(vdata) = ((mat).data.ptr); \
|
||||
if( (mat).rows == 1 ) \
|
||||
{ \
|
||||
(vstep) = CV_ELEM_SIZE( (mat).type ); \
|
||||
(num) = (mat).cols; \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
(vstep) = (mat).step; \
|
||||
(num) = (mat).rows; \
|
||||
} |
||||
|
||||
/* get raw data */ |
||||
#define ICV_RAWDATA( mat, flags, rdata, sstep, cstep, m, n ) \ |
||||
(rdata) = (mat).data.ptr; \
|
||||
if( CV_IS_ROW_SAMPLE( flags ) ) \
|
||||
{ \
|
||||
(sstep) = (mat).step; \
|
||||
(cstep) = CV_ELEM_SIZE( (mat).type ); \
|
||||
(m) = (mat).rows; \
|
||||
(n) = (mat).cols; \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
(cstep) = (mat).step; \
|
||||
(sstep) = CV_ELEM_SIZE( (mat).type ); \
|
||||
(n) = (mat).rows; \
|
||||
(m) = (mat).cols; \
|
||||
} |
||||
|
||||
#define ICV_IS_MAT_OF_TYPE( mat, mat_type) \ |
||||
(CV_IS_MAT( mat ) && CV_MAT_TYPE( mat->type ) == (mat_type) && \
|
||||
(mat)->cols > 0 && (mat)->rows > 0) |
||||
|
||||
/*
|
||||
uchar* data; int sstep, cstep; - trainData->data |
||||
uchar* classes; int clstep; int ncl;- trainClasses |
||||
uchar* tmask; int tmstep; int ntm; - typeMask |
||||
uchar* missed;int msstep, mcstep; -missedMeasurements... |
||||
int mm, mn; == m,n == size,dim |
||||
uchar* sidx;int sistep; - sampleIdx |
||||
uchar* cidx;int cistep; - compIdx |
||||
int k, l; == n,m == dim,size (length of cidx, sidx) |
||||
int m, n; == size,dim |
||||
*/ |
||||
#define ICV_DECLARE_TRAIN_ARGS() \ |
||||
uchar* data; \
|
||||
int sstep, cstep; \
|
||||
uchar* classes; \
|
||||
int clstep; \
|
||||
int ncl; \
|
||||
uchar* tmask; \
|
||||
int tmstep; \
|
||||
int ntm; \
|
||||
uchar* missed; \
|
||||
int msstep, mcstep; \
|
||||
int mm, mn; \
|
||||
uchar* sidx; \
|
||||
int sistep; \
|
||||
uchar* cidx; \
|
||||
int cistep; \
|
||||
int k, l; \
|
||||
int m, n; \
|
||||
\
|
||||
data = classes = tmask = missed = sidx = cidx = NULL; \
|
||||
sstep = cstep = clstep = ncl = tmstep = ntm = msstep = mcstep = mm = mn = 0; \
|
||||
sistep = cistep = k = l = m = n = 0; |
||||
|
||||
#define ICV_TRAIN_DATA_REQUIRED( param, flags ) \ |
||||
if( !ICV_IS_MAT_OF_TYPE( (param), CV_32FC1 ) ) \
|
||||
{ \
|
||||
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
ICV_RAWDATA( *(param), (flags), data, sstep, cstep, m, n ); \
|
||||
k = n; \
|
||||
l = m; \
|
||||
} |
||||
|
||||
#define ICV_TRAIN_CLASSES_REQUIRED( param ) \ |
||||
if( !ICV_IS_MAT_OF_TYPE( (param), CV_32FC1 ) ) \
|
||||
{ \
|
||||
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
ICV_MAT2VEC( *(param), classes, clstep, ncl ); \
|
||||
if( m != ncl ) \
|
||||
{ \
|
||||
CV_ERROR( CV_StsBadArg, "Unmatched sizes" ); \
|
||||
} \
|
||||
} |
||||
|
||||
#define ICV_ARG_NULL( param ) \ |
||||
if( (param) != NULL ) \
|
||||
{ \
|
||||
CV_ERROR( CV_StsBadArg, #param " parameter must be NULL" ); \
|
||||
} |
||||
|
||||
#define ICV_MISSED_MEASUREMENTS_OPTIONAL( param, flags ) \ |
||||
if( param ) \
|
||||
{ \
|
||||
if( !ICV_IS_MAT_OF_TYPE( param, CV_8UC1 ) ) \
|
||||
{ \
|
||||
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
ICV_RAWDATA( *(param), (flags), missed, msstep, mcstep, mm, mn ); \
|
||||
if( mm != m || mn != n ) \
|
||||
{ \
|
||||
CV_ERROR( CV_StsBadArg, "Unmatched sizes" ); \
|
||||
} \
|
||||
} \
|
||||
} |
||||
|
||||
#define ICV_COMP_IDX_OPTIONAL( param ) \ |
||||
if( param ) \
|
||||
{ \
|
||||
if( !ICV_IS_MAT_OF_TYPE( param, CV_32SC1 ) ) \
|
||||
{ \
|
||||
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
ICV_MAT2VEC( *(param), cidx, cistep, k ); \
|
||||
if( k > n ) \
|
||||
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
|
||||
} \
|
||||
} |
||||
|
||||
#define ICV_SAMPLE_IDX_OPTIONAL( param ) \ |
||||
if( param ) \
|
||||
{ \
|
||||
if( !ICV_IS_MAT_OF_TYPE( param, CV_32SC1 ) ) \
|
||||
{ \
|
||||
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
ICV_MAT2VEC( *sampleIdx, sidx, sistep, l ); \
|
||||
if( l > m ) \
|
||||
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
|
||||
} \
|
||||
} |
||||
|
||||
/****************************************************************************************/ |
||||
#define ICV_CONVERT_FLOAT_ARRAY_TO_MATRICE( array, matrice ) \ |
||||
{ \
|
||||
CvMat a, b; \
|
||||
int dims = (matrice)->cols; \
|
||||
int nsamples = (matrice)->rows; \
|
||||
int type = CV_MAT_TYPE((matrice)->type); \
|
||||
int i, offset = dims; \
|
||||
\
|
||||
CV_ASSERT( type == CV_32FC1 || type == CV_64FC1 ); \
|
||||
offset *= ((type == CV_32FC1) ? sizeof(float) : sizeof(double));\
|
||||
\
|
||||
b = cvMat( 1, dims, CV_32FC1 ); \
|
||||
cvGetRow( matrice, &a, 0 ); \
|
||||
for( i = 0; i < nsamples; i++, a.data.ptr += offset ) \
|
||||
{ \
|
||||
b.data.fl = (float*)array[i]; \
|
||||
CV_CALL( cvConvert( &b, &a ) ); \
|
||||
} \
|
||||
} |
||||
|
||||
/****************************************************************************************\
|
||||
* Auxiliary functions declarations * |
||||
\****************************************************************************************/ |
||||
|
||||
/* Generates a set of classes centers in quantity <num_of_clusters> that are generated as
|
||||
uniform random vectors in parallelepiped, where <data> is concentrated. Vectors in |
||||
<data> should have horizontal orientation. If <centers> != NULL, the function doesn't |
||||
allocate any memory and stores generated centers in <centers>, returns <centers>. |
||||
If <centers> == NULL, the function allocates memory and creates the matrice. Centers |
||||
are supposed to be oriented horizontally. */ |
||||
CvMat* icvGenerateRandomClusterCenters( int seed, |
||||
const CvMat* data, |
||||
int num_of_clusters, |
||||
CvMat* centers CV_DEFAULT(0)); |
||||
|
||||
/* Fills the <labels> using <probs> by choosing the maximal probability. Outliers are
|
||||
fixed by <oulier_tresh> and have cluster label (-1). Function also controls that there |
||||
weren't "empty" clusters by filling empty clusters with the maximal probability vector. |
||||
If probs_sums != NULL, filles it with the sums of probabilities for each sample (it is |
||||
useful for normalizing probabilities' matrice of FCM) */ |
||||
void icvFindClusterLabels( const CvMat* probs, float outlier_thresh, float r, |
||||
const CvMat* labels ); |
||||
|
||||
typedef struct CvSparseVecElem32f |
||||
{ |
||||
int idx; |
||||
float val; |
||||
} |
||||
CvSparseVecElem32f; |
||||
|
||||
/* Prepare training data and related parameters */ |
||||
#define CV_TRAIN_STATMODEL_DEFRAGMENT_TRAIN_DATA 1 |
||||
#define CV_TRAIN_STATMODEL_SAMPLES_AS_ROWS 2 |
||||
#define CV_TRAIN_STATMODEL_SAMPLES_AS_COLUMNS 4 |
||||
#define CV_TRAIN_STATMODEL_CATEGORICAL_RESPONSE 8 |
||||
#define CV_TRAIN_STATMODEL_ORDERED_RESPONSE 16 |
||||
#define CV_TRAIN_STATMODEL_RESPONSES_ON_OUTPUT 32 |
||||
#define CV_TRAIN_STATMODEL_ALWAYS_COPY_TRAIN_DATA 64 |
||||
#define CV_TRAIN_STATMODEL_SPARSE_AS_SPARSE 128 |
||||
|
||||
int |
||||
cvPrepareTrainData( const char* /*funcname*/, |
||||
const CvMat* train_data, int tflag, |
||||
const CvMat* responses, int response_type, |
||||
const CvMat* var_idx, |
||||
const CvMat* sample_idx, |
||||
bool always_copy_data, |
||||
const float*** out_train_samples, |
||||
int* _sample_count, |
||||
int* _var_count, |
||||
int* _var_all, |
||||
CvMat** out_responses, |
||||
CvMat** out_response_map, |
||||
CvMat** out_var_idx, |
||||
CvMat** out_sample_idx=0 ); |
||||
|
||||
void |
||||
cvSortSamplesByClasses( const float** samples, const CvMat* classes, |
||||
int* class_ranges, const uchar** mask CV_DEFAULT(0) ); |
||||
|
||||
void |
||||
cvCombineResponseMaps (CvMat* _responses, |
||||
const CvMat* old_response_map, |
||||
CvMat* new_response_map, |
||||
CvMat** out_response_map); |
||||
|
||||
void |
||||
cvPreparePredictData( const CvArr* sample, int dims_all, const CvMat* comp_idx, |
||||
int class_count, const CvMat* prob, float** row_sample, |
||||
int as_sparse CV_DEFAULT(0) ); |
||||
|
||||
/* copies clustering [or batch "predict"] results
|
||||
(labels and/or centers and/or probs) back to the output arrays */ |
||||
void |
||||
cvWritebackLabels( const CvMat* labels, CvMat* dst_labels, |
||||
const CvMat* centers, CvMat* dst_centers, |
||||
const CvMat* probs, CvMat* dst_probs, |
||||
const CvMat* sample_idx, int samples_all, |
||||
const CvMat* comp_idx, int dims_all ); |
||||
#define cvWritebackResponses cvWritebackLabels |
||||
|
||||
#define XML_FIELD_NAME "_name" |
||||
CvFileNode* icvFileNodeGetChild(CvFileNode* father, const char* name); |
||||
CvFileNode* icvFileNodeGetChildArrayElem(CvFileNode* father, const char* name,int index); |
||||
CvFileNode* icvFileNodeGetNext(CvFileNode* n, const char* name); |
||||
|
||||
|
||||
void cvCheckTrainData( const CvMat* train_data, int tflag, |
||||
const CvMat* missing_mask, |
||||
int* var_all, int* sample_all ); |
||||
|
||||
CvMat* cvPreprocessIndexArray( const CvMat* idx_arr, int data_arr_size, bool check_for_duplicates=false ); |
||||
|
||||
CvMat* cvPreprocessVarType( const CvMat* type_mask, const CvMat* var_idx, |
||||
int var_all, int* response_type ); |
||||
|
||||
CvMat* cvPreprocessOrderedResponses( const CvMat* responses, |
||||
const CvMat* sample_idx, int sample_all ); |
||||
|
||||
CvMat* cvPreprocessCategoricalResponses( const CvMat* responses, |
||||
const CvMat* sample_idx, int sample_all, |
||||
CvMat** out_response_map, CvMat** class_counts=0 ); |
||||
|
||||
const float** cvGetTrainSamples( const CvMat* train_data, int tflag, |
||||
const CvMat* var_idx, const CvMat* sample_idx, |
||||
int* _var_count, int* _sample_count, |
||||
bool always_copy_data=false ); |
||||
|
||||
namespace cv |
||||
{ |
||||
struct DTreeBestSplitFinder |
||||
{ |
||||
DTreeBestSplitFinder(){ splitSize = 0, tree = 0; node = 0; } |
||||
DTreeBestSplitFinder( CvDTree* _tree, CvDTreeNode* _node); |
||||
DTreeBestSplitFinder( const DTreeBestSplitFinder& finder, Split ); |
||||
virtual ~DTreeBestSplitFinder() {} |
||||
virtual void operator()(const BlockedRange& range); |
||||
void join( DTreeBestSplitFinder& rhs ); |
||||
Ptr<CvDTreeSplit> bestSplit; |
||||
Ptr<CvDTreeSplit> split; |
||||
int splitSize; |
||||
CvDTree* tree; |
||||
CvDTreeNode* node; |
||||
}; |
||||
|
||||
struct ForestTreeBestSplitFinder : DTreeBestSplitFinder |
||||
{ |
||||
ForestTreeBestSplitFinder() : DTreeBestSplitFinder() {} |
||||
ForestTreeBestSplitFinder( CvForestTree* _tree, CvDTreeNode* _node ); |
||||
ForestTreeBestSplitFinder( const ForestTreeBestSplitFinder& finder, Split ); |
||||
virtual void operator()(const BlockedRange& range); |
||||
}; |
||||
} |
||||
|
||||
#endif /* __ML_H__ */ |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,322 +0,0 @@ |
||||
#include "opencv2/core/core_c.h" |
||||
#include "opencv2/ml/ml.hpp" |
||||
#include <stdio.h> |
||||
|
||||
static void help() |
||||
{ |
||||
printf("\nThis program demonstrated the use of OpenCV's decision tree function for learning and predicting data\n" |
||||
"Usage :\n" |
||||
"./mushroom <path to agaricus-lepiota.data>\n" |
||||
"\n" |
||||
"The sample demonstrates how to build a decision tree for classifying mushrooms.\n" |
||||
"It uses the sample base agaricus-lepiota.data from UCI Repository, here is the link:\n" |
||||
"\n" |
||||
"Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998).\n" |
||||
"UCI Repository of machine learning databases\n" |
||||
"[http://www.ics.uci.edu/~mlearn/MLRepository.html].\n" |
||||
"Irvine, CA: University of California, Department of Information and Computer Science.\n" |
||||
"\n" |
||||
"// loads the mushroom database, which is a text file, containing\n" |
||||
"// one training sample per row, all the input variables and the output variable are categorical,\n" |
||||
"// the values are encoded by characters.\n\n"); |
||||
} |
||||
|
||||
static int mushroom_read_database( const char* filename, CvMat** data, CvMat** missing, CvMat** responses ) |
||||
{ |
||||
const int M = 1024; |
||||
FILE* f = fopen( filename, "rt" ); |
||||
CvMemStorage* storage; |
||||
CvSeq* seq; |
||||
char buf[M+2], *ptr; |
||||
float* el_ptr; |
||||
CvSeqReader reader; |
||||
int i, j, var_count = 0; |
||||
|
||||
if( !f ) |
||||
return 0; |
||||
|
||||
// read the first line and determine the number of variables
|
||||
if( !fgets( buf, M, f )) |
||||
{ |
||||
fclose(f); |
||||
return 0; |
||||
} |
||||
|
||||
for( ptr = buf; *ptr != '\0'; ptr++ ) |
||||
var_count += *ptr == ','; |
||||
assert( ptr - buf == (var_count+1)*2 ); |
||||
|
||||
// create temporary memory storage to store the whole database
|
||||
el_ptr = new float[var_count+1]; |
||||
storage = cvCreateMemStorage(); |
||||
seq = cvCreateSeq( 0, sizeof(*seq), (var_count+1)*sizeof(float), storage ); |
||||
|
||||
for(;;) |
||||
{ |
||||
for( i = 0; i <= var_count; i++ ) |
||||
{ |
||||
int c = buf[i*2]; |
||||
el_ptr[i] = c == '?' ? -1.f : (float)c; |
||||
} |
||||
if( i != var_count+1 ) |
||||
break; |
||||
cvSeqPush( seq, el_ptr ); |
||||
if( !fgets( buf, M, f ) || !strchr( buf, ',' ) ) |
||||
break; |
||||
} |
||||
fclose(f); |
||||
|
||||
// allocate the output matrices and copy the base there
|
||||
*data = cvCreateMat( seq->total, var_count, CV_32F ); |
||||
*missing = cvCreateMat( seq->total, var_count, CV_8U ); |
||||
*responses = cvCreateMat( seq->total, 1, CV_32F ); |
||||
|
||||
cvStartReadSeq( seq, &reader ); |
||||
|
||||
for( i = 0; i < seq->total; i++ ) |
||||
{ |
||||
const float* sdata = (float*)reader.ptr + 1; |
||||
float* ddata = data[0]->data.fl + var_count*i; |
||||
float* dr = responses[0]->data.fl + i; |
||||
uchar* dm = missing[0]->data.ptr + var_count*i; |
||||
|
||||
for( j = 0; j < var_count; j++ ) |
||||
{ |
||||
ddata[j] = sdata[j]; |
||||
dm[j] = sdata[j] < 0; |
||||
} |
||||
*dr = sdata[-1]; |
||||
CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); |
||||
} |
||||
|
||||
cvReleaseMemStorage( &storage ); |
||||
delete [] el_ptr; |
||||
return 1; |
||||
} |
||||
|
||||
|
||||
static CvDTree* mushroom_create_dtree( const CvMat* data, const CvMat* missing, |
||||
const CvMat* responses, float p_weight ) |
||||
{ |
||||
CvDTree* dtree; |
||||
CvMat* var_type; |
||||
int i, hr1 = 0, hr2 = 0, p_total = 0; |
||||
float priors[] = { 1, p_weight }; |
||||
|
||||
var_type = cvCreateMat( data->cols + 1, 1, CV_8U ); |
||||
cvSet( var_type, cvScalarAll(CV_VAR_CATEGORICAL) ); // all the variables are categorical
|
||||
|
||||
dtree = new CvDTree; |
||||
|
||||
dtree->train( data, CV_ROW_SAMPLE, responses, 0, 0, var_type, missing, |
||||
CvDTreeParams( 8, // max depth
|
||||
10, // min sample count
|
||||
0, // regression accuracy: N/A here
|
||||
true, // compute surrogate split, as we have missing data
|
||||
15, // max number of categories (use sub-optimal algorithm for larger numbers)
|
||||
10, // the number of cross-validation folds
|
||||
true, // use 1SE rule => smaller tree
|
||||
true, // throw away the pruned tree branches
|
||||
priors // the array of priors, the bigger p_weight, the more attention
|
||||
// to the poisonous mushrooms
|
||||
// (a mushroom will be judjed to be poisonous with bigger chance)
|
||||
)); |
||||
|
||||
// compute hit-rate on the training database, demonstrates predict usage.
|
||||
for( i = 0; i < data->rows; i++ ) |
||||
{ |
||||
CvMat sample, mask; |
||||
cvGetRow( data, &sample, i ); |
||||
cvGetRow( missing, &mask, i ); |
||||
double r = dtree->predict( &sample, &mask )->value; |
||||
int d = fabs(r - responses->data.fl[i]) >= FLT_EPSILON; |
||||
if( d ) |
||||
{ |
||||
if( r != 'p' ) |
||||
hr1++; |
||||
else |
||||
hr2++; |
||||
} |
||||
p_total += responses->data.fl[i] == 'p'; |
||||
} |
||||
|
||||
printf( "Results on the training database:\n" |
||||
"\tPoisonous mushrooms mis-predicted: %d (%g%%)\n" |
||||
"\tFalse-alarms: %d (%g%%)\n", hr1, (double)hr1*100/p_total, |
||||
hr2, (double)hr2*100/(data->rows - p_total) ); |
||||
|
||||
cvReleaseMat( &var_type ); |
||||
|
||||
return dtree; |
||||
} |
||||
|
||||
|
||||
static const char* var_desc[] = |
||||
{ |
||||
"cap shape (bell=b,conical=c,convex=x,flat=f)", |
||||
"cap surface (fibrous=f,grooves=g,scaly=y,smooth=s)", |
||||
"cap color (brown=n,buff=b,cinnamon=c,gray=g,green=r,\n\tpink=p,purple=u,red=e,white=w,yellow=y)", |
||||
"bruises? (bruises=t,no=f)", |
||||
"odor (almond=a,anise=l,creosote=c,fishy=y,foul=f,\n\tmusty=m,none=n,pungent=p,spicy=s)", |
||||
"gill attachment (attached=a,descending=d,free=f,notched=n)", |
||||
"gill spacing (close=c,crowded=w,distant=d)", |
||||
"gill size (broad=b,narrow=n)", |
||||
"gill color (black=k,brown=n,buff=b,chocolate=h,gray=g,\n\tgreen=r,orange=o,pink=p,purple=u,red=e,white=w,yellow=y)", |
||||
"stalk shape (enlarging=e,tapering=t)", |
||||
"stalk root (bulbous=b,club=c,cup=u,equal=e,rhizomorphs=z,rooted=r)", |
||||
"stalk surface above ring (ibrous=f,scaly=y,silky=k,smooth=s)", |
||||
"stalk surface below ring (ibrous=f,scaly=y,silky=k,smooth=s)", |
||||
"stalk color above ring (brown=n,buff=b,cinnamon=c,gray=g,orange=o,\n\tpink=p,red=e,white=w,yellow=y)", |
||||
"stalk color below ring (brown=n,buff=b,cinnamon=c,gray=g,orange=o,\n\tpink=p,red=e,white=w,yellow=y)", |
||||
"veil type (partial=p,universal=u)", |
||||
"veil color (brown=n,orange=o,white=w,yellow=y)", |
||||
"ring number (none=n,one=o,two=t)", |
||||
"ring type (cobwebby=c,evanescent=e,flaring=f,large=l,\n\tnone=n,pendant=p,sheathing=s,zone=z)", |
||||
"spore print color (black=k,brown=n,buff=b,chocolate=h,green=r,\n\torange=o,purple=u,white=w,yellow=y)", |
||||
"population (abundant=a,clustered=c,numerous=n,\n\tscattered=s,several=v,solitary=y)", |
||||
"habitat (grasses=g,leaves=l,meadows=m,paths=p\n\turban=u,waste=w,woods=d)", |
||||
0 |
||||
}; |
||||
|
||||
|
||||
static void print_variable_importance( CvDTree* dtree ) |
||||
{ |
||||
const CvMat* var_importance = dtree->get_var_importance(); |
||||
int i; |
||||
char input[1000]; |
||||
|
||||
if( !var_importance ) |
||||
{ |
||||
printf( "Error: Variable importance can not be retrieved\n" ); |
||||
return; |
||||
} |
||||
|
||||
printf( "Print variable importance information? (y/n) " ); |
||||
int values_read = scanf( "%1s", input ); |
||||
CV_Assert(values_read == 1); |
||||
|
||||
if( input[0] != 'y' && input[0] != 'Y' ) |
||||
return; |
||||
|
||||
for( i = 0; i < var_importance->cols*var_importance->rows; i++ ) |
||||
{ |
||||
double val = var_importance->data.db[i]; |
||||
char buf[100]; |
||||
int len = (int)(strchr( var_desc[i], '(' ) - var_desc[i] - 1); |
||||
strncpy( buf, var_desc[i], len ); |
||||
buf[len] = '\0'; |
||||
printf( "%s", buf ); |
||||
printf( ": %g%%\n", val*100. ); |
||||
} |
||||
} |
||||
|
||||
static void interactive_classification( CvDTree* dtree ) |
||||
{ |
||||
char input[1000]; |
||||
const CvDTreeNode* root; |
||||
CvDTreeTrainData* data; |
||||
|
||||
if( !dtree ) |
||||
return; |
||||
|
||||
root = dtree->get_root(); |
||||
data = dtree->get_data(); |
||||
|
||||
for(;;) |
||||
{ |
||||
const CvDTreeNode* node; |
||||
|
||||
printf( "Start/Proceed with interactive mushroom classification (y/n): " ); |
||||
int values_read = scanf( "%1s", input ); |
||||
CV_Assert(values_read == 1); |
||||
|
||||
if( input[0] != 'y' && input[0] != 'Y' ) |
||||
break; |
||||
printf( "Enter 1-letter answers, '?' for missing/unknown value...\n" ); |
||||
|
||||
// custom version of predict
|
||||
node = root; |
||||
for(;;) |
||||
{ |
||||
CvDTreeSplit* split = node->split; |
||||
int dir = 0; |
||||
|
||||
if( !node->left || node->Tn <= dtree->get_pruned_tree_idx() || !node->split ) |
||||
break; |
||||
|
||||
for( ; split != 0; ) |
||||
{ |
||||
int vi = split->var_idx, j; |
||||
int count = data->cat_count->data.i[vi]; |
||||
const int* map = data->cat_map->data.i + data->cat_ofs->data.i[vi]; |
||||
|
||||
printf( "%s: ", var_desc[vi] ); |
||||
values_read = scanf( "%1s", input ); |
||||
CV_Assert(values_read == 1); |
||||
|
||||
if( input[0] == '?' ) |
||||
{ |
||||
split = split->next; |
||||
continue; |
||||
} |
||||
|
||||
// convert the input character to the normalized value of the variable
|
||||
for( j = 0; j < count; j++ ) |
||||
if( map[j] == input[0] ) |
||||
break; |
||||
if( j < count ) |
||||
{ |
||||
dir = (split->subset[j>>5] & (1 << (j&31))) ? -1 : 1; |
||||
if( split->inversed ) |
||||
dir = -dir; |
||||
break; |
||||
} |
||||
else |
||||
printf( "Error: unrecognized value\n" ); |
||||
} |
||||
|
||||
if( !dir ) |
||||
{ |
||||
printf( "Impossible to classify the sample\n"); |
||||
node = 0; |
||||
break; |
||||
} |
||||
node = dir < 0 ? node->left : node->right; |
||||
} |
||||
|
||||
if( node ) |
||||
printf( "Prediction result: the mushroom is %s\n", |
||||
node->class_idx == 0 ? "EDIBLE" : "POISONOUS" ); |
||||
printf( "\n-----------------------------\n" ); |
||||
} |
||||
} |
||||
|
||||
|
||||
int main( int argc, char** argv ) |
||||
{ |
||||
CvMat *data = 0, *missing = 0, *responses = 0; |
||||
CvDTree* dtree; |
||||
const char* base_path = argc >= 2 ? argv[1] : "agaricus-lepiota.data"; |
||||
|
||||
help(); |
||||
|
||||
if( !mushroom_read_database( base_path, &data, &missing, &responses ) ) |
||||
{ |
||||
printf( "\nUnable to load the training database\n\n"); |
||||
help(); |
||||
return -1; |
||||
} |
||||
|
||||
dtree = mushroom_create_dtree( data, missing, responses, |
||||
10 // poisonous mushrooms will have 10x higher weight in the decision tree
|
||||
); |
||||
cvReleaseMat( &data ); |
||||
cvReleaseMat( &missing ); |
||||
cvReleaseMat( &responses ); |
||||
|
||||
print_variable_importance( dtree ); |
||||
interactive_classification( dtree ); |
||||
delete dtree; |
||||
|
||||
return 0; |
||||
} |
Loading…
Reference in new issue