Class: Statsample::FitModel

Inherits:
Object show all
Defined in:
lib/statsample/formula/fit_model.rb

Overview

Class for performing regression

Instance Method Summary collapse

Constructor Details

#initialize(formula, df, opts = {}) ⇒ FitModel

Returns a new instance of FitModel.



6
7
8
9
10
# File 'lib/statsample/formula/fit_model.rb', line 6

def initialize(formula, df, opts = {})
  @formula = FormulaWrapper.new formula, df
  @df = df
  @opts = opts
end

Instance Method Details

#canonicalize_df(orig_df) ⇒ Object



30
31
32
33
34
35
# File 'lib/statsample/formula/fit_model.rb', line 30

def canonicalize_df(orig_df)
  tokens = @formula.canonical_tokens
  tokens.shift if tokens.first.value == '1'
  df = tokens.map { |t| t.to_df orig_df }.reduce(&:merge)
  df
end

#df_for_prediction(df) ⇒ Object



20
21
22
# File 'lib/statsample/formula/fit_model.rb', line 20

def df_for_prediction df
  canonicalize_df(df)
end

#df_for_regressionObject



24
25
26
27
28
# File 'lib/statsample/formula/fit_model.rb', line 24

def df_for_regression
  df = canonicalize_df(@df)
  df[@formula.y.value] = @df[@formula.y.value]
  df        
end

#fit_modelObject



37
38
39
40
41
42
43
44
# File 'lib/statsample/formula/fit_model.rb', line 37

def fit_model
  # TODO: Add support for inclusion/exclusion of intercept
  @model = Statsample::Regression.multiple(
    df_for_regression,
    @formula.y.value,
    @opts
  )
end

#modelObject



12
13
14
# File 'lib/statsample/formula/fit_model.rb', line 12

def model
  @model || fit_model
end

#predict(new_data) ⇒ Object



16
17
18
# File 'lib/statsample/formula/fit_model.rb', line 16

def predict(new_data)
  model.predict(df_for_prediction(new_data))
end