@@ -12,6 +12,7 @@ def initialize(params: nil, train_set: nil, model_file: nil, model_str: nil)
1212 create_handle do |handle |
1313 safe_call FFI . LGBM_BoosterCreateFromModelfile ( model_file , out_num_iterations , handle )
1414 end
15+ @pandas_categorical = load_pandas_categorical ( file_name : model_file )
1516 else
1617 params ||= { }
1718 set_verbosity ( params )
@@ -96,6 +97,7 @@ def model_from_string(model_str)
9697 create_handle do |handle |
9798 safe_call FFI . LGBM_BoosterLoadModelFromString ( model_str , out_num_iterations , handle )
9899 end
100+ @pandas_categorical = load_pandas_categorical ( model_str : model_str )
99101 @cached_feature_name = nil
100102 self
101103 end
@@ -235,5 +237,48 @@ def feature_importance_type_mapper(importance_type)
235237 -1
236238 end
237239 end
240+
241+ def load_pandas_categorical ( file_name : nil , model_str : nil )
242+ pandas_key = "pandas_categorical:"
243+ offset = -pandas_key . length
244+ if !file_name . nil?
245+ max_offset = -File . size ( file_name )
246+ lines = [ ]
247+ File . open ( file_name , "rb" ) do |f |
248+ loop do
249+ offset = [ offset , max_offset ] . max
250+ f . seek ( offset , IO ::SEEK_END )
251+ lines = f . readlines
252+ if lines . length >= 2
253+ break
254+ end
255+ offset *= 2
256+ end
257+ end
258+ last_line = lines [ -1 ] . strip
259+ if !last_line . start_with? ( pandas_key )
260+ last_line = lines [ -2 ] . strip
261+ end
262+ elsif !model_str . nil?
263+ idx = model_str [ ..offset ] . rindex ( "\n " )
264+ last_line = model_str [ idx ..] . strip
265+ end
266+ if last_line . start_with? ( pandas_key )
267+ JSON . parse ( last_line [ pandas_key . length ..] )
268+ end
269+ end
270+
271+ def loaded_param
272+ buffer_len = 1 << 20
273+ out_len = ::FFI ::MemoryPointer . new ( :int64 )
274+ out_str = ::FFI ::MemoryPointer . new ( :char , buffer_len )
275+ safe_call FFI . LGBM_BoosterGetLoadedParam ( @handle , buffer_len , out_len , out_str )
276+ actual_len = out_len . read_int64
277+ if actual_len > buffer_len
278+ out_str = ::FFI ::MemoryPointer . new ( :char , actual_len )
279+ safe_call FFI . LGBM_BoosterGetLoadedParam ( @handle , actual_len , out_len , out_str )
280+ end
281+ JSON . parse ( out_str . read_string )
282+ end
238283 end
239284end
0 commit comments