Module: Tools::DataMethods

Included in:
LinearRegression, Perceptron, RubyML
Defined in:
lib/rubyml/tools.rb

Overview

Methods for loading and manipulating data.

Instance Method Summary collapse

Instance Method Details

#bias_trick(x) ⇒ Object



28
29
30
31
32
# File 'lib/rubyml/tools.rb', line 28

def bias_trick(x)
  ones = Matrix.columns([[1] * x.row_count])
  x_bias = ones.hstack(x)
  x_bias
end

#load_data(file, text = false) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/rubyml/tools.rb', line 7

def load_data(file, text = false)
  mat = []
  File.foreach(file) do |f|
    mat << f.split(',').map { |i| text ? String(i).chomp : Float(i) }
  end
  Matrix.rows(mat)
end

#mat_to_array(data) ⇒ Object



22
23
24
25
26
# File 'lib/rubyml/tools.rb', line 22

def mat_to_array(data)
  arr = []
  data.each { |e| arr << e }
  arr
end

#plot(fx, fy, px, py) ⇒ Object



44
45
46
47
48
49
# File 'lib/rubyml/tools.rb', line 44

def plot(fx, fy, px, py)
  g = Gruff::Scatter.new(800)
  g.data(:data, px, py)
  g.data(:fit, fx, fy)
  g.write('scatter.png')
end

#plot_function(px, py, theta) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/rubyml/tools.rb', line 34

def plot_function(px, py, theta)
  fx = []
  fy = []
  1000.times do |i|
    fx << (px[0] + (px[-1] - px[0]) * Float(i) / 1000.0)
    fy << (fx[-1] * theta[1] + theta[0])
  end
  plot(fx, fy, px, py)
end

#separate_data(data) ⇒ Object



15
16
17
18
19
20
# File 'lib/rubyml/tools.rb', line 15

def separate_data(data)
  col_vec = data.column_vectors
  y = Matrix.columns([col_vec.pop])
  x = Matrix.columns(col_vec).collect { |e| Float(e) }
  [x, y]
end