Module: SVMKit::PairwiseMetric
- Defined in:
- lib/svmkit/pairwise_metric.rb
Overview
Module for calculating pairwise distances, similarities, and kernels.
Class Method Summary collapse
-
.euclidean_distance(x, y = nil) ⇒ Numo::DFloat
Calculate the pairwise euclidean distances between x and y.
-
.linear_kernel(x, y = nil) ⇒ Numo::DFloat
Calculate the linear kernel between x and y.
-
.polynomial_kernel(x, y = nil, degree = 3, gamma = nil, coef = 1) ⇒ Numo::DFloat
Calculate the polynomial kernel between x and y.
-
.rbf_kernel(x, y = nil, gamma = nil) ⇒ Numo::DFloat
Calculate the rbf kernel between x and y.
-
.sigmoid_kernel(x, y = nil, gamma = nil, coef = 1) ⇒ Numo::DFloat
Calculate the sigmoid kernel between x and y.
Class Method Details
.euclidean_distance(x, y = nil) ⇒ Numo::DFloat
Calculate the pairwise euclidean distances between x and y.
12 13 14 15 16 17 18 19 20 21 |
# File 'lib/svmkit/pairwise_metric.rb', line 12 def euclidean_distance(x, y = nil) y = x if y.nil? sum_x_vec = (x**2).sum(1) sum_y_vec = (y**2).sum(1) dot_xy_mat = x.dot(y.transpose) distance_matrix = dot_xy_mat * -2.0 + sum_x_vec.tile(y.shape[0], 1).transpose + sum_y_vec.tile(x.shape[0], 1) Numo::NMath.sqrt(distance_matrix.abs) end |
.linear_kernel(x, y = nil) ⇒ Numo::DFloat
Calculate the linear kernel between x and y.
41 42 43 44 |
# File 'lib/svmkit/pairwise_metric.rb', line 41 def linear_kernel(x, y = nil) y = x if y.nil? x.dot(y.transpose) end |
.polynomial_kernel(x, y = nil, degree = 3, gamma = nil, coef = 1) ⇒ Numo::DFloat
Calculate the polynomial kernel between x and y.
54 55 56 57 58 |
# File 'lib/svmkit/pairwise_metric.rb', line 54 def polynomial_kernel(x, y = nil, degree = 3, gamma = nil, coef = 1) y = x if y.nil? gamma ||= 1.0 / x.shape[1] (x.dot(y.transpose) * gamma + coef)**degree end |
.rbf_kernel(x, y = nil, gamma = nil) ⇒ Numo::DFloat
Calculate the rbf kernel between x and y.
29 30 31 32 33 34 |
# File 'lib/svmkit/pairwise_metric.rb', line 29 def rbf_kernel(x, y = nil, gamma = nil) y = x if y.nil? gamma ||= 1.0 / x.shape[1] distance_matrix = euclidean_distance(x, y) Numo::NMath.exp((distance_matrix**2) * -gamma) end |
.sigmoid_kernel(x, y = nil, gamma = nil, coef = 1) ⇒ Numo::DFloat
Calculate the sigmoid kernel between x and y.
67 68 69 70 71 |
# File 'lib/svmkit/pairwise_metric.rb', line 67 def sigmoid_kernel(x, y = nil, gamma = nil, coef = 1) y = x if y.nil? gamma ||= 1.0 / x.shape[1] Numo::NMath.tanh(x.dot(y.transpose) * gamma + coef) end |