FeatureMatrixT.tcc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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 > 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 > 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 > 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 0
  395. return;
  396. }
  397. if (this->features[_dim].getNonZeros() == 1)
  398. {
  399. std::cerr << " FeatureMatrixT<T>::findFirstLargerInDimension -- only one non-zero element: " << this->features[_dim].getNonZeros() << " with value : " << this->features[_dim].nonzeroElements().begin()->first << std::endl;
  400. // if element is greater than the only nonzero element, then it is larger than everything else
  401. if (this->features[_dim].nonzeroElements().begin()->first <= _elem)
  402. _position = this->ui_n;
  403. //if not, but the element is still greater than zero, than
  404. else if (_elem > this->features[_dim].getTolerance() )
  405. _position = this->ui_n -1;
  406. std::cerr << " -> decided position: " << _position << std::endl;
  407. return;
  408. }
  409. // standard case - not everything is zero and not only a single element is zero
  410. // find pointer to last non-zero element
  411. // FIXME no idea why this should be necessary...
  412. typename SortedVectorSparse<T>::const_elementpointer it = this->features[_dim].nonzeroElements().end(); //this is needed !!!
  413. // find pointer to first element largern than the given value
  414. it = this->features[_dim].nonzeroElements().upper_bound ( _elem ); //if all values are smaller, this does not do anything at all
  415. _position = distance( this->features[_dim].nonzeroElements().begin(), it );
  416. T valtmp ( it->second.second );
  417. std::cerr << " FeatureMatrixT<T>::findFirstLargerInDimension --distance is : " << _position << " with value: " << (double) valtmp << std::endl;
  418. if ( _elem > this->features[_dim].getTolerance() )
  419. {
  420. //position += features[dim].getZeros();
  421. _position += this->ui_n - this->features[_dim].getNonZeros();
  422. }
  423. }
  424. // Finds the last element in a given dimension, which is smaller as elem
  425. template <typename T>
  426. void FeatureMatrixT<T>::findLastSmallerInDimension(const uint & _dim,
  427. const T & _elem,
  428. uint & _position
  429. ) const
  430. {
  431. _position = 0;
  432. if ( (_dim < 0) || (_dim > this->ui_d))
  433. return;
  434. typename SortedVectorSparse<T>::const_elementpointer it = this->features[_dim].nonzeroElements().lower_bound ( _elem );
  435. _position = distance( this->features[_dim].nonzeroElements().begin(), it );
  436. if ( it->first > this->features[_dim].getTolerance() )
  437. _position += this->features[_dim].getZeros();
  438. }
  439. //------------------------------------------------------
  440. // high level methods
  441. //------------------------------------------------------
  442. template <typename T>
  443. void FeatureMatrixT<T>::applyFunctionToFeatureMatrix ( const NICE::ParameterizedFunction *_pf )
  444. {
  445. if (_pf != NULL)
  446. {
  447. // REMARK: might be inefficient due to virtual calls
  448. if ( !_pf->isOrderPreserving() )
  449. fthrow(Exception, "ParameterizedFunction::applyFunctionToFeatureMatrix: this function is optimized for order preserving transformations");
  450. uint d = this->get_d();
  451. for (uint dim = 0; dim < d; dim++)
  452. {
  453. std::multimap< double, typename SortedVectorSparse<double>::dataelement> & nonzeroElements = this->getFeatureValues(dim).nonzeroElements();
  454. for ( SortedVectorSparse<double>::elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++ )
  455. {
  456. SortedVectorSparse<double>::dataelement & de = i->second;
  457. //TODO check, wether the element is "sparse" afterwards
  458. de.second = _pf->f( dim, i->first );
  459. }
  460. }
  461. /*for ( int i = 0 ; i < featureMatrix.get_n(); i++ )
  462. for ( int index = 0 ; index < featureMatrix.get_d(); index++ )
  463. featureMatrix.set(index, i, f( (uint)index, featureMatrix.getOriginal(index,i) ), isOrderPreserving() );*/
  464. }
  465. else
  466. {
  467. //no pf given -> nothing to do
  468. }
  469. }
  470. //Computes the ratio of sparsity across the matrix
  471. template <typename T>
  472. double FeatureMatrixT<T>:: computeSparsityRatio() const
  473. {
  474. double ratio(0.0);
  475. for (typename std::vector<NICE::SortedVectorSparse<T> >::const_iterator it = this->features.begin(); it != this->features.end(); it++)
  476. {
  477. ratio += (*it).getZeros() / (double) (*it).getN();
  478. }
  479. if (this->features.size() != 0)
  480. ratio /= double(this->features.size());
  481. return ratio;
  482. }
  483. // add a new feature and insert its elements at the end of each dimension vector
  484. template <typename T>
  485. void FeatureMatrixT<T>::add_feature( const std::vector<T> & _feature,
  486. const NICE::ParameterizedFunction *_pf
  487. )
  488. {
  489. if (this->ui_n == 0)
  490. {
  491. this->set_d( _feature.size() );
  492. }
  493. if ( _feature.size() != this->ui_d)
  494. {
  495. fthrow(Exception, "FeatureMatrixT<T>::add_feature - number of dimensions does not fit");
  496. return;
  497. }
  498. for (uint dimension = 0; dimension < this->features.size(); dimension++)
  499. {
  500. if (_pf != NULL)
  501. this->features[dimension].insert( _feature[dimension], _pf->f( dimension, _feature[dimension]) );
  502. else
  503. this->features[dimension].insert( _feature[dimension] );
  504. }
  505. this->ui_n++;
  506. }
  507. // add a new feature and insert its elements at the end of each dimension vector
  508. template <typename T>
  509. void FeatureMatrixT<T>::add_feature(const NICE::SparseVector & _feature,
  510. const ParameterizedFunction *_pf
  511. )
  512. {
  513. if (this->ui_n == 0)
  514. {
  515. this->set_d( _feature.size() );
  516. }
  517. if ( _feature.getDim() > this->ui_d)
  518. {
  519. fthrow(Exception, "FeatureMatrixT<T>::add_feature - number of dimensions does not fit");
  520. return;
  521. }
  522. for (NICE::SparseVector::const_iterator it = _feature.begin(); it != _feature.end(); it++)
  523. {
  524. if (_pf != NULL)
  525. this->features[it->first].insert( (T) it->second, _pf->f( it->first, (T) it->second), this->ui_n );
  526. else
  527. this->features[it->first].insert( (T) it->second, this->ui_n );
  528. }
  529. this->ui_n++;
  530. }
  531. // add several new features and insert their elements in the already ordered structure
  532. template <typename T>
  533. void FeatureMatrixT<T>::add_features(const std::vector<std::vector<T> > & _features )
  534. {
  535. //TODO do we need the parameterized function here as well? usually, we add several features and run applyFunctionToFeatureMatrix afterwards.
  536. // check this please :)
  537. //TODO assure that every feature has the same dimension
  538. if (this->ui_n == 0)
  539. {
  540. this->set_d(_features.size());
  541. }
  542. //pay attention: we assume now, that we have a vector (over dimensions) containing vectors over features (examples per dimension) - to be more efficient
  543. for (uint dim = 0; dim < this->ui_d; dim++)
  544. {
  545. this->features[dim].insert( _features[dim] );
  546. }
  547. //update the number of our features
  548. this->ui_n += _features[0].size();
  549. }
  550. template <typename T>
  551. void FeatureMatrixT<T>::set_features(const std::vector<std::vector<T> > & _features,
  552. std::vector<std::vector<uint> > & _permutations,
  553. const uint & _dim
  554. )
  555. {
  556. this->features.clear();
  557. this->set_d( std::max ( _dim, _features.size() ) );
  558. if ( this->ui_d > 0 )
  559. this->ui_n = _features[0].size();
  560. //pay attention: we assume now, that we have a vector (over dimensions) containing vectors over features (examples per dimension) - to be more efficient
  561. for (uint dim = 0; dim < this->ui_d; dim++)
  562. {
  563. this->features[dim].insert( _features[dim] );
  564. }
  565. this->getPermutations( _permutations );
  566. }
  567. template <typename T>
  568. void FeatureMatrixT<T>::set_features(const std::vector<std::vector<T> > & _features,
  569. std::vector<std::map<uint,uint> > & _permutations,
  570. const uint & _dim
  571. )
  572. {
  573. this->features.clear();
  574. this->set_d( std::max ( _dim, _features.size() ) );
  575. if ( this->ui_d > 0 )
  576. this->ui_n = _features[0].size();
  577. //pay attention: we assume now, that we have a vector (over dimensions) containing vectors over features (examples per dimension) - to be more efficient
  578. for (uint dim = 0; dim < this->ui_d; dim++)
  579. {
  580. this->features[dim].insert( _features[dim] );
  581. }
  582. this->getPermutations( _permutations );
  583. }
  584. template <typename T>
  585. void FeatureMatrixT<T>::set_features(const std::vector<std::vector<T> > & _features,
  586. const uint & _dim
  587. )
  588. {
  589. this->features.clear();
  590. uint featsize ( _features.size() ); // necessary for some compiler reasons
  591. this->set_d( std::max ( _dim, featsize ) );
  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. //therefore, let's first of all figure out if the user specified a dimension or not.
  613. uint dimTmp ( _dim );
  614. if (_dimensionsOverExamples) //do we have dim x examples ?
  615. {
  616. if ( _features.size() > dimTmp )
  617. {
  618. dimTmp = _features.size();
  619. }
  620. }
  621. else //we have examples x dimes (as usually done)
  622. {
  623. if (_features.size() > 0) //and have at least one example
  624. {
  625. try{
  626. if ( _features[0]->getDim() > dimTmp )
  627. {
  628. dimTmp = _features[0]->getDim();
  629. }
  630. }
  631. catch(...)
  632. {
  633. std::cerr << "FeatureMatrixT<T>::set_features -- something went wrong using getDim() of SparseVectors" << std::endl;
  634. }
  635. }
  636. }
  637. this->set_d( dimTmp );
  638. std::cerr << "FeatureMatrixT<T>::set_features -- dimension: " << this->get_d() << std::endl;
  639. // set number of examples n
  640. if ( this->ui_d > 0 )
  641. {
  642. if ( _dimensionsOverExamples ) //do we have dim x examples ?
  643. this->ui_n = _features[0]->getDim(); //NOTE Pay attention: we assume, that this number is set!
  644. else //we have examples x dimes (as usually done)
  645. this->ui_n = _features.size();
  646. }
  647. // insert all values
  648. if ( _dimensionsOverExamples ) //do we have dim x examples ?
  649. {
  650. for (uint dim = 0; dim < this->ui_d; dim++)
  651. {
  652. this->features[dim].insert( _features[dim] );
  653. }
  654. }
  655. else //we have examples x dimes (as usually done)
  656. {
  657. if ( this->b_debug )
  658. std::cerr << "FeatureMatrixT<T>::set_features " << this->ui_n << " new examples" << std::endl;
  659. //loop over every example to add its content
  660. for (uint nr = 0; nr < this->ui_n; nr++)
  661. {
  662. if ( this->b_debug )
  663. std::cerr << "add feature nr. " << nr << " / " << _features.size() << " ";
  664. //loop over every dimension to add the specific value to the corresponding SortedVectorSparse
  665. for (NICE::SparseVector::const_iterator elemIt = _features[nr]->begin(); elemIt != _features[nr]->end(); elemIt++)
  666. {
  667. if ( this->b_debug )
  668. std::cerr << elemIt->first << "-" << elemIt->second << " ";
  669. //elemIt->first: dim, elemIt->second: value
  670. this->features[elemIt->first].insert( (T) elemIt->second, nr);
  671. }//for non-zero-values of the feature
  672. if ( this->b_debug )
  673. std::cerr << std::endl;
  674. }//for every new feature
  675. if ( this->b_debug )
  676. std::cerr << "FeatureMatrixT<T>::set_features done" << std::endl;
  677. }//if dimOverEx
  678. //set n for the internal data structure SortedVectorSparse
  679. for (typename std::vector<NICE::SortedVectorSparse<T> >::iterator it = this->features.begin(); it != this->features.end(); it++)
  680. (*it).setN( this->ui_n );
  681. }
  682. template <typename T>
  683. void FeatureMatrixT<T>::getPermutations( std::vector<std::vector<uint> > & _permutations) const
  684. {
  685. for (uint dim = 0; dim < this->ui_d; dim++)
  686. {
  687. std::vector<uint> perm ( (this->features[dim]).getPermutation() );
  688. _permutations.push_back(perm);
  689. }
  690. }
  691. template <typename T>
  692. void FeatureMatrixT<T>::getPermutations( std::vector<std::map<uint,uint> > & _permutations) const
  693. {
  694. for (uint dim = 0; dim < this->ui_d; dim++)
  695. {
  696. std::map<uint,uint> perm ( (this->features[dim]).getPermutationNonZeroReal() );
  697. _permutations.push_back(perm);
  698. }
  699. }
  700. // Prints the whole Matrix (outer loop over dimension, inner loop over features)
  701. template <typename T>
  702. void FeatureMatrixT<T>::print(std::ostream & _os) const
  703. {
  704. if (_os.good())
  705. {
  706. for (uint dim = 0; dim < this->ui_d; dim++)
  707. {
  708. this->features[dim].print(_os);
  709. }
  710. }
  711. }
  712. // Computes the whole non-sparse matrix. WARNING: this may result in a really memory-consuming data-structure!
  713. template <typename T>
  714. void FeatureMatrixT<T>::computeNonSparseMatrix(NICE::MatrixT<T> & _matrix,
  715. bool _transpose
  716. ) const
  717. {
  718. if ( _transpose )
  719. _matrix.resize(this->get_n(),this->get_d());
  720. else
  721. _matrix.resize(this->get_d(),this->get_n());
  722. _matrix.set((T)0.0);
  723. uint dimIdx(0);
  724. for (typename std::vector<NICE::SortedVectorSparse<T> >::const_iterator it = this->features.begin(); it != this->features.end(); it++, dimIdx++)
  725. {
  726. std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer> nonzeroIndices= (*it).nonzeroIndices();
  727. for (typename std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer>::const_iterator inIt = nonzeroIndices.begin(); inIt != nonzeroIndices.end(); inIt++)
  728. {
  729. uint featIndex = ((*inIt).second)->second.first;
  730. if ( _transpose )
  731. _matrix(featIndex,dimIdx) =((*inIt).second)->second.second;
  732. else
  733. _matrix(dimIdx,featIndex) =((*inIt).second)->second.second;
  734. }
  735. }
  736. }
  737. // Computes the whole non-sparse matrix. WARNING: this may result in a really memory-consuming data-structure!
  738. template <typename T>
  739. void FeatureMatrixT<T>::computeNonSparseMatrix(std::vector<std::vector<T> > & _matrix,
  740. bool _transpose
  741. ) const
  742. {
  743. if ( _transpose )
  744. _matrix.resize(this->get_n());
  745. else
  746. _matrix.resize(this->get_d());
  747. // resizing the matrix
  748. for ( uint i = 0 ; i < _matrix.size(); i++ )
  749. if ( _transpose )
  750. _matrix[i] = std::vector<T>(this->get_d(), 0.0);
  751. else
  752. _matrix[i] = std::vector<T>(this->get_n(), 0.0);
  753. uint dimIdx(0);
  754. for (typename std::vector<NICE::SortedVectorSparse<T> >::const_iterator it = this->features.begin(); it != this->features.end(); it++, dimIdx++)
  755. {
  756. std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer> nonzeroIndices= (*it).nonzeroIndices();
  757. for (typename std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer>::const_iterator inIt = nonzeroIndices.begin(); inIt != nonzeroIndices.end(); inIt++)
  758. {
  759. uint featIndex = ((*inIt).second)->second.first;
  760. if ( _transpose )
  761. _matrix[featIndex][dimIdx] =((*inIt).second)->second.second;
  762. else
  763. _matrix[dimIdx][featIndex] =((*inIt).second)->second.second;
  764. }
  765. }
  766. }
  767. // Swaps to specified elements, performing a validity check
  768. template <typename T>
  769. void FeatureMatrixT<T>::swap(const uint & _row1,
  770. const uint & _col1,
  771. const uint & _row2,
  772. const uint & _col2
  773. )
  774. {
  775. if ( (_row1 < 0) || (_col1 < 0) || (_row1 > this->ui_d) || (_col1 > this->ui_n) ||
  776. (_row2 < 0) || (_col2 < 0) || (_row2 > this->ui_d) || (_col2 > this->ui_n)
  777. )
  778. {
  779. return;
  780. }
  781. else
  782. {
  783. //swap
  784. T tmp = (*this)(_row1, _col1);
  785. (*this).set(_row1, _col1, (*this)(_row2,_col2));
  786. (*this).set(_row2, _col2, tmp);
  787. }
  788. }
  789. // Swaps to specified elements, without performing a validity check
  790. template <typename T>
  791. void FeatureMatrixT<T>::swapUnsafe(const uint & _row1,
  792. const uint & _col1,
  793. const uint & _row2,
  794. const uint & _col2
  795. )
  796. {
  797. //swap
  798. T tmp = (*this)(_row1, _col1);
  799. (*this).set(_row1, _col1, (*this)(_row2,_col2));
  800. (*this).set(_row2, _col2, tmp);
  801. }
  802. template <typename T>
  803. void FeatureMatrixT<T>::hikDiagonalElements( Vector & _diagonalElements ) const
  804. {
  805. uint dimIdx = 0;
  806. // the function calculates the diagonal elements of a HIK kernel matrix
  807. _diagonalElements.resize(this->ui_n);
  808. _diagonalElements.set(0.0);
  809. // loop through all dimensions
  810. for (typename std::vector<NICE::SortedVectorSparse<T> >::const_iterator it = this->features.begin(); it != this->features.end(); it++, dimIdx++)
  811. {
  812. std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer> nonzeroIndices= (*it).nonzeroIndices();
  813. // loop through all features
  814. for (typename std::map< uint, typename NICE::SortedVectorSparse<T>::elementpointer>::const_iterator inIt = nonzeroIndices.begin(); inIt != nonzeroIndices.end(); inIt++)
  815. {
  816. uint index = inIt->first;
  817. typename NICE::SortedVectorSparse<T>::elementpointer p = inIt->second;
  818. typename NICE::SortedVectorSparse<T>::dataelement de = p->second;
  819. _diagonalElements[index] += de.second;
  820. }
  821. }
  822. }
  823. template <typename T>
  824. double FeatureMatrixT<T>::hikTrace() const
  825. {
  826. Vector diagonalElements;
  827. this->hikDiagonalElements( diagonalElements );
  828. return diagonalElements.Sum();
  829. }
  830. template <typename T>
  831. uint FeatureMatrixT<T>::getNumberOfNonZeroElementsPerDimension(const uint & dim) const
  832. {
  833. //FIXME we could return a boolean indicating success and return the actual number via call-by-reference
  834. if ( (dim < 0) || (dim > this->ui_d))
  835. return 0;
  836. return this->features[dim].getNonZeros();
  837. }
  838. template <typename T>
  839. uint FeatureMatrixT<T>::getNumberOfZeroElementsPerDimension(const uint & dim) const
  840. {
  841. if ( (dim < 0) || (dim > this->ui_d))
  842. return 0;
  843. return this->ui_n - this-> features[dim].getNonZeros();
  844. }
  845. template <typename T>
  846. void FeatureMatrixT<T>::restore ( std::istream & _is,
  847. int _format
  848. )
  849. {
  850. bool b_restoreVerbose ( false );
  851. if ( _is.good() )
  852. {
  853. if ( b_restoreVerbose )
  854. std::cerr << " restore FeatureMatrixT" << std::endl;
  855. std::string tmp;
  856. _is >> tmp; //class name
  857. if ( ! this->isStartTag( tmp, "FeatureMatrixT" ) )
  858. {
  859. std::cerr << " WARNING - attempt to restore FeatureMatrixT, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  860. throw;
  861. }
  862. _is.precision ( std::numeric_limits<double>::digits10 + 1);
  863. bool b_endOfBlock ( false ) ;
  864. while ( !b_endOfBlock )
  865. {
  866. _is >> tmp; // start of block
  867. if ( this->isEndTag( tmp, "FeatureMatrixT" ) )
  868. {
  869. b_endOfBlock = true;
  870. continue;
  871. }
  872. tmp = this->removeStartTag ( tmp );
  873. if ( b_restoreVerbose )
  874. std::cerr << " currently restore section " << tmp << " in FeatureMatrixT" << std::endl;
  875. if ( tmp.compare("n") == 0 )
  876. {
  877. _is >> this->ui_n;
  878. _is >> tmp; // end of block
  879. tmp = this->removeEndTag ( tmp );
  880. }
  881. else if ( tmp.compare("d") == 0 )
  882. {
  883. _is >> this->ui_d;
  884. _is >> tmp; // end of block
  885. tmp = this->removeEndTag ( tmp );
  886. }
  887. else if ( tmp.compare("features") == 0 )
  888. {
  889. //NOTE assumes d to be read first!
  890. this->features.resize( this->ui_d);
  891. //now read features for every dimension
  892. for (uint dim = 0; dim < this->ui_d; dim++)
  893. {
  894. NICE::SortedVectorSparse<T> svs;
  895. this->features[dim] = svs;
  896. this->features[dim].restore(_is, _format);
  897. }
  898. _is >> tmp; // end of block
  899. tmp = this->removeEndTag ( tmp );
  900. }
  901. else
  902. {
  903. std::cerr << "WARNING -- unexpected FeatureMatrixT object -- " << tmp << " -- for restoration... aborting" << std::endl;
  904. throw;
  905. }
  906. }
  907. }
  908. else
  909. {
  910. std::cerr << "FeatureMatrixT<T>::restore -- InStream not initialized - restoring not possible!" << std::endl;
  911. throw;
  912. }
  913. }
  914. template <typename T>
  915. void FeatureMatrixT<T>::store ( std::ostream & _os,
  916. int _format
  917. ) const
  918. {
  919. if (_os.good())
  920. {
  921. // show starting point
  922. _os << this->createStartTag( "FeatureMatrixT" ) << std::endl;
  923. _os.precision (std::numeric_limits<double>::digits10 + 1);
  924. _os << this->createStartTag( "ui_n" ) << std::endl;
  925. _os << this->ui_n << std::endl;
  926. _os << this->createEndTag( "ui_n" ) << std::endl;
  927. _os << this->createStartTag( "ui_d" ) << std::endl;
  928. _os << this->ui_d << std::endl;
  929. _os << this->createEndTag( "ui_d" ) << std::endl;
  930. //now write features for every dimension
  931. _os << this->createStartTag( "features" ) << std::endl;
  932. for (uint dim = 0; dim < this->ui_d; dim++)
  933. {
  934. this->features[dim].store(_os,_format);
  935. }
  936. _os << this->createEndTag( "features" ) << std::endl;
  937. // done
  938. _os << this->createEndTag( "FeatureMatrixT" ) << std::endl;
  939. }
  940. else
  941. {
  942. std::cerr << "FeatureMatrixT<T>::store -- OutStream not initialized - storing not possible!" << std::endl;
  943. }
  944. }
  945. template <typename T>
  946. void FeatureMatrixT<T>::clear ()
  947. {}
  948. } // namespace
  949. // #endif