Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011 #include <shogun/preprocessor/PNorm.h>
00012 #include <shogun/preprocessor/DensePreprocessor.h>
00013 #include <shogun/mathematics/Math.h>
00014 #include <shogun/features/Features.h>
00015
00016 #ifdef HAVE_LAPACK
00017 #include <shogun/mathematics/lapack.h>
00018 #endif
00019
00020 using namespace shogun;
00021
00022 CPNorm::CPNorm ()
00023 : CDensePreprocessor<float64_t>(),
00024 m_p (2.0)
00025 {
00026 register_param ();
00027 }
00028
00029 CPNorm::CPNorm (double p)
00030 : CDensePreprocessor<float64_t>(),
00031 m_p (p)
00032 {
00033 ASSERT (m_p >= 1.0);
00034 register_param ();
00035 }
00036
00037 CPNorm::~CPNorm ()
00038 {
00039 }
00040
00042 bool CPNorm::init (CFeatures* features)
00043 {
00044 ASSERT(features->get_feature_class()==C_DENSE);
00045 ASSERT(features->get_feature_type()==F_DREAL);
00046
00047 return true;
00048 }
00049
00051 void CPNorm::cleanup ()
00052 {
00053 }
00054
00056 bool CPNorm::load (FILE* f)
00057 {
00058 SG_SET_LOCALE_C;
00059 SG_RESET_LOCALE;
00060 return false;
00061 }
00062
00064 bool CPNorm::save (FILE* f)
00065 {
00066 SG_SET_LOCALE_C;
00067 SG_RESET_LOCALE;
00068 return false;
00069 }
00070
00074 SGMatrix<float64_t> CPNorm::apply_to_feature_matrix (CFeatures* features)
00075 {
00076 SGMatrix<float64_t> feature_matrix=((CDenseFeatures<float64_t>*)features)->get_feature_matrix();
00077
00078 for (int32_t i=0; i<feature_matrix.num_cols; i++)
00079 {
00080 float64_t* vec= &(feature_matrix.matrix[i*feature_matrix.num_rows]);
00081 float64_t norm = get_pnorm (vec, feature_matrix.num_rows);
00082 SGVector<float64_t>::scale_vector(1.0/norm, vec, feature_matrix.num_rows);
00083 }
00084 return feature_matrix;
00085 }
00086
00089 SGVector<float64_t> CPNorm::apply_to_feature_vector (SGVector<float64_t> vector)
00090 {
00091 float64_t* normed_vec = SG_MALLOC(float64_t, vector.vlen);
00092 float64_t norm = get_pnorm (vector.vector, vector.vlen);
00093
00094 for (int32_t i=0; i<vector.vlen; i++)
00095 normed_vec[i]=vector.vector[i]/norm;
00096
00097 return SGVector<float64_t>(normed_vec,vector.vlen);
00098 }
00099
00100 void CPNorm::set_pnorm (double pnorm)
00101 {
00102 ASSERT (pnorm >= 1.0);
00103 m_p = pnorm;
00104 register_param ();
00105 }
00106
00107 double CPNorm::get_pnorm () const
00108 {
00109 return m_p;
00110 }
00111
00112 void CPNorm::register_param ()
00113 {
00114 m_parameters->add (&m_p, "norm", "P-norm parameter");
00115 }
00116
00117 inline float64_t CPNorm::get_pnorm (float64_t* vec, int32_t vec_len) const
00118 {
00119 float64_t norm = 0.0;
00120 if (m_p == 1.0)
00121 {
00122 for (int i = 0; i < vec_len; ++i)
00123 norm += fabs (vec[i]);
00124 }
00125 else if (m_p == 2.0)
00126 {
00127 norm = SGVector<float64_t>::twonorm(vec, vec_len);
00128 }
00129 else
00130 {
00131 norm = SGVector<float64_t>::qnorm(vec, vec_len, m_p);
00132 }
00133
00134 return norm;
00135 }