FeatureMatrixT.tcc 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. /**
  2. * @file FeatureMatrixT.tcc
  3. * @brief A feature matrix, storing (sparse) features sorted per dimension (Implementation)
  4. * @author Alexander Freytag
  5. * @date 07-12-2011 (dd-mm-yyyy)
  6. */
  7. // #ifndef FEATUREMATRIX_TCC
  8. // #define FEATUREMATRIX_TCC
  9. // gp-hik-core includes
  10. #include "FeatureMatrixT.h"
  11. namespace NICE {
  12. //------------------------------------------------------
  13. // several constructors and destructors
  14. //------------------------------------------------------
  15. // Default constructor
  16. template <typename T>
  17. FeatureMatrixT<T>::FeatureMatrixT()
  18. {
  19. this->ui_n = 0;
  20. this->ui_d = 0;
  21. this->features.clear();
  22. this->b_verbose = false;
  23. this->b_debug = false;
  24. }
  25. // Recommended constructor
  26. template <typename T>
  27. FeatureMatrixT<T>::FeatureMatrixT(const std::vector<std::vector<T> > & _features,
  28. const uint & _dim
  29. )
  30. {
  31. this->ui_n = 0;
  32. if (_dim < 0)
  33. this->ui_d = (*_features.begin()).size();
  34. else
  35. this->ui_d = _dim;
  36. for (typename std::vector<std::vector<T> >::const_iterator it = _features.begin(); it != _features.end(); it++)
  37. {
  38. add_feature(*it);
  39. }
  40. this->b_verbose = false;
  41. this->b_debug = false;
  42. }
  43. //Constructor reading data from a vector of sparse vector pointers
  44. template <typename T>
  45. FeatureMatrixT<T>::
  46. FeatureMatrixT(const std::vector< const NICE::SparseVector * > & _X,
  47. const bool _dimensionsOverExamples,
  48. const uint & _dim
  49. )
  50. {
  51. this->features.clear();
  52. // resize our data structure
  53. //FIXME adapt these security checks to uint ...
  54. if (_dim >= 0) //did the user specified the number of dimensions?
  55. set_d( _dim );
  56. else //dimensions not specified by users
  57. {
  58. if (_dimensionsOverExamples) //do we have dim x examples ?
  59. {
  60. set_d( _X.size());
  61. }
  62. else //we have examples x dimes (as usually done)
  63. {
  64. if ( _X.size() > 0) //and have at least one example
  65. set_d( _X[0]->getDim() );
  66. else //no example, so set the dim to 0, since we have no idea at all
  67. {
  68. set_d(0);
  69. }
  70. }
  71. }
  72. // set number of examples n
  73. if ( this->ui_d > 0 )
  74. {
  75. if (_dimensionsOverExamples) //do we have dim x examples ?
  76. this->ui_n = _X[0]->getDim(); //NOTE Pay attention: we assume, that this number is set!
  77. else //we have examples x dimes (as usually done)
  78. this->ui_n = _X.size();
  79. }
  80. // insert all values
  81. if (_dimensionsOverExamples) //do we have dim x examples ?
  82. {
  83. for (uint dim = 0; dim < this->ui_d; dim++)
  84. {
  85. this->features[dim].insert( _X[dim] );
  86. }
  87. }
  88. else //we have examples x dimes (as usually done)
  89. {
  90. //loop over every example to add its content
  91. for (uint nr = 0; nr < this->ui_n; nr++)
  92. {
  93. //loop over every dimension to add the specific value to the corresponding SortedVectorSparse
  94. for (NICE::SparseVector::const_iterator elemIt = _X[nr]->begin(); elemIt != _X[nr]->end(); elemIt++)
  95. {
  96. //elemIt->first: dim, elemIt->second: value
  97. this->features[elemIt->first].insert( (T) elemIt->second, nr);
  98. }//for non-zero-values of the feature
  99. }//for every new feature
  100. }//if dimOverEx
  101. //set n for the internal data structure SortedVectorSparse
  102. for (typename std::vector<NICE::SortedVectorSparse<T> >::iterator it = this->features.begin(); it != this->features.end(); it++)
  103. (*it).setN( this->ui_n );
  104. }
  105. #ifdef NICE_USELIB_MATIO
  106. //Constructor reading data from matlab-files
  107. template <typename T>
  108. FeatureMatrixT<T>::
  109. FeatureMatrixT(const sparse_t & _features,
  110. const uint & _dim
  111. )
  112. {
  113. if (_dim < 0)
  114. set_d( _features.njc -1 );
  115. else
  116. set_d( _dim );
  117. uint nMax(0);
  118. for ( uint i = 0; i < _features.njc-1; i++ ) //walk over dimensions
  119. {
  120. for ( uint j = _features.jc[i]; j < _features.jc[i+1] && j < _features.ndata; j++ ) //walk over single features, which are sparsely represented
  121. {
  122. this->features[i].insert(((T*)_features.data)[j], _features.ir[ j]);
  123. if ((_features.ir[ j])>nMax)
  124. nMax = _features.ir[ j];
  125. }
  126. }
  127. for (typename std::vector<NICE::SortedVectorSparse<T> >::iterator it = this->features.begin(); it != this->features.end(); it++)
  128. {
  129. (*it).setN(nMax+1);
  130. }
  131. this->ui_n = nMax+1;
  132. this->b_verbose = false;
  133. }
  134. //Constructor reading data from matlab-files
  135. template <typename T>
  136. FeatureMatrixT<T>::
  137. FeatureMatrixT(const sparse_t & _features,
  138. const std::map<uint, uint> & _examples,
  139. const uint & _dim)
  140. {
  141. if (_dim < 0)
  142. set_d(_features.njc -1);
  143. else
  144. set_d(_dim);
  145. uint nMax(0);
  146. for ( uint i = 0; i < _features.njc-1; i++ ) //walk over dimensions
  147. {
  148. for ( uint j = _features.jc[i]; j < _features.jc[i+1] && j < _features.ndata; j++ ) //walk over single features, which are sparsely represented
  149. {
  150. uint example_index = _features.ir[ j];
  151. std::map<uint, uint>::const_iterator it = examples.find(example_index);
  152. if ( it != examples.end() ) {
  153. this->features[i].insert(((T*)_features.data)[j], it->second /* new index */);
  154. if (it->second > nMax)
  155. nMax = it->second;
  156. }
  157. }
  158. }
  159. for (typename std::vector<NICE::SortedVectorSparse<T> >::iterator it = this->features.begin(); it != this->features.end(); it++)
  160. (*it).setN(nMax+1);
  161. this->ui_n = nMax+1;
  162. this->b_verbose = false;
  163. }
  164. #endif
  165. // Default destructor
  166. template <typename T>
  167. FeatureMatrixT<T>::~FeatureMatrixT()
  168. {
  169. }
  170. //------------------------------------------------------
  171. // several get and set methods including access operators
  172. //------------------------------------------------------
  173. // Get number of examples
  174. template <typename T>
  175. uint FeatureMatrixT<T>::get_n() const
  176. {
  177. return this->ui_n;
  178. }
  179. // Get number of dimensions
  180. template <typename T>
  181. uint FeatureMatrixT<T>::get_d() const
  182. {
  183. return this->ui_d;
  184. }
  185. // Sets the given dimension and re-sizes internal data structure. WARNING: this will completely remove your current data!
  186. template <typename T>
  187. void FeatureMatrixT<T>::set_d(const uint & _d)
  188. {
  189. this->ui_d = _d;
  190. this->features.resize( this->ui_d );
  191. }
  192. template <typename T>
  193. void FeatureMatrixT<T>::setVerbose( const bool & _verbose)
  194. {
  195. this->b_verbose = _verbose;
  196. }
  197. template <typename T>
  198. bool FeatureMatrixT<T>::getVerbose( ) const
  199. {
  200. return this->b_verbose;
  201. }
  202. template <typename T>
  203. void FeatureMatrixT<T>::setDebug( const bool & _debug)
  204. {
  205. this->b_debug = _debug;
  206. }
  207. template <typename T>
  208. bool FeatureMatrixT<T>::getDebug( ) const
  209. {
  210. return this->b_debug;
  211. }
  212. // Matrix-like operator for element access, performs validity check
  213. template <typename T>
  214. inline T FeatureMatrixT<T>::operator()(const uint _row,
  215. const uint _col
  216. ) const
  217. {
  218. if ( (_row < 0) || (_col < 0) || (_row > this->ui_d) || (_col > this->ui_n) )
  219. {
  220. fthrow(Exception, "FeatureMatrixT: out of bounds");
  221. }
  222. else
  223. return ( this->features[_row]).access(_col);
  224. }
  225. template<class T>
  226. inline bool
  227. FeatureMatrixT<T>::operator==(const FeatureMatrixT<T> & _F) const
  228. {
  229. if ( ( this->get_n() != _F.get_n()) || (this->get_d() != _F.get_d()) )
  230. {
  231. fthrow(Exception, "FeatureMatrixT<T>::operator== : (n != F.get_n()) || (d != F.get_d()) -- number of dimensions does not fit");
  232. }
  233. else if ((this->ui_n == 0) || (this->ui_d == 0))
  234. {
  235. return true;
  236. }
  237. for (uint i = 0; i < this->ui_d; i++)
  238. {
  239. for (uint j = 0; j < this->ui_n; j++)
  240. {
  241. // FIXME: it would be more efficient if we compare SortedVectorSparse objects here
  242. if(!((*this)(i,j) == _F(i,j)))
  243. return false;
  244. }
  245. }
  246. return true;
  247. }
  248. template<class T>
  249. inline bool
  250. FeatureMatrixT<T>::operator!=(const FeatureMatrixT<T> & _F) const
  251. {
  252. if ( ( (*this).get_n() != _F.get_n()) ||
  253. ( (*this).get_d() != _F.get_d())
  254. )
  255. {
  256. fthrow(Exception, "FeatureMatrixT::operator!=(): (n != F.get_n()) || (d != F.get_d()) -- number of dimensions does not fit");
  257. }
  258. else if ((this->ui_n == 0) || (this->ui_d == 0))
  259. {
  260. return false;
  261. }
  262. for (uint i = 0; i < this->ui_d; i++)
  263. {
  264. for (uint j = 0; j < this->ui_n; j++)
  265. {
  266. if(!((*this)(i,j) == _F(i,j)))
  267. return true;
  268. }
  269. }
  270. return false;
  271. }
  272. template<typename T>
  273. inline FeatureMatrixT<T>&
  274. FeatureMatrixT<T>::operator=(const FeatureMatrixT<T> & _F)
  275. {
  276. this->set_d(_F.get_d());
  277. this->ui_n = _F.get_n();
  278. for (uint i = 0; i < (*this).get_d(); i++)
  279. {
  280. // use the operator= of SortedVectorSparse
  281. features[i] = _F[i];
  282. }
  283. return *this;
  284. }
  285. // Element access without validity check
  286. template <typename T>
  287. inline T FeatureMatrixT<T>::getUnsafe(const uint _row,
  288. const uint _col
  289. ) const
  290. {
  291. return (this->features[_row]).access(_col);
  292. }
  293. //! Element access of original values without validity check
  294. template <typename T>
  295. inline T FeatureMatrixT<T>::getOriginal(const uint _row,
  296. const uint _col
  297. ) const
  298. {
  299. return (this->features[_row]).accessOriginal(_col);
  300. }
  301. // Sets a specified element to the given value, performs validity check
  302. template <typename T>
  303. inline void FeatureMatrixT<T>::set (const uint _row,
  304. const uint _col,
  305. const T & _newElement,
  306. bool _setTransformedValue
  307. )
  308. {
  309. if ( (_row < 0) || (_col < 0) || (_row > this->ui_d) || (_col > this->ui_n) )
  310. {
  311. return;
  312. }
  313. else
  314. (this->features[_row]).set ( _col, _newElement, _setTransformedValue );
  315. }
  316. // Sets a specified element to the given value, without validity check
  317. template <typename T>
  318. inline void FeatureMatrixT<T>::setUnsafe (const uint _row,
  319. const uint _col,
  320. const T & _newElement,
  321. bool _setTransformedValue
  322. )
  323. {
  324. (this->features[_row]).set ( _col, _newElement, _setTransformedValue );
  325. }
  326. // Acceess to all element entries of a specified dimension, including validity check
  327. template <typename T>
  328. void FeatureMatrixT<T>::getDimension(const uint & _dim,
  329. NICE::SortedVectorSparse<T> & _dimension
  330. ) const
  331. {
  332. if ( (_dim < 0) || (_dim > this->ui_d) )
  333. {
  334. return;
  335. }
  336. else
  337. _dimension = this->features[_dim];
  338. }
  339. // Acceess to all element entries of a specified dimension, without validity check
  340. template <typename T>
  341. void FeatureMatrixT<T>::getDimensionUnsafe(const uint & _dim,
  342. NICE::SortedVectorSparse<T> & _dimension
  343. ) const
  344. {
  345. _dimension = this->features[_dim];
  346. }
  347. // Finds the first element in a given dimension, which equals elem
  348. template <typename T>
  349. void FeatureMatrixT<T>::findFirstInDimension(const uint & _dim,
  350. const T & _elem,
  351. uint & _position
  352. ) const
  353. {
  354. _position = 0;
  355. if ( (_dim < 0) || (_dim > this->ui_d))
  356. return;
  357. std::pair< typename SortedVectorSparse<T>::elementpointer, typename SortedVectorSparse<T>::elementpointer > eit;
  358. eit = this->features[_dim].nonzeroElements().equal_range ( _elem );
  359. _position = distance( this->features[_dim].nonzeroElements().begin(), eit.first );
  360. if ( _elem > this->features[_dim].getTolerance() )
  361. _position += this->features[_dim].getZeros();
  362. }
  363. // Finds the last element in a given dimension, which equals elem
  364. template <typename T>
  365. void FeatureMatrixT<T>::findLastInDimension(const uint & _dim,
  366. const T & _elem,
  367. uint & _position
  368. ) const
  369. {
  370. _position = 0;
  371. if ( (_dim < 0) || (_dim > this->ui_d))
  372. return;
  373. std::pair< typename SortedVectorSparse<T>::const_elementpointer, typename SortedVectorSparse<T>::const_elementpointer > eit = this->features[_dim].nonzeroElements().equal_range ( _elem );
  374. _position = distance( this->features[_dim].nonzeroElements().begin(), eit.second );
  375. if ( _elem > this->features[_dim].getTolerance() )
  376. _position += this->features[_dim].getZeros();
  377. }
  378. // Finds the first element in a given dimension, which is larger as elem
  379. template <typename T>
  380. void FeatureMatrixT<T>::findFirstLargerInDimension(const uint & _dim,
  381. const T & _elem,
  382. uint & _position
  383. ) const
  384. {
  385. _position = 0;
  386. if ( (_dim < 0) || (_dim > this->ui_d))
  387. return;
  388. //no non-zero elements?
  389. if (this->features[_dim].getNonZeros() <= 0)
  390. {
  391. // if element is greater than zero, than is should be added at the last position
  392. if (_elem > this->features[_dim].getTolerance() )
  393. _position = this->ui_n;
  394. //if not, position is -1
  395. return;
  396. }
  397. if (this->features[_dim].getNonZeros() == 1)
  398. {
  399. // if element is greater than the only nonzero element, than it is larger as everything else
  400. if (this->features[_dim].nonzeroElements().begin()->first <= _elem)
  401. _position = this->ui_n;
  402. //if not, but the element is still greater than zero, than
  403. else if (_elem > this->features[_dim].getTolerance() )
  404. _position = this->ui_n -1;
  405. return;
  406. }
  407. typename SortedVectorSparse<T>::const_elementpointer it = this->features[_dim].nonzeroElements().end(); //this is needed !!!
  408. it = this->features[_dim].nonzeroElements().upper_bound ( _elem ); //if all values are smaller, this does not do anything at all
  409. _position = distance( this->features[_dim].nonzeroElements().begin(), it );
  410. if ( _elem > this->features[_dim].getTolerance() )
  411. {
  412. //position += features[dim].getZeros();
  413. _position += this->ui_n - this->features[_dim].getNonZeros();
  414. }
  415. }
  416. // Finds the last element in a given dimension, which is smaller as elem
  417. template <typename T>
  418. void FeatureMatrixT<T>::findLastSmallerInDimension(const uint & _dim,
  419. const T & _elem,
  420. uint & _position
  421. ) const
  422. {
  423. _position = 0;
  424. if ( (_dim < 0) || (_dim > this->ui_d))
  425. return;
  426. typename SortedVectorSparse<T>::const_elementpointer it = this->features[_dim].nonzeroElements().lower_bound ( _elem );
  427. _position = distance( this->features[_dim].nonzeroElements().begin(), it );
  428. if ( it->first > this->features[_dim].getTolerance() )
  429. _position += this->features[_dim].getZeros();
  430. }
  431. //------------------------------------------------------
  432. // high level methods
  433. //------------------------------------------------------
  434. template <typename T>
  435. void FeatureMatrixT<T>::applyFunctionToFeatureMatrix ( const NICE::ParameterizedFunction *_pf )
  436. {
  437. if (_pf != NULL)
  438. {
  439. // REMARK: might be inefficient due to virtual calls
  440. if ( !_pf->isOrderPreserving() )
  441. fthrow(Exception, "ParameterizedFunction::applyFunctionToFeatureMatrix: this function is optimized for order preserving transformations");
  442. uint d = this->get_d();
  443. for (uint dim = 0; dim < d; dim++)
  444. {
  445. std::multimap< double, typename SortedVectorSparse<double>::dataelement> & nonzeroElements = this->getFeatureValues(dim).nonzeroElements();
  446. for ( SortedVectorSparse<double>::elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++ )
  447. {
  448. SortedVectorSparse<double>::dataelement & de = i->second;
  449. //TODO check, wether the element is "sparse" afterwards
  450. de.second = _pf->f( dim, i->first );
  451. }
  452. }
  453. /*for ( int i = 0 ; i < featureMatrix.get_n(); i++ )
  454. for ( int index = 0 ; index < featureMatrix.get_d(); index++ )
  455. featureMatrix.set(index, i, f( (uint)index, featureMatrix.getOriginal(index,i) ), isOrderPreserving() );*/
  456. }
  457. else
  458. {
  459. //no pf given -> nothing to do
  460. }
  461. }
  462. //Computes the ratio of sparsity across the matrix
  463. template <typename T>
  464. double FeatureMatrixT<T>:: computeSparsityRatio() const
  465. {
  466. double ratio(0.0);
  467. for (typename std::vector<NICE::SortedVectorSparse<T> >::const_iterator it = this->features.begin(); it != this->features.end(); it++)
  468. {
  469. ratio += (*it).getZeros() / (double) (*it).getN();
  470. }
  471. if (this->features.size() != 0)
  472. ratio /= double(this->features.size());
  473. return ratio;
  474. }
  475. // add a new feature and insert its elements at the end of each dimension vector
  476. template <typename T>
  477. void FeatureMatrixT<T>::add_feature( const std::vector<T> & _feature,
  478. const NICE::ParameterizedFunction *_pf
  479. )
  480. {
  481. if (this->ui_n == 0)
  482. {
  483. this->set_d( _feature.size() );
  484. }
  485. if ( _feature.size() != this->ui_d)
  486. {
  487. fthrow(Exception, "FeatureMatrixT<T>::add_feature - number of dimensions does not fit");
  488. return;
  489. }
  490. for (uint dimension = 0; dimension < this->features.size(); dimension++)
  491. {
  492. if (_pf != NULL)
  493. this->features[dimension].insert( _feature[dimension], _pf->f( dimension, _feature[dimension]) );
  494. else
  495. this->features[dimension].insert( _feature[dimension] );
  496. }
  497. this->ui_n++;
  498. }
  499. // add a new feature and insert its elements at the end of each dimension vector
  500. template <typename T>
  501. void FeatureMatrixT<T>::add_feature(const NICE::SparseVector & _feature,
  502. const ParameterizedFunction *_pf
  503. )
  504. {
  505. if (this->ui_n == 0)
  506. {
  507. this->set_d( _feature.size() );
  508. }
  509. if ( _feature.getDim() > this->ui_d)
  510. {
  511. fthrow(Exception, "FeatureMatrixT<T>::add_feature - number of dimensions does not fit");
  512. return;
  513. }
  514. for (NICE::SparseVector::const_iterator it = _feature.begin(); it != _feature.end(); it++)
  515. {
  516. if (_pf != NULL)
  517. this->features[it->first].insert( (T) it->second, _pf->f( it->first, (T) it->second), this->ui_n );
  518. else
  519. this->features[it->first].insert( (T) it->second, this->ui_n );
  520. }
  521. this->ui_n++;
  522. }
  523. // add several new features and insert their elements in the already ordered structure
  524. template <typename T>
  525. void FeatureMatrixT<T>::add_features(const std::vector<std::vector<T> > & _features )
  526. {
  527. //TODO do we need the parameterized function here as well? usually, we add several features and run applyFunctionToFeatureMatrix afterwards.
  528. // check this please :)
  529. //TODO assure that every feature has the same dimension
  530. if (this->ui_n == 0)
  531. {
  532. this->set_d(_features.size());
  533. }
  534. //pay attention: we assume now, that we have a vector (over dimensions) containing vectors over features (examples per dimension) - to be more efficient
  535. for (uint dim = 0; dim < this->ui_d; dim++)
  536. {
  537. this->features[dim].insert( _features[dim] );
  538. }
  539. //update the number of our features
  540. this->ui_n += _features[0].size();
  541. }
  542. template <typename T>
  543. void FeatureMatrixT<T>::set_features(const std::vector<std::vector<T> > & _features,
  544. std::vector<std::vector<uint> > & _permutations,
  545. const uint & _dim
  546. )
  547. {
  548. this->features.clear();
  549. if (_dim < 0)
  550. this->set_d( _features.size() );
  551. else
  552. this->set_d( _dim );
  553. if ( this->ui_d > 0 )
  554. this->ui_n = _features[0].size();
  555. //pay attention: we assume now, that we have a vector (over dimensions) containing vectors over features (examples per dimension) - to be more efficient
  556. for (uint dim = 0; dim < this->ui_d; dim++)
  557. {
  558. this->features[dim].insert( _features[dim] );
  559. }
  560. this->getPermutations( _permutations );
  561. }
  562. template <typename T>
  563. void FeatureMatrixT<T>::set_features(const std::vector<std::vector<T> > & _features,
  564. std::vector<std::map<uint,uint> > & _permutations,
  565. const uint & _dim
  566. )
  567. {
  568. this->features.clear();
  569. if ( _dim < 0)
  570. this->set_d( _features.size() );
  571. else
  572. this->set_d( _dim );
  573. if ( this->ui_d > 0 )
  574. this->ui_n = _features[0].size();
  575. //pay attention: we assume now, that we have a vector (over dimensions) containing vectors over features (examples per dimension) - to be more efficient
  576. for (uint dim = 0; dim < this->ui_d; dim++)
  577. {
  578. this->features[dim].insert( _features[dim] );
  579. }
  580. this->getPermutations( _permutations );
  581. }
  582. template <typename T>
  583. void FeatureMatrixT<T>::set_features(const std::vector<std::vector<T> > & _features,
  584. const uint & _dim
  585. )
  586. {
  587. this->features.clear();
  588. if (_dim < 0)
  589. this->set_d(_features.size());
  590. else
  591. this->set_d(_dim);
  592. if ( this->ui_d > 0 )
  593. this->ui_n = _features[0].size();
  594. //pay attention: we assume now, that we have a vector (over dimensions) containing vectors over features (examples per dimension) - to be more efficient
  595. for (uint dim = 0; dim < this->ui_d; dim++)
  596. {
  597. this->features[dim].insert( _features[dim] );
  598. }
  599. }
  600. template <typename T>
  601. void FeatureMatrixT<T>::set_features(const std::vector< const NICE::SparseVector * > & _features,
  602. const bool _dimensionsOverExamples,
  603. const uint & _dim
  604. )
  605. {
  606. this->features.clear();
  607. if (_features.size() == 0)
  608. {
  609. std::cerr << "set_features without features" << std::endl;
  610. }
  611. // resize our data structure
  612. if (_dim >= 0) //did the user specified the number of dimensions?
  613. this->set_d(_dim);
  614. else //dimensions not specified by users
  615. {
  616. if (_dimensionsOverExamples) //do we have dim x examples ?
  617. {
  618. this->set_d(_features.size());
  619. }
  620. else //we have examples x dimes (as usually done)
  621. {
  622. if (_features.size() > 0) //and have at least one example
  623. {
  624. try{
  625. this->set_d(_features[0]->getDim());
  626. }
  627. catch(...)
  628. {
  629. std::cerr << "FeatureMatrixT<T>::set_features -- something went wrong using getDim() of SparseVectors" << std::endl;
  630. }
  631. }
  632. else //no example, so set the dim to 0, since we have no idea at all
  633. {
  634. this-> set_d(0);
  635. }
  636. }
  637. }
  638. // set number of examples n
  639. if ( this->ui_d > 0 )
  640. {
  641. if ( _dimensionsOverExamples ) //do we have dim x examples ?
  642. this->ui_n = _features[0]->getDim(); //NOTE Pay attention: we assume, that this number is set!
  643. else //we have examples x dimes (as usually done)
  644. this->ui_n = _features.size();
  645. }
  646. // insert all values
  647. if ( _dimensionsOverExamples ) //do we have dim x examples ?
  648. {
  649. for (uint dim = 0; dim < this->ui_d; dim++)
  650. {
  651. this->features[dim].insert( _features[dim] );
  652. }
  653. }
  654. else //we have examples x dimes (as usually done)
  655. {
  656. if ( this->b_debug )
  657. std::cerr << "FeatureMatrixT<T>::set_features " << this->ui_n << " new examples" << std::endl;
  658. //loop over every example to add its content
  659. for (iint nr = 0; nr < this->ui_n; nr++)
  660. {
  661. if ( this->b_debug )
  662. std::cerr << "add feature nr. " << nr << " / " << _features.size() << " ";
  663. //loop over every dimension to add the specific value to the corresponding SortedVectorSparse
  664. for (NICE::SparseVector::const_iterator elemIt = _features[nr]->begin(); elemIt != _features[nr]->end(); elemIt++)
  665. {
  666. if ( this->b_debug )
  667. std::cerr << elemIt->first << "-" << elemIt->second << " ";
  668. //elemIt->first: dim, elemIt->second: value
  669. this->features[elemIt->first].insert( (T) elemIt->second, nr);
  670. }//for non-zero-values of the feature
  671. if ( this->b_debug )
  672. std::cerr << std::endl;
  673. }//for every new feature
  674. if ( this->b_debug )
  675. std::cerr << "FeatureMatrixT<T>::set_features done" << std::endl;
  676. }//if dimOverEx
  677. //set n for the internal data structure SortedVectorSparse
  678. for (typename std::vector<NICE::SortedVectorSparse<T> >::iterator it = this->features.begin(); it != this->features.end(); it++)
  679. (*it).setN( this->ui_n );
  680. }
  681. template <typename T>
  682. void FeatureMatrixT<T>::getPermutations( std::vector<std::vector<uint> > & _permutations) const
  683. {
  684. for (uint dim = 0; dim < this->ui_d; dim++)
  685. {
  686. std::vector<uint> perm ( (this->features[dim]).getPermutation() );
  687. _permutations.push_back(perm);
  688. }
  689. }
  690. template <typename T>
  691. void FeatureMatrixT<T>::getPermutations( std::vector<std::map<uint,uint> > & _permutations) const
  692. {
  693. for (uint dim = 0; dim < this->ui_d; dim++)
  694. {
  695. std::map<uint,uint> perm ( (this->features[dim]).getPermutationNonZeroReal() );
  696. _permutations.push_back(perm);
  697. }
  698. }
  699. // Prints the whole Matrix (outer loop over dimension, inner loop over features)
  700. template <typename T>
  701. void FeatureMatrixT<T>::print(std::ostream & _os) const
  702. {
  703. if (_os.good())
  704. {
  705. for (uint dim = 0; dim < this->ui_d; dim++)
  706. {
  707. this->features[dim].print(_os);
  708. }
  709. }
  710. }
  711. // Computes the whole non-sparse matrix. WARNING: this may result in a really memory-consuming data-structure!
  712. template <typename T>
  713. void FeatureMatrixT<T>::computeNonSparseMatrix(NICE::MatrixT<T> & _matrix,
  714. bool _transpose
  715. ) const
  716. {
  717. if ( _transpose )
  718. _matrix.resize(this->get_n(),this->get_d());
  719. else
  720. _matrix.resize(this->get_d(),this->get_n());
  721. _matrix.set((T)0.0);
  722. uint dimIdx(0);
  723. for (typename std::vector<NICE::SortedVectorSparse<T> >::const_iterator it = this->features.begin(); it != this->features.end(); it++, dimIdx++)
  724. {
  725. std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer> nonzeroIndices= (*it).nonzeroIndices();
  726. for (typename std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer>::const_iterator inIt = nonzeroIndices.begin(); inIt != nonzeroIndices.end(); inIt++)
  727. {
  728. uint featIndex = ((*inIt).second)->second.first;
  729. if ( _transpose )
  730. _matrix(featIndex,dimIdx) =((*inIt).second)->second.second;
  731. else
  732. _matrix(dimIdx,featIndex) =((*inIt).second)->second.second;
  733. }
  734. }
  735. }
  736. // Computes the whole non-sparse matrix. WARNING: this may result in a really memory-consuming data-structure!
  737. template <typename T>
  738. void FeatureMatrixT<T>::computeNonSparseMatrix(std::vector<std::vector<T> > & _matrix,
  739. bool _transpose
  740. ) const
  741. {
  742. if ( _transpose )
  743. _matrix.resize(this->get_n());
  744. else
  745. _matrix.resize(this->get_d());
  746. // resizing the matrix
  747. for ( uint i = 0 ; i < _matrix.size(); i++ )
  748. if ( _transpose )
  749. _matrix[i] = std::vector<T>(this->get_d(), 0.0);
  750. else
  751. _matrix[i] = std::vector<T>(this->get_n(), 0.0);
  752. uint dimIdx(0);
  753. for (typename std::vector<NICE::SortedVectorSparse<T> >::const_iterator it = this->features.begin(); it != this->features.end(); it++, dimIdx++)
  754. {
  755. std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer> nonzeroIndices= (*it).nonzeroIndices();
  756. for (typename std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer>::const_iterator inIt = nonzeroIndices.begin(); inIt != nonzeroIndices.end(); inIt++)
  757. {
  758. uint featIndex = ((*inIt).second)->second.first;
  759. if ( _transpose )
  760. _matrix[featIndex][dimIdx] =((*inIt).second)->second.second;
  761. else
  762. _matrix[dimIdx][featIndex] =((*inIt).second)->second.second;
  763. }
  764. }
  765. }
  766. // Swaps to specified elements, performing a validity check
  767. template <typename T>
  768. void FeatureMatrixT<T>::swap(const uint & _row1,
  769. const uint & _col1,
  770. const uint & _row2,
  771. const uint & _col2
  772. )
  773. {
  774. if ( (_row1 < 0) || (_col1 < 0) || (_row1 > this->ui_d) || (_col1 > this->ui_n) ||
  775. (_row2 < 0) || (_col2 < 0) || (_row2 > this->ui_d) || (_col2 > this->ui_n)
  776. )
  777. {
  778. return;
  779. }
  780. else
  781. {
  782. //swap
  783. T tmp = (*this)(_row1, _col1);
  784. (*this).set(_row1, _col1, (*this)(_row2,_col2));
  785. (*this).set(_row2, _col2, tmp);
  786. }
  787. }
  788. // Swaps to specified elements, without performing a validity check
  789. template <typename T>
  790. void FeatureMatrixT<T>::swapUnsafe(const uint & _row1,
  791. const uint & _col1,
  792. const uint & _row2,
  793. const uint & _col2
  794. )
  795. {
  796. //swap
  797. T tmp = (*this)(_row1, _col1);
  798. (*this).set(_row1, _col1, (*this)(_row2,_col2));
  799. (*this).set(_row2, _col2, tmp);
  800. }
  801. template <typename T>
  802. void FeatureMatrixT<T>::hikDiagonalElements( Vector & _diagonalElements ) const
  803. {
  804. uint dimIdx = 0;
  805. // the function calculates the diagonal elements of a HIK kernel matrix
  806. _diagonalElements.resize(this->ui_n);
  807. _diagonalElements.set(0.0);
  808. // loop through all dimensions
  809. for (typename std::vector<NICE::SortedVectorSparse<T> >::const_iterator it = this->features.begin(); it != this->features.end(); it++, dimIdx++)
  810. {
  811. std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer> nonzeroIndices= (*it).nonzeroIndices();
  812. // loop through all features
  813. for (typename std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer>::const_iterator inIt = nonzeroIndices.begin(); inIt != nonzeroIndices.end(); inIt++)
  814. {
  815. uint index = inIt->first;
  816. typename NICE::SortedVectorSparse<T>::elementpointer p = inIt->second;
  817. typename NICE::SortedVectorSparse<T>::dataelement de = p->second;
  818. _diagonalElements[index] += de.second;
  819. }
  820. }
  821. }
  822. template <typename T>
  823. double FeatureMatrixT<T>::hikTrace() const
  824. {
  825. Vector diagonalElements;
  826. this->hikDiagonalElements( diagonalElements );
  827. return diagonalElements.Sum();
  828. }
  829. template <typename T>
  830. uint FeatureMatrixT<T>::getNumberOfNonZeroElementsPerDimension(const uint & dim) const
  831. {
  832. //FIXME we could return a boolean indicating success and return the actual number via call-by-reference
  833. if ( (dim < 0) || (dim > this->ui_d))
  834. return 0;
  835. return this->features[dim].getNonZeros();
  836. }
  837. template <typename T>
  838. uint FeatureMatrixT<T>::getNumberOfZeroElementsPerDimension(const uint & dim) const
  839. {
  840. if ( (dim < 0) || (dim > this->ui_d))
  841. return 0;
  842. return this->ui_n - this-> features[dim].getNonZeros();
  843. }
  844. template <typename T>
  845. void FeatureMatrixT<T>::restore ( std::istream & _is,
  846. int _format
  847. )
  848. {
  849. bool b_restoreVerbose ( false );
  850. if ( _is.good() )
  851. {
  852. if ( b_restoreVerbose )
  853. std::cerr << " restore FeatureMatrixT" << std::endl;
  854. std::string tmp;
  855. _is >> tmp; //class name
  856. if ( ! this->isStartTag( tmp, "FeatureMatrixT" ) )
  857. {
  858. std::cerr << " WARNING - attempt to restore FeatureMatrixT, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  859. throw;
  860. }
  861. _is.precision ( std::numeric_limits<double>::digits10 + 1);
  862. bool b_endOfBlock ( false ) ;
  863. while ( !b_endOfBlock )
  864. {
  865. _is >> tmp; // start of block
  866. if ( this->isEndTag( tmp, "FeatureMatrixT" ) )
  867. {
  868. b_endOfBlock = true;
  869. continue;
  870. }
  871. tmp = this->removeStartTag ( tmp );
  872. if ( b_restoreVerbose )
  873. std::cerr << " currently restore section " << tmp << " in FeatureMatrixT" << std::endl;
  874. if ( tmp.compare("n") == 0 )
  875. {
  876. _is >> this->ui_n;
  877. _is >> tmp; // end of block
  878. tmp = this->removeEndTag ( tmp );
  879. }
  880. else if ( tmp.compare("d") == 0 )
  881. {
  882. _is >> this->ui_d;
  883. _is >> tmp; // end of block
  884. tmp = this->removeEndTag ( tmp );
  885. }
  886. else if ( tmp.compare("features") == 0 )
  887. {
  888. //NOTE assumes d to be read first!
  889. this->features.resize( this->ui_d);
  890. //now read features for every dimension
  891. for (uint dim = 0; dim < this->ui_d; dim++)
  892. {
  893. NICE::SortedVectorSparse<T> svs;
  894. this->features[dim] = svs;
  895. this->features[dim].restore(_is, _format);
  896. }
  897. _is >> tmp; // end of block
  898. tmp = this->removeEndTag ( tmp );
  899. }
  900. else
  901. {
  902. std::cerr << "WARNING -- unexpected FeatureMatrixT object -- " << tmp << " -- for restoration... aborting" << std::endl;
  903. throw;
  904. }
  905. }
  906. }
  907. else
  908. {
  909. std::cerr << "FeatureMatrixT<T>::restore -- InStream not initialized - restoring not possible!" << std::endl;
  910. throw;
  911. }
  912. }
  913. template <typename T>
  914. void FeatureMatrixT<T>::store ( std::ostream & _os,
  915. int _format
  916. ) const
  917. {
  918. if (_os.good())
  919. {
  920. // show starting point
  921. _os << this->createStartTag( "FeatureMatrixT" ) << std::endl;
  922. _os.precision (std::numeric_limits<double>::digits10 + 1);
  923. _os << this->createStartTag( "ui_n" ) << std::endl;
  924. _os << this->ui_n << std::endl;
  925. _os << this->createEndTag( "ui_n" ) << std::endl;
  926. _os << this->createStartTag( "ui_d" ) << std::endl;
  927. _os << this->ui_d << std::endl;
  928. _os << this->createEndTag( "ui_d" ) << std::endl;
  929. //now write features for every dimension
  930. _os << this->createStartTag( "features" ) << std::endl;
  931. for (uint dim = 0; dim < this->ui_d; dim++)
  932. {
  933. this->features[dim].store(_os,_format);
  934. }
  935. _os << this->createEndTag( "features" ) << std::endl;
  936. // done
  937. _os << this->createEndTag( "FeatureMatrixT" ) << std::endl;
  938. }
  939. else
  940. {
  941. std::cerr << "FeatureMatrixT<T>::store -- OutStream not initialized - storing not possible!" << std::endl;
  942. }
  943. }
  944. template <typename T>
  945. void FeatureMatrixT<T>::clear ()
  946. {}
  947. } // namespace
  948. // #endif