Class: GSLR::Ridge
Instance Attribute Summary
Attributes inherited from Model
Instance Method Summary collapse
- #fit(x, y) ⇒ Object
-
#initialize(alpha: 1.0, **options) ⇒ Ridge
constructor
A new instance of Ridge.
Methods inherited from Model
Constructor Details
#initialize(alpha: 1.0, **options) ⇒ Ridge
Returns a new instance of Ridge.
3 4 5 6 |
# File 'lib/gslr/ridge.rb', line 3 def initialize(alpha: 1.0, **) super(**) @alpha = alpha end |
Instance Method Details
#fit(x, y) ⇒ Object
8 9 10 11 12 13 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 |
# File 'lib/gslr/ridge.rb', line 8 def fit(x, y) if @fit_intercept # the intercept should not be regularized # so we need to center x and y # and exclude the intercept xc, x_offset, s1, s2 = centered_matrix(x) yc, y_offset = centered_vector(y) else xc, s1, s2 = set_matrix(x, intercept: false) yc = set_vector(y) end # allocate solution c = FFI.gsl_vector_alloc(s2) rnorm = Fiddle::Pointer.malloc(Fiddle::SIZEOF_DOUBLE) snorm = Fiddle::Pointer.malloc(Fiddle::SIZEOF_DOUBLE) work = FFI.gsl_multifit_linear_alloc(s1, s2) # fit FFI.gsl_multifit_linear_svd(xc, work) FFI.gsl_multifit_linear_solve(Math.sqrt(@alpha), xc, yc, c, rnorm.ref, snorm.ref, work) # read solution c_ptr = FFI.gsl_vector_ptr(c, 0) @coefficients = c_ptr[0, s2 * Fiddle::SIZEOF_DOUBLE].unpack("d*") @intercept = if @fit_intercept y_offset - x_offset.zip(@coefficients).map { |xii, c| xii * c }.sum else 0.0 end nil ensure FFI.gsl_matrix_free(xc) if xc FFI.gsl_vector_free(yc) if yc FFI.gsl_vector_free(c) if c FFI.gsl_multifit_linear_free(work) if work end |