Class: Prophet::StanBackend

Inherits:
Object
  • Object
show all
Defined in:
lib/prophet/stan_backend.rb

Instance Method Summary collapse

Constructor Details

#initialize(logger) ⇒ StanBackend

Returns a new instance of StanBackend.



3
4
5
6
# File 'lib/prophet/stan_backend.rb', line 3

def initialize(logger)
  @model = load_model
  @logger = logger
end

Instance Method Details

#fit(stan_init, stan_data, **kwargs) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/prophet/stan_backend.rb', line 14

def fit(stan_init, stan_data, **kwargs)
  stan_init, stan_data = prepare_data(stan_init, stan_data)

  if !kwargs[:inits] && kwargs[:init]
    kwargs[:inits] = prepare_data(kwargs.delete(:init), stan_data)[0]
  end

  kwargs[:algorithm] ||= stan_data["T"] < 100 ? "Newton" : "LBFGS"
  iterations = 10000

  stan_fit = nil
  begin
    stan_fit = @model.optimize(
      data: stan_data,
      inits: stan_init,
      iter: iterations,
      **kwargs
    )
  rescue => e
    if kwargs[:algorithm] != "Newton"
      @logger.warn "Optimization terminated abnormally. Falling back to Newton."
      kwargs[:algorithm] = "Newton"
      stan_fit = @model.optimize(
        data: stan_data,
        inits: stan_init,
        iter: iterations,
        **kwargs
      )
    else
      raise e
    end
  end

  params = stan_to_numo(stan_fit.column_names, Numo::NArray.asarray(stan_fit.optimized_params.values))
  params.each_key do |par|
    params[par] = params[par].reshape(1, *params[par].shape)
  end
  params
end

#load_modelObject

Raises:



8
9
10
11
12
# File 'lib/prophet/stan_backend.rb', line 8

def load_model
  model_file = File.expand_path("../../vendor/#{platform}/bin/prophet", __dir__)
  raise Error, "Platform not supported yet" unless File.exist?(model_file)
  CmdStan::Model.new(exe_file: model_file)
end

#sampling(stan_init, stan_data, samples, **kwargs) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/prophet/stan_backend.rb', line 54

def sampling(stan_init, stan_data, samples, **kwargs)
  stan_init, stan_data = prepare_data(stan_init, stan_data)

  if !kwargs[:inits] && kwargs[:init]
    kwargs[:inits] = prepare_data(kwargs.delete(:init), stan_data)[0]
  end

  kwargs[:chains] ||= 4
  kwargs[:warmup_iters] ||= samples / 2

  stan_fit = @model.sample(
    data: stan_data,
    inits: stan_init,
    sampling_iters: samples,
    **kwargs
  )
  res = Numo::NArray.asarray(stan_fit.sample)
  samples, c, columns = res.shape
  res = res.reshape(samples * c, columns)
  params = stan_to_numo(stan_fit.column_names, res)

  params.each_key do |par|
    s = params[par].shape

    if s[1] == 1
      params[par] = params[par].reshape(s[0])
    end

    if ["delta", "beta"].include?(par) && s.size < 2
      params[par] = params[par].reshape(-1, 1)
    end
  end

  params
end