spark-connect 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module SparkConnect
6
+ module ML
7
+ # Multiclass classification by one binary classifier per class, like
8
+ # `pyspark.ml.classification.OneVsRest`. Spark's server does not allowlist
9
+ # this meta-algorithm, so, as in PySpark, it runs on the client: one binary
10
+ # fit per class (on a relabelled copy of the data), and a transform that
11
+ # scores every binary model and picks the class with the highest score.
12
+ module Classification
13
+ # One-vs-rest reduction around a binary `classifier`.
14
+ class OneVsRest < Estimator
15
+ operator "org.apache.spark.ml.classification.OneVsRest"
16
+ model -> { OneVsRestModel }
17
+
18
+ param :classifier, :any, doc: "base binary classifier"
19
+ param :label_col, :string, default: "label", doc: "label column name"
20
+ param :features_col, :string, default: "features", doc: "features column name"
21
+ param :prediction_col, :string, default: "prediction", doc: "prediction column name"
22
+ param :weight_col, :string, doc: "weight column name; unset means every instance has weight 1.0"
23
+ param :parallelism, :int, default: 1, doc: "number of threads to use when running parallel algorithms (>= 1)"
24
+
25
+ # Fit one binary classifier per class, `max(label) + 1` of them.
26
+ #
27
+ # @param dataset [DataFrame]
28
+ # @param params [Hash, nil]
29
+ # @return [OneVsRestModel]
30
+ def fit(dataset, params = nil)
31
+ return copy(params).fit(dataset) if params && !params.empty?
32
+
33
+ label = get(:label_col)
34
+ features = get(:features_col)
35
+ prediction = get(:prediction_col)
36
+ base = get(:classifier)
37
+ weight = is_set?(:weight_col) && base.class.params.key?(:weight_col) ? get(:weight_col) : nil
38
+ num_classes = dataset.select(F.max(F.col(label)).alias("max_label")).collect.first["max_label"].to_i + 1
39
+
40
+ columns = [label, features, weight].compact
41
+ multiclass = dataset.select(*columns.map { |c| F.col(c) })
42
+ multiclass.cache
43
+ begin
44
+ models = Tuning::ValidatorSupport.run_parallel(Array(0...num_classes), get(:parallelism)) do |index|
45
+ binary_label = "mc2b$#{index}"
46
+ training = multiclass.with_column(binary_label,
47
+ F.when(F.col(label) == F.lit(index.to_f), 1.0).otherwise(0.0))
48
+ pmap = { base.param(:label_col) => binary_label, base.param(:features_col) => features,
49
+ base.param(:prediction_col) => prediction, }
50
+ pmap[base.param(:weight_col)] = weight if weight
51
+ base.fit(training, pmap)
52
+ end
53
+ ensure
54
+ multiclass.unpersist
55
+ end
56
+ OneVsRestModel.new(uid: uid, models: models).copy_values_from(self)
57
+ end
58
+
59
+ # @api private
60
+ def save_meta(path, overwrite:, session:)
61
+ Persistence.handle_overwrite(session, path, overwrite)
62
+ Persistence.write_metadata(session, path, self,
63
+ param_map: Persistence.extract_json_params(self, skip: ["classifier"]))
64
+ get(:classifier).save(File.join(path, "classifier"), overwrite: false, session: session)
65
+ nil
66
+ end
67
+
68
+ # @api private
69
+ def self.load_meta(path, session:)
70
+ meta = Persistence.read_metadata(session, path)
71
+ classifier = Persistence.load_any(session, File.join(path, "classifier"))
72
+ ovr = new(uid: meta.fetch("uid"), classifier: classifier)
73
+ Persistence.apply_params(ovr, meta.fetch("paramMap").except("classifier"))
74
+ ovr
75
+ end
76
+ end
77
+
78
+ # The fitted {OneVsRest}: one binary model per class. A row is labelled with
79
+ # the class whose model scores it highest.
80
+ class OneVsRestModel < Model
81
+ operator "org.apache.spark.ml.classification.OneVsRestModel"
82
+
83
+ param :classifier, :any, doc: "base binary classifier"
84
+ param :label_col, :string, default: "label", doc: "label column name"
85
+ param :features_col, :string, default: "features", doc: "features column name"
86
+ param :prediction_col, :string, default: "prediction", doc: "prediction column name"
87
+ param :raw_prediction_col, :string, default: "rawPrediction", doc: "raw prediction (confidence) column name"
88
+ param :weight_col, :string, doc: "weight column name"
89
+
90
+ # @return [Array<Model>] the binary models, one per class.
91
+ attr_reader :models
92
+
93
+ # @api private
94
+ def initialize(uid: nil, models: [], **values)
95
+ super(uid: uid, **values)
96
+ @models = models
97
+ end
98
+
99
+ # Score every class and label each row with the best one: the
100
+ # `rawPrediction` vector holds the per-class scores, and `prediction` is
101
+ # the index of the highest score. As PySpark does, the scores accumulate
102
+ # in an array column that is turned into the vector at the end.
103
+ #
104
+ # @param dataset [DataFrame]
105
+ # @param params [Hash, nil]
106
+ # @return [DataFrame]
107
+ def transform(dataset, params = nil)
108
+ return copy(params).transform(dataset) if params && !params.empty?
109
+
110
+ original = dataset.columns
111
+ acc = "mbc$acc#{SecureRandom.hex(8)}"
112
+ raw = get(:raw_prediction_col)
113
+ aggregated = dataset.with_column(acc, F.array.cast("array<double>"))
114
+ models.each do |model|
115
+ tmp = "mbc$tmp#{SecureRandom.hex(8)}"
116
+ scored = model.transform(aggregated).select(*(original + [raw, acc]))
117
+ appended = scored.with_column(tmp, F.call_function("array_append", F.col(acc),
118
+ Functions.vector_to_array(F.col(raw)).get_item(1)))
119
+ aggregated = appended.select(*(original + [tmp])).with_column_renamed(tmp, acc)
120
+ end
121
+ aggregated = aggregated.with_column(raw, Functions.array_to_vector(F.col(acc)))
122
+ # The index of the highest score: the first position of the maximum (0-based).
123
+ best = F.call_function("array_position", F.col(acc), F.call_function("array_max", F.col(acc))) - 1
124
+ aggregated = aggregated.with_column(get(:prediction_col), best.cast("double"))
125
+ aggregated.drop(acc)
126
+ end
127
+
128
+ # @api private
129
+ def save_meta(path, overwrite:, session:)
130
+ Persistence.handle_overwrite(session, path, overwrite)
131
+ Persistence.write_metadata(session, path, self,
132
+ param_map: Persistence.extract_json_params(self, skip: ["classifier"]),
133
+ extra: { "numClasses" => models.size })
134
+ get(:classifier).save(File.join(path, "classifier"), overwrite: false, session: session)
135
+ models.each_with_index do |model, i|
136
+ model.save(File.join(path, "model_#{i}"), overwrite: false, session: session)
137
+ end
138
+ nil
139
+ end
140
+
141
+ # @api private
142
+ def self.load_meta(path, session:)
143
+ meta = Persistence.read_metadata(session, path)
144
+ classifier = Persistence.load_any(session, File.join(path, "classifier"))
145
+ models = Array.new(meta.fetch("numClasses")) { |i| Persistence.load_any(session, File.join(path, "model_#{i}")) }
146
+ ovr = new(uid: meta.fetch("uid"), classifier: classifier, models: models)
147
+ Persistence.apply_params(ovr, meta.fetch("paramMap").except("classifier"))
148
+ ovr
149
+ end
150
+ end
151
+ end
152
+
153
+ # The class is also available at the ML level, as in PySpark's `pyspark.ml`.
154
+ OneVsRest = Classification::OneVsRest
155
+ OneVsRestModel = Classification::OneVsRestModel
156
+ end
157
+ end
@@ -0,0 +1,378 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module SparkConnect
6
+ module ML
7
+ # Marks a param that has no default value (Spark leaves it unset).
8
+ NO_DEFAULT = Object.new.tap do |o|
9
+ def o.inspect = "NO_DEFAULT"
10
+ o.freeze
11
+ end
12
+
13
+ # Default of a `seed` param: Spark's `HasSeed` default, the Java hash code of
14
+ # the concrete class name (`this.getClass.getName.hashCode.toLong`). It is
15
+ # resolved per class by {Param#default_for}.
16
+ SEED_DEFAULT = Object.new.tap do |o|
17
+ def o.inspect = "SEED_DEFAULT"
18
+ o.freeze
19
+ end
20
+
21
+ # A declared ML parameter. Params are declared on the operator classes with
22
+ # {Params.param}; the same {Param} object is shared by every instance of the
23
+ # class, and is what {Params#param} / ParamGridBuilder use as a key.
24
+ class Param
25
+ # @return [Class] the class that declares the param.
26
+ attr_reader :owner
27
+ # @return [Symbol] the Ruby (snake_case) name, e.g. `:reg_param`.
28
+ attr_reader :name
29
+ # @return [String] the camelCase name the Spark server uses, e.g. `"regParam"`.
30
+ attr_reader :spark_name
31
+ # @return [Symbol] the value type (see {ParamTypes}).
32
+ attr_reader :type
33
+ # @return [String, nil] the Spark doc string.
34
+ attr_reader :doc
35
+
36
+ # @api private
37
+ def initialize(owner, name, type, spark_name:, default:, doc:)
38
+ @owner = owner
39
+ @name = name
40
+ @type = type
41
+ @spark_name = spark_name
42
+ @default = default
43
+ @doc = doc
44
+ end
45
+
46
+ # @return [Boolean] whether Spark defines a default for this param.
47
+ def default?
48
+ !@default.equal?(NO_DEFAULT)
49
+ end
50
+
51
+ # @return [Object, nil] the default for the owner class (nil when there is none).
52
+ def default
53
+ default_for(owner)
54
+ end
55
+
56
+ # The default for an instance of `klass`: a `seed` default depends on the class.
57
+ # @param klass [Class]
58
+ # @return [Object, nil]
59
+ def default_for(klass)
60
+ return nil unless default?
61
+ return ML.java_string_hash(klass.operator || klass.name) if @default.equal?(SEED_DEFAULT)
62
+
63
+ @default
64
+ end
65
+
66
+ # @return [String]
67
+ def to_s = name.to_s
68
+
69
+ # @return [String]
70
+ def inspect = "#<SparkConnect::ML::Param #{owner&.name}##{name}>"
71
+ end
72
+
73
+ # Value coercion and validation per {Param} type.
74
+ module ParamTypes
75
+ INT_RANGE = (-(2**31)..((2**31) - 1))
76
+
77
+ TYPES = %i[any int long double boolean string string_array int_array double_array
78
+ double_array_array string_array_array vector matrix].freeze
79
+
80
+ module_function
81
+
82
+ # Validate and normalise `value` for a param of `type`.
83
+ #
84
+ # @param param [Param]
85
+ # @param value [Object]
86
+ # @return [Object] the normalised value
87
+ # @raise [IllegalArgumentError] when the value does not fit the param type
88
+ def coerce(param, value)
89
+ type = param.type
90
+ return value if type == :any
91
+ return value if value.nil? && type != :any # nil is rejected below for typed params
92
+
93
+ case type
94
+ when :int, :long then coerce_int(param, value)
95
+ when :double then coerce_double(param, value)
96
+ when :boolean then coerce_boolean(param, value)
97
+ when :string then coerce_string(param, value)
98
+ when :string_array then array_of(param, value) { |v| coerce_string(param, v) }
99
+ when :int_array then array_of(param, value) { |v| coerce_int(param, v) }
100
+ when :double_array then array_of(param, value) { |v| coerce_double(param, v) }
101
+ when :double_array_array
102
+ array_of(param, value) { |row| array_of(param, row) { |v| coerce_double(param, v) } }
103
+ when :string_array_array
104
+ array_of(param, value) { |row| array_of(param, row) { |v| coerce_string(param, v) } }
105
+ when :vector then coerce_vector(param, value)
106
+ when :matrix then coerce_matrix(param, value)
107
+ else
108
+ raise IllegalArgumentError, "unknown param type #{type.inspect} for #{param.name}"
109
+ end
110
+ end
111
+
112
+ def coerce_int(param, value)
113
+ raise IllegalArgumentError, "#{param.name} expects an Integer, got #{value.inspect}" unless value.is_a?(Integer)
114
+
115
+ value
116
+ end
117
+
118
+ def coerce_double(param, value)
119
+ raise IllegalArgumentError, "#{param.name} expects a Numeric, got #{value.inspect}" unless value.is_a?(Numeric)
120
+
121
+ value.to_f
122
+ end
123
+
124
+ def coerce_boolean(param, value)
125
+ raise IllegalArgumentError, "#{param.name} expects true or false, got #{value.inspect}" unless [true, false].include?(value)
126
+
127
+ value
128
+ end
129
+
130
+ def coerce_string(param, value)
131
+ raise IllegalArgumentError, "#{param.name} expects a String, got #{value.inspect}" unless value.is_a?(String) || value.is_a?(Symbol)
132
+
133
+ value.to_s
134
+ end
135
+
136
+ def array_of(param, value, &)
137
+ raise IllegalArgumentError, "#{param.name} expects an Array, got #{value.inspect}" unless value.is_a?(Array)
138
+
139
+ value.map(&)
140
+ end
141
+
142
+ def coerce_vector(param, value)
143
+ case value
144
+ when Linalg::Vector then value
145
+ when Array then Linalg::Vectors.dense(value.map { |v| coerce_double(param, v) })
146
+ else raise IllegalArgumentError, "#{param.name} expects a Vector, got #{value.inspect}"
147
+ end
148
+ end
149
+
150
+ def coerce_matrix(param, value)
151
+ return value if value.is_a?(Linalg::Matrix)
152
+
153
+ raise IllegalArgumentError, "#{param.name} expects a Matrix, got #{value.inspect}"
154
+ end
155
+ end
156
+
157
+ # Behaviour shared by every ML operator (estimators, transformers, models,
158
+ # evaluators, pipelines): declared params, values, defaults, copies and a
159
+ # unique `uid`, like PySpark's `pyspark.ml.param.Params`.
160
+ class Params
161
+ class << self
162
+ # @!visibility private
163
+ def own_params
164
+ @own_params ||= {}
165
+ end
166
+
167
+ # All params visible on this class, including inherited ones.
168
+ #
169
+ # @return [Hash{Symbol => Param}]
170
+ def params
171
+ inherited = superclass.respond_to?(:params) ? superclass.params : {}
172
+ inherited.merge(own_params)
173
+ end
174
+
175
+ # Declare a param. Defines the getter `name` (returns the value or the
176
+ # default) and the chainable setter `set_name(value)`.
177
+ #
178
+ # @param name [Symbol] the Ruby name, snake_case, e.g. `:max_iter`.
179
+ # @param type [Symbol] one of {ParamTypes::TYPES}.
180
+ # @param default [Object] the Spark default; omit for params without one.
181
+ # @param spark_name [String, nil] the Spark name; defaults to camelCase of `name`.
182
+ # @param doc [String, nil] the doc string.
183
+ # @return [Param]
184
+ def param(name, type = :any, default: NO_DEFAULT, spark_name: nil, doc: nil)
185
+ name = name.to_sym
186
+ raise ArgumentError, "unknown param type #{type.inspect}" unless ParamTypes::TYPES.include?(type)
187
+
188
+ spark = spark_name || ML.camelize(name)
189
+ declared = Param.new(self, name, type, spark_name: spark, default: default, doc: doc)
190
+ own_params[name] = declared
191
+ define_method(name) { get(declared) }
192
+ define_method(:"set_#{name}") { |value| set(declared, value) }
193
+ declared
194
+ end
195
+
196
+ # The Spark operator (fully qualified Scala class) this Ruby class wraps.
197
+ # @param name [String, nil] set when declaring; omit to read.
198
+ # @return [String, nil]
199
+ def operator(name = nil)
200
+ return @operator = name if name
201
+
202
+ @operator || (superclass.respond_to?(:operator) ? superclass.operator : nil)
203
+ end
204
+
205
+ # @return [String] a fresh uid, e.g. `"LogisticRegression_1a2b3c4d5e6f"`.
206
+ def random_uid
207
+ "#{name.to_s.split('::').last || 'Params'}_#{SecureRandom.hex(6)}"
208
+ end
209
+ end
210
+
211
+ # @return [String] the unique id of this instance.
212
+ attr_reader :uid
213
+
214
+ # @param uid [String, nil] an explicit uid, otherwise a random one.
215
+ # @param values [Hash] initial param values, e.g. `max_iter: 10`.
216
+ def initialize(uid: nil, **values)
217
+ @uid = uid || self.class.random_uid
218
+ @param_map = {}
219
+ set_params(**values)
220
+ end
221
+
222
+ # @return [Array<Param>] every param of this instance, sorted by name.
223
+ def params
224
+ self.class.params.values.sort_by(&:name)
225
+ end
226
+
227
+ # Look up a declared param.
228
+ #
229
+ # @param name [Symbol, String, Param]
230
+ # @return [Param]
231
+ # @raise [IllegalArgumentError] when the param does not exist on this class
232
+ def param(name)
233
+ return name if name.is_a?(Param) && self.class.params.key?(name.name)
234
+
235
+ self.class.params.fetch(name.to_sym) do
236
+ raise IllegalArgumentError, "#{self.class.name.split('::').last} does not have a param named #{name}."
237
+ end
238
+ end
239
+
240
+ # Set one param. Returns `self`.
241
+ #
242
+ # @param name [Symbol, String, Param]
243
+ # @param value [Object]
244
+ # @return [self]
245
+ def set(name, value)
246
+ declared = param(name)
247
+ raise IllegalArgumentError, "#{declared.name} must not be nil" if value.nil?
248
+
249
+ @param_map[declared] = ParamTypes.coerce(declared, value)
250
+ self
251
+ end
252
+
253
+ # Set several params from keyword arguments, like PySpark's `setParams`.
254
+ # @return [self]
255
+ def set_params(**values)
256
+ values.each { |k, v| set(k, v) }
257
+ self
258
+ end
259
+
260
+ # The value of a param: the explicitly set value, else the default.
261
+ #
262
+ # @param name [Symbol, String, Param]
263
+ # @return [Object]
264
+ # @raise [IllegalArgumentError] when neither is available
265
+ def get(name)
266
+ declared = param(name)
267
+ return @param_map[declared] if @param_map.key?(declared)
268
+ return declared.default_for(self.class) if declared.default?
269
+
270
+ raise IllegalArgumentError, "Failed to find a default value for #{declared.name}"
271
+ end
272
+
273
+ # @return [Boolean] whether the param was set explicitly.
274
+ def is_set?(name)
275
+ @param_map.key?(param(name))
276
+ end
277
+
278
+ # @return [Boolean] whether the param has a value, set or default.
279
+ def is_defined?(name)
280
+ declared = param(name)
281
+ @param_map.key?(declared) || declared.default?
282
+ end
283
+
284
+ # Remove an explicit value, so the default applies again.
285
+ # @return [self]
286
+ def clear(name)
287
+ @param_map.delete(param(name))
288
+ self
289
+ end
290
+
291
+ # The explicitly set params only (what gets sent to the server).
292
+ #
293
+ # @return [Hash{Param => Object}]
294
+ def explicit_param_map
295
+ @param_map.dup
296
+ end
297
+
298
+ # Every param with a value: defaults, overridden by explicit values, then by `extra`.
299
+ #
300
+ # @param extra [Hash{Param, Symbol, String => Object}]
301
+ # @return [Hash{Param => Object}]
302
+ def extract_param_map(extra = {})
303
+ map = {}
304
+ params.each do |declared|
305
+ map[declared] = declared.default_for(self.class) if declared.default?
306
+ end
307
+ map.merge!(@param_map)
308
+ extra.each { |k, v| map[param(k)] = ParamTypes.coerce(param(k), v) if self.class.params.key?(key_name(k)) }
309
+ map
310
+ end
311
+
312
+ # A human-readable description of every param, one line each.
313
+ #
314
+ # @return [String]
315
+ def explain_params
316
+ params.map do |declared|
317
+ parts = ["#{declared.name}: #{declared.doc}".rstrip]
318
+ if is_set?(declared.name)
319
+ parts << "(default: #{declared.default.inspect}, current: #{@param_map[declared].inspect})" if declared.default?
320
+ parts << "(current: #{@param_map[declared].inspect})" unless declared.default?
321
+ elsif declared.default?
322
+ parts << "(default: #{declared.default.inspect})"
323
+ end
324
+ parts.join(" ")
325
+ end.join("\n")
326
+ end
327
+
328
+ # A copy of this instance with the same uid, explicit values and `extra`
329
+ # applied on top (PySpark's `copy(extra)`).
330
+ #
331
+ # @param extra [Hash]
332
+ # @return [Params]
333
+ def copy(extra = {})
334
+ that = dup
335
+ that.instance_variable_set(:@param_map, @param_map.dup)
336
+ extra.each do |k, v|
337
+ that.set(k, v) if self.class.params.key?(key_name(k))
338
+ end
339
+ that
340
+ end
341
+
342
+ # Copy the explicit values of `other` that this class also declares.
343
+ # @api private
344
+ # @return [self]
345
+ def copy_values_from(other)
346
+ other.explicit_param_map.each do |declared, value|
347
+ @param_map[param(declared.name)] = value if self.class.params.key?(declared.name)
348
+ end
349
+ self
350
+ end
351
+
352
+ # @api private
353
+ def key_name(key)
354
+ key.is_a?(Param) ? key.name : key.to_sym
355
+ end
356
+
357
+ # @return [String]
358
+ def inspect = "#<#{self.class.name} uid=#{uid}>"
359
+ end
360
+
361
+ # Java's `String#hashCode` of `str` (as a signed 32-bit integer).
362
+ # @param str [String]
363
+ # @return [Integer]
364
+ def self.java_string_hash(str)
365
+ hash = 0
366
+ str.encode("UTF-16BE").unpack("n*").each { |unit| hash = ((31 * hash) + unit) & 0xFFFFFFFF }
367
+ hash >= 0x80000000 ? hash - 0x100000000 : hash
368
+ end
369
+
370
+ # Converts a Ruby name to the camelCase name Spark uses (`max_iter` -> `maxIter`).
371
+ # @param name [String, Symbol]
372
+ # @return [String]
373
+ def self.camelize(name)
374
+ first, *rest = name.to_s.split("_")
375
+ [first, *rest.map(&:capitalize)].join
376
+ end
377
+ end
378
+ end