Module: Hanny::Utils

Defined in:
lib/hanny/utils.rb

Overview

This module consists of utility methods.

Class Method Summary collapse

Class Method Details

.euclidean_distance(x, y = nil) ⇒ Numo::DFloat

Calculate pairwise euclidean distances between x and y.

Parameters:

  • x (Numo::DFloat)

    (shape: [n_samples_x, n_features])

  • y (Numo::DFloat) (defaults to: nil)

    (shape: [n_samples_y, n_features])

Returns:

  • (Numo::DFloat)

    (shape: [n_samples_x, n_samples_x] or [n_samples_x, n_samples_y] if y is given)



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/hanny/utils.rb', line 11

def euclidean_distance(x, y = nil)
  y = x if y.nil?
  x = Numo::DFloat[x] if x.shape[1].nil?
  y = Numo::DFloat[y] if y.shape[1].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

.rand_normal(shape, rng, mu = 0.0, sigma = 1.0) ⇒ Numo::DFloat

Generate a normal random matrix with random number generator.

Parameters:

  • shape (Array<Integer>)

    The size of random matrix.

  • rng (Random)

    The random number generator

Returns:

  • (Numo::DFloat)

    The generated normal random matrix.



37
38
39
40
41
# File 'lib/hanny/utils.rb', line 37

def rand_normal(shape, rng, mu = 0.0, sigma = 1.0)
  a = rand_uniform(shape, rng)
  b = rand_uniform(shape, rng)
  (Numo::NMath.sqrt(Numo::NMath.log(a) * -2.0) * Numo::NMath.sin(b * 2.0 * Math::PI)) * sigma + mu
end

.rand_uniform(shape, rng) ⇒ Numo::DFloat

Generate a uniform random matrix with random number generator.

Parameters:

  • shape (Array<Integer>)

    The size of random matrix.

  • rng (Random)

    The random number generator

Returns:

  • (Numo::DFloat)

    The generated uniform random matrix.



28
29
30
31
# File 'lib/hanny/utils.rb', line 28

def rand_uniform(shape, rng)
  rnd_vals = Array.new(shape.inject(:*)) { rng.rand }
  Numo::DFloat.asarray(rnd_vals).reshape(shape[0], shape[1])
end