SHOGUN  3.2.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
PNorm.cpp
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * Written (W) 2012 Viktor Gal
8  * Copyright (C) 2012 Viktor Gal
9  */
10 
15 
16 #ifdef HAVE_LAPACK
18 #endif
19 
20 using namespace shogun;
21 
24  m_p (2.0)
25 {
26  register_param ();
27 }
28 
29 CPNorm::CPNorm (double p)
31  m_p (p)
32 {
33  ASSERT (m_p >= 1.0)
34  register_param ();
35 }
36 
38 {
39 }
40 
42 bool CPNorm::init (CFeatures* features)
43 {
44  ASSERT(features->get_feature_class()==C_DENSE)
45  ASSERT(features->get_feature_type()==F_DREAL)
46 
47  return true;
48 }
49 
52 {
53 }
54 
56 bool CPNorm::load (FILE* f)
57 {
60  return false;
61 }
62 
64 bool CPNorm::save (FILE* f)
65 {
68  return false;
69 }
70 
75 {
76  SGMatrix<float64_t> feature_matrix=((CDenseFeatures<float64_t>*)features)->get_feature_matrix();
77 
78  for (int32_t i=0; i<feature_matrix.num_cols; i++)
79  {
80  float64_t* vec= &(feature_matrix.matrix[i*feature_matrix.num_rows]);
81  float64_t norm = get_pnorm (vec, feature_matrix.num_rows);
82  SGVector<float64_t>::scale_vector(1.0/norm, vec, feature_matrix.num_rows);
83  }
84  return feature_matrix;
85 }
86 
90 {
91  float64_t* normed_vec = SG_MALLOC(float64_t, vector.vlen);
92  float64_t norm = get_pnorm (vector.vector, vector.vlen);
93 
94  for (int32_t i=0; i<vector.vlen; i++)
95  normed_vec[i]=vector.vector[i]/norm;
96 
97  return SGVector<float64_t>(normed_vec,vector.vlen);
98 }
99 
100 void CPNorm::set_pnorm (double pnorm)
101 {
102  ASSERT (pnorm >= 1.0)
103  m_p = pnorm;
104  register_param ();
105 }
106 
107 double CPNorm::get_pnorm () const
108 {
109  return m_p;
110 }
111 
112 void CPNorm::register_param ()
113 {
114  m_parameters->add (&m_p, "norm", "P-norm parameter");
115 }
116 
117 inline float64_t CPNorm::get_pnorm (float64_t* vec, int32_t vec_len) const
118 {
119  float64_t norm = 0.0;
120  if (m_p == 1.0)
121  {
122  for (int i = 0; i < vec_len; ++i)
123  norm += fabs (vec[i]);
124  }
125  else if (m_p == 2.0)
126  {
127  norm = SGVector<float64_t>::twonorm(vec, vec_len);
128  }
129  else
130  {
131  norm = SGVector<float64_t>::qnorm(vec, vec_len, m_p);
132  }
133 
134  return norm;
135 }

SHOGUN Machine Learning Toolbox - Documentation