35 #ifndef SHARK_MODELS_KERNELS_GAUSSIAN_RBF_KERNEL_H 36 #define SHARK_MODELS_KERNELS_GAUSSIAN_RBF_KERNEL_H 49 template<
class InputType=RealVector>
55 struct InternalState:
public State{
59 void resize(std::size_t sizeX1, std::size_t sizeX2){
60 norm2.resize(sizeX1, sizeX2);
61 expNorm.resize(sizeX1, sizeX2);
79 {
return "GaussianRbfKernel"; }
92 SHARK_RUNTIME_CHECK(newParameters.size() == 1,
"[GaussianRbfKernel::setParameterVector] invalid size of parameter vector");
94 m_gamma = std::exp(newParameters(0));
97 SHARK_RUNTIME_CHECK(newParameters(0) > 0.0,
"[GaussianRbfKernel::setParameterVector] gamma must be positive");
113 return 1. / std::sqrt(2 *
m_gamma);
142 return boost::shared_ptr<State>(
new InternalState());
149 double eval(ConstInputReference x1, ConstInputReference x2)
const{
151 double norm2 = distanceSqr(x2, x1);
152 double exponential = std::exp(-
m_gamma * norm2);
160 void eval(ConstBatchInputReference batchX1, ConstBatchInputReference batchX2, RealMatrix& result,
State& state)
const{
161 SIZE_CHECK(batchX1.size2() == batchX2.size2());
162 std::size_t sizeX1=batchX1.size1();
163 std::size_t sizeX2=batchX2.size1();
166 InternalState& s=state.
toState<InternalState>();
167 s.resize(sizeX1,sizeX2);
170 noalias(s.norm2)=distanceSqr(batchX1,batchX2);
171 noalias(s.expNorm)=exp(-
m_gamma*s.norm2);
175 void eval(ConstBatchInputReference batchX1, ConstBatchInputReference batchX2, RealMatrix& result)
const{
176 SIZE_CHECK(batchX1.size2() == batchX2.size2());
177 result = distanceSqr(batchX1,batchX2);
178 noalias(result)=exp(-
m_gamma*result);
182 ConstBatchInputReference batchX1,
183 ConstBatchInputReference batchX2,
184 RealMatrix
const& coefficients,
188 std::size_t sizeX1=batchX1.size1();
189 std::size_t sizeX2=batchX2.size1();
190 InternalState
const& s = state.
toState<InternalState>();
193 SIZE_CHECK(batchX1.size2() == batchX2.size2());
200 gradient(0)= - sum(coefficients *s.expNorm * s.norm2);
206 ConstBatchInputReference batchX1,
207 ConstBatchInputReference batchX2,
208 RealMatrix
const& coefficientsX2,
210 BatchInputType& gradient
212 std::size_t sizeX1=batchX1.size1();
213 std::size_t sizeX2=batchX2.size1();
214 InternalState
const& s = state.
toState<InternalState>();
217 SIZE_CHECK(batchX1.size2() == batchX2.size2());
223 gradient.resize(sizeX1,batchX1.size2());
224 RealMatrix W = coefficientsX2*s.expNorm;
225 noalias(gradient) = prod(W,batchX2);
226 RealVector columnSum = sum_columns(coefficientsX2*s.expNorm);
228 for(std::size_t i = 0; i != sizeX1; ++i){
229 noalias(row(gradient,i)) -= columnSum(i) * row(batchX1,i);