SubrangeKernelTutorial.cpp
Go to the documentation of this file.
8 #include <shark/Core/Random.h>
9 
10 using namespace shark;
11 
12 //our problem
13 class UniformPoints : public DataDistribution<RealVector>
14 {
15 public:
16  UniformPoints(std::size_t dimensions){
17  m_dimensions = dimensions;
18  }
19 
20  void draw(RealVector& input)const{
21  input.resize(m_dimensions);
22  for ( std::size_t j=0; j<m_dimensions; j++ ) {
23  input(j) = random::uni(random::globalRng, -1,1);
24  }
25  }
26 
27 protected:
28  std::size_t m_dimensions;
29 };
30 
31 int main()
32 {
33  std::cout << "\n ----- Starting MklKernel normalization demo ---- \n\n" << std::flush;
34 
35  std::size_t num_dims = 9;
36  std::size_t num_points = 200;
37  UniformPoints problem(num_dims);
38  UnlabeledData<RealVector> data = problem.generateDataset(num_points);
39 
40  DenseRbfKernel basekernel1(0.1);
41  DenseLinearKernel basekernel2;
42  DensePolynomialKernel basekernel3(2, 1.0);
43 
44  std::vector< AbstractKernelFunction<RealVector> * > kernels;
45  kernels.push_back(&basekernel1);
46  kernels.push_back(&basekernel2);
47  kernels.push_back(&basekernel3);
48 
49  std::vector< std::pair< std::size_t, std::size_t > > frs;
50  frs.push_back( std::make_pair( 0,3 ) );
51  frs.push_back( std::make_pair( 3,6 ) );
52  frs.push_back( std::make_pair( 6,9 ) );
53 
54  DenseSubrangeKernel kernel( kernels, frs );
55  DenseScaledKernel scale( &kernel );
56 
58  normalizer.train( scale, data );
59  std::cout << " Done training. Factor is " << scale.factor() << std::endl;
60  std::cout << " Mean = " << normalizer.mean() << std::endl;
61  std::cout << " Trace = " << normalizer.trace() << std::endl << std::endl;
62  //check in feature space
63  double control = 0.0;
64  for ( std::size_t i=0; i<num_points; i++ ) {
65  control += scale.eval(data.element(i), data.element(i));
66  for ( std::size_t j=0; j<num_points; j++ ) {
67  control -= scale.eval(data.element(i), data.element(j)) / num_points;
68  }
69  }
70  control /= num_points;
71  std::cout << " Variance of scaled MklKernel: " << control << std::endl;
72 }