Class: Xgb::Regressor

Inherits:
Object
  • Object
show all
Defined in:
lib/xgb/regressor.rb

Instance Method Summary collapse

Constructor Details

#initialize(max_depth: 3, learning_rate: 0.1, n_estimators: 100, objective: "reg:squarederror", importance_type: "gain") ⇒ Regressor

Returns a new instance of Regressor.



3
4
5
6
7
8
9
10
11
# File 'lib/xgb/regressor.rb', line 3

def initialize(max_depth: 3, learning_rate: 0.1, n_estimators: 100, objective: "reg:squarederror", importance_type: "gain")
  @params = {
    max_depth: max_depth,
    objective: objective,
    learning_rate: learning_rate
  }
  @n_estimators = n_estimators
  @importance_type = importance_type
end

Instance Method Details

#feature_importancesObject



32
33
34
35
36
37
# File 'lib/xgb/regressor.rb', line 32

def feature_importances
  score = @booster.score(importance_type: @importance_type)
  scores = @booster.feature_names.map { |k| score[k] || 0.0 }
  total = scores.sum.to_f
  scores.map { |s| s / total }
end

#fit(x, y) ⇒ Object



13
14
15
16
17
# File 'lib/xgb/regressor.rb', line 13

def fit(x, y)
  dtrain = DMatrix.new(x, label: y)
  @booster = Xgb.train(@params, dtrain, num_boost_round: @n_estimators)
  nil
end

#load_model(fname) ⇒ Object



28
29
30
# File 'lib/xgb/regressor.rb', line 28

def load_model(fname)
  @booster = Booster.new(params: @params, model_file: fname)
end

#predict(data) ⇒ Object



19
20
21
22
# File 'lib/xgb/regressor.rb', line 19

def predict(data)
  dmat = DMatrix.new(data)
  @booster.predict(dmat)
end

#save_model(fname) ⇒ Object



24
25
26
# File 'lib/xgb/regressor.rb', line 24

def save_model(fname)
  @booster.save_model(fname)
end