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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +39 -1
- data/README.md +5 -3
- data/lib/spark_connect/arrow.rb +5 -1
- data/lib/spark_connect/client.rb +3 -1
- data/lib/spark_connect/data_frame.rb +2 -1
- data/lib/spark_connect/ml/base.rb +433 -0
- data/lib/spark_connect/ml/classification.rb +444 -0
- data/lib/spark_connect/ml/clustering.rb +296 -0
- data/lib/spark_connect/ml/evaluation.rb +120 -0
- data/lib/spark_connect/ml/feature.rb +563 -0
- data/lib/spark_connect/ml/feature_transformers.rb +200 -0
- data/lib/spark_connect/ml/fpm.rb +58 -0
- data/lib/spark_connect/ml/functions.rb +47 -0
- data/lib/spark_connect/ml/linalg.rb +336 -0
- data/lib/spark_connect/ml/one_vs_rest.rb +157 -0
- data/lib/spark_connect/ml/params.rb +378 -0
- data/lib/spark_connect/ml/persistence.rb +247 -0
- data/lib/spark_connect/ml/pipeline.rb +115 -0
- data/lib/spark_connect/ml/recommendation.rb +56 -0
- data/lib/spark_connect/ml/regression.rb +289 -0
- data/lib/spark_connect/ml/rpc.rb +244 -0
- data/lib/spark_connect/ml/serialize.rb +211 -0
- data/lib/spark_connect/ml/stat.rb +127 -0
- data/lib/spark_connect/ml/tuning.rb +501 -0
- data/lib/spark_connect/ml.rb +62 -0
- data/lib/spark_connect/version.rb +1 -1
- data/lib/spark_connect.rb +1 -0
- metadata +22 -2
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SparkConnect
|
|
4
|
+
module ML
|
|
5
|
+
# Feature transformers (`org.apache.spark.ml.feature`) that are not models.
|
|
6
|
+
#
|
|
7
|
+
# Defaults are Spark 4.3.0's `setDefault` values. Params that Spark leaves
|
|
8
|
+
# unset, or that Spark derives at run time (`outputCol` defaults to
|
|
9
|
+
# `<uid>__output`, `stopWords` to the English list, `locale` to the JVM
|
|
10
|
+
# locale), are declared without a `default:`.
|
|
11
|
+
module FeatureTransformers
|
|
12
|
+
# Discrete cosine transform of a vector (`org.apache.spark.ml.feature.DCT`).
|
|
13
|
+
class DCT < Transformer
|
|
14
|
+
operator "org.apache.spark.ml.feature.DCT"
|
|
15
|
+
|
|
16
|
+
param :inverse, :boolean, default: false, doc: "whether to perform the inverse DCT (true) or forward DCT (false)"
|
|
17
|
+
param :input_col, :string, doc: "input column name"
|
|
18
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# Converts an array of strings into an array of n-grams (`NGram`).
|
|
22
|
+
class NGram < Transformer
|
|
23
|
+
operator "org.apache.spark.ml.feature.NGram"
|
|
24
|
+
|
|
25
|
+
param :n, :int, default: 2, doc: "number of elements per n-gram (>= 1)"
|
|
26
|
+
param :input_col, :string, doc: "input column name"
|
|
27
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Normalizes vectors to unit p-norm (`Normalizer`).
|
|
31
|
+
class Normalizer < Transformer
|
|
32
|
+
operator "org.apache.spark.ml.feature.Normalizer"
|
|
33
|
+
|
|
34
|
+
param :p, :double, default: 2.0, doc: "the p norm value (>= 1)"
|
|
35
|
+
param :input_col, :string, doc: "input column name"
|
|
36
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Multiplies the features of several columns together (`Interaction`).
|
|
40
|
+
class Interaction < Transformer
|
|
41
|
+
operator "org.apache.spark.ml.feature.Interaction"
|
|
42
|
+
|
|
43
|
+
param :input_cols, :string_array, spark_name: "inputCols", doc: "input column names"
|
|
44
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Thresholds numerical features to binary values (`Binarizer`).
|
|
48
|
+
class Binarizer < Transformer
|
|
49
|
+
operator "org.apache.spark.ml.feature.Binarizer"
|
|
50
|
+
|
|
51
|
+
param :threshold, :double, default: 0.0, doc: "values above the threshold map to 1.0, others to 0.0"
|
|
52
|
+
param :thresholds, :double_array, doc: "per-column thresholds for multi-column binarization"
|
|
53
|
+
param :input_col, :string, doc: "input column name"
|
|
54
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
55
|
+
param :input_cols, :string_array, doc: "input column names (multi-column mode)"
|
|
56
|
+
param :output_cols, :string_array, doc: "output column names (multi-column mode)"
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Maps continuous columns to bucket indices given split points (`Bucketizer`).
|
|
60
|
+
class Bucketizer < Transformer
|
|
61
|
+
operator "org.apache.spark.ml.feature.Bucketizer"
|
|
62
|
+
|
|
63
|
+
param :splits, :double_array, doc: "split points for mapping continuous features into buckets"
|
|
64
|
+
param :splits_array, :double_array_array, spark_name: "splitsArray",
|
|
65
|
+
doc: "split points per input column (multi-column mode)"
|
|
66
|
+
param :input_col, :string, doc: "input column name"
|
|
67
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
68
|
+
param :input_cols, :string_array, doc: "input column names (multi-column mode)"
|
|
69
|
+
param :output_cols, :string_array, doc: "output column names (multi-column mode)"
|
|
70
|
+
param :handle_invalid, :string, default: "error", spark_name: "handleInvalid",
|
|
71
|
+
doc: "how to handle NaN and out-of-range values: error, skip or keep"
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Merges several columns into one vector column (`VectorAssembler`).
|
|
75
|
+
class VectorAssembler < Transformer
|
|
76
|
+
operator "org.apache.spark.ml.feature.VectorAssembler"
|
|
77
|
+
|
|
78
|
+
param :input_cols, :string_array, doc: "input column names"
|
|
79
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
80
|
+
param :handle_invalid, :string, default: "error", spark_name: "handleInvalid",
|
|
81
|
+
doc: "how to handle invalid entries: error, skip or keep"
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Selects a subset of the elements of a vector column (`VectorSlicer`).
|
|
85
|
+
class VectorSlicer < Transformer
|
|
86
|
+
operator "org.apache.spark.ml.feature.VectorSlicer"
|
|
87
|
+
|
|
88
|
+
param :indices, :int_array, default: [].freeze, doc: "indices to take from the input vector"
|
|
89
|
+
param :names, :string_array, default: [].freeze, doc: "names of the features to take from the input vector"
|
|
90
|
+
param :input_col, :string, doc: "input column name"
|
|
91
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# Adds the vector size to a column's metadata so it can be used downstream (`VectorSizeHint`).
|
|
95
|
+
class VectorSizeHint < Transformer
|
|
96
|
+
operator "org.apache.spark.ml.feature.VectorSizeHint"
|
|
97
|
+
|
|
98
|
+
param :size, :int, doc: "size of the vectors in the column (>= 0)"
|
|
99
|
+
param :input_col, :string, doc: "input column name"
|
|
100
|
+
param :handle_invalid, :string, default: "error", spark_name: "handleInvalid",
|
|
101
|
+
doc: "how to handle invalid entries: error, skip or optimistic"
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# Splits a string column into lowercase tokens on whitespace (`Tokenizer`).
|
|
105
|
+
class Tokenizer < Transformer
|
|
106
|
+
operator "org.apache.spark.ml.feature.Tokenizer"
|
|
107
|
+
|
|
108
|
+
param :input_col, :string, doc: "input column name"
|
|
109
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Tokenizes a string column with a regex, either splitting on it or matching it (`RegexTokenizer`).
|
|
113
|
+
class RegexTokenizer < Transformer
|
|
114
|
+
operator "org.apache.spark.ml.feature.RegexTokenizer"
|
|
115
|
+
|
|
116
|
+
param :min_token_length, :int, default: 1, spark_name: "minTokenLength",
|
|
117
|
+
doc: "minimum token length (>= 0)"
|
|
118
|
+
param :gaps, :boolean, default: true, doc: "whether the regex splits on gaps (true) or matches tokens (false)"
|
|
119
|
+
param :pattern, :string, default: "\\s+", doc: "the regex pattern used for tokenizing"
|
|
120
|
+
param :to_lowercase, :boolean, default: true, spark_name: "toLowercase",
|
|
121
|
+
doc: "whether to convert all characters to lowercase before tokenizing"
|
|
122
|
+
param :input_col, :string, doc: "input column name"
|
|
123
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Transforms the input dataset with a SQL statement; the input is `__THIS__` (`SQLTransformer`).
|
|
127
|
+
class SQLTransformer < Transformer
|
|
128
|
+
operator "org.apache.spark.ml.feature.SQLTransformer"
|
|
129
|
+
|
|
130
|
+
param :statement, :string, doc: "SQL statement, e.g. SELECT ... FROM __THIS__"
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# Filters stop words out of token arrays (`StopWordsRemover`).
|
|
134
|
+
# The default `stopWords` is the server's English list.
|
|
135
|
+
class StopWordsRemover < Transformer
|
|
136
|
+
operator "org.apache.spark.ml.feature.StopWordsRemover"
|
|
137
|
+
|
|
138
|
+
param :stop_words, :string_array, spark_name: "stopWords",
|
|
139
|
+
doc: "the words to be filtered out (server default: English stop words)"
|
|
140
|
+
param :case_sensitive, :boolean, default: false, spark_name: "caseSensitive",
|
|
141
|
+
doc: "whether to do a case-sensitive comparison over the stop words"
|
|
142
|
+
param :locale, :string, doc: "locale of the input for case insensitive matching (server default: JVM locale)"
|
|
143
|
+
param :input_col, :string, doc: "input column name"
|
|
144
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
145
|
+
param :input_cols, :string_array, doc: "input column names (multi-column mode)"
|
|
146
|
+
param :output_cols, :string_array, doc: "output column names (multi-column mode)"
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Hashes several columns into one vector with the hashing trick (`FeatureHasher`).
|
|
150
|
+
class FeatureHasher < Transformer
|
|
151
|
+
operator "org.apache.spark.ml.feature.FeatureHasher"
|
|
152
|
+
|
|
153
|
+
param :num_features, :int, default: 1 << 18, spark_name: "numFeatures",
|
|
154
|
+
doc: "number of features, the size of the output vector (> 0)"
|
|
155
|
+
param :input_cols, :string_array, doc: "input column names"
|
|
156
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
157
|
+
param :categorical_cols, :string_array, spark_name: "categoricalCols",
|
|
158
|
+
doc: "numeric columns to treat as categorical"
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
# Multiplies each vector element by a fixed scaling vector (`ElementwiseProduct`).
|
|
162
|
+
class ElementwiseProduct < Transformer
|
|
163
|
+
operator "org.apache.spark.ml.feature.ElementwiseProduct"
|
|
164
|
+
|
|
165
|
+
param :scaling_vec, :vector, spark_name: "scalingVec", doc: "the vector to multiply with input vectors"
|
|
166
|
+
param :input_col, :string, doc: "input column name"
|
|
167
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# Maps a sequence of terms to term frequencies with the hashing trick (`HashingTF`).
|
|
171
|
+
class HashingTF < Transformer
|
|
172
|
+
operator "org.apache.spark.ml.feature.HashingTF"
|
|
173
|
+
|
|
174
|
+
param :num_features, :int, default: 1 << 18, spark_name: "numFeatures",
|
|
175
|
+
doc: "number of features, the size of the output vector (> 0)"
|
|
176
|
+
param :binary, :boolean, default: false, doc: "whether all non-zero counts are set to 1.0"
|
|
177
|
+
param :input_col, :string, doc: "input column name"
|
|
178
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
# Maps indices back to the original string labels (`IndexToString`).
|
|
182
|
+
class IndexToString < Transformer
|
|
183
|
+
operator "org.apache.spark.ml.feature.IndexToString"
|
|
184
|
+
|
|
185
|
+
param :input_col, :string, doc: "input column name (numeric label indices)"
|
|
186
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
187
|
+
param :labels, :string_array, doc: "the index-to-string mapping; unset means the input column's metadata is used"
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
# Expands vectors into all polynomial terms up to `degree` (`PolynomialExpansion`).
|
|
191
|
+
class PolynomialExpansion < Transformer
|
|
192
|
+
operator "org.apache.spark.ml.feature.PolynomialExpansion"
|
|
193
|
+
|
|
194
|
+
param :degree, :int, default: 2, doc: "the polynomial degree to expand (>= 1)"
|
|
195
|
+
param :input_col, :string, doc: "input column name"
|
|
196
|
+
param :output_col, :string, doc: "output column name (server default: <uid>__output)"
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
end
|
|
200
|
+
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SparkConnect
|
|
4
|
+
module ML
|
|
5
|
+
# Frequent pattern mining (`org.apache.spark.ml.fpm`).
|
|
6
|
+
module FPM
|
|
7
|
+
# FP-growth frequent itemset mining and association rules.
|
|
8
|
+
class FPGrowth < Estimator
|
|
9
|
+
operator "org.apache.spark.ml.fpm.FPGrowth"
|
|
10
|
+
model -> { FPGrowthModel }
|
|
11
|
+
|
|
12
|
+
param :min_support, :double, default: 0.3, doc: "minimal support level in [0, 1]"
|
|
13
|
+
param :min_confidence, :double, default: 0.8, doc: "minimal confidence for generating association rules in [0, 1]"
|
|
14
|
+
param :items_col, :string, default: "items", doc: "items column name"
|
|
15
|
+
param :num_partitions, :int, doc: "number of partitions used by parallel FP-growth (>= 1)"
|
|
16
|
+
param :prediction_col, :string, default: "prediction", doc: "prediction column name"
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# A fitted {FPGrowth} model: the frequent itemsets and association rules.
|
|
20
|
+
class FPGrowthModel < Model
|
|
21
|
+
operator "org.apache.spark.ml.fpm.FPGrowthModel"
|
|
22
|
+
|
|
23
|
+
param :min_support, :double, default: 0.3, doc: "minimal support level in [0, 1]"
|
|
24
|
+
param :min_confidence, :double, default: 0.8, doc: "minimal confidence for generating association rules in [0, 1]"
|
|
25
|
+
param :items_col, :string, default: "items", doc: "items column name"
|
|
26
|
+
param :num_partitions, :int, doc: "number of partitions used by parallel FP-growth (>= 1)"
|
|
27
|
+
param :prediction_col, :string, default: "prediction", doc: "prediction column name"
|
|
28
|
+
|
|
29
|
+
attribute :freq_itemsets, :dataframe, spark_name: "freqItemsets"
|
|
30
|
+
attribute :association_rules, :dataframe, spark_name: "associationRules"
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Sequential pattern mining. Not a Spark ML estimator: PySpark runs it over Connect through the
|
|
34
|
+
# ML connect helper, and so does this class.
|
|
35
|
+
class PrefixSpan < Params
|
|
36
|
+
operator "org.apache.spark.ml.fpm.PrefixSpan"
|
|
37
|
+
|
|
38
|
+
param :min_support, :double, default: 0.1, doc: "minimal support level in [0, 1]"
|
|
39
|
+
param :max_pattern_length, :int, default: 10, doc: "maximal length of the sequential patterns (> 0)"
|
|
40
|
+
param :max_local_proj_db_size, :long, default: 32_000_000,
|
|
41
|
+
doc: "limit on the size of the local projected database"
|
|
42
|
+
param :sequence_col, :string, default: "sequence", doc: "name of the sequence column"
|
|
43
|
+
|
|
44
|
+
# Find the frequent sequential patterns of the sequences in `dataset`.
|
|
45
|
+
#
|
|
46
|
+
# @param dataset [DataFrame] a column of sequences (`array<array<T>>`)
|
|
47
|
+
# @return [DataFrame] the columns `sequence` and `freq`
|
|
48
|
+
def find_frequent_sequential_patterns(dataset)
|
|
49
|
+
session = dataset.session
|
|
50
|
+
args = [dataset, min_support, max_pattern_length, max_local_proj_db_size, sequence_col]
|
|
51
|
+
methods = [AttributeSupport.method_proto("prefixSpanFindFrequentSequentialPatterns", args)]
|
|
52
|
+
fetch = Proto::Fetch.new(obj_ref: Proto::ObjectRef.new(id: Rpc::HELPER_ID), methods: methods)
|
|
53
|
+
DataFrame.new(session, PlanBuilder.relation(session, ml_relation: Proto::MlRelation.new(fetch: fetch)))
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SparkConnect
|
|
4
|
+
module ML
|
|
5
|
+
# The `pyspark.ml.functions` helpers over Connect: converting between array
|
|
6
|
+
# columns and `VectorUDT` columns. They call Spark's internal functions, so
|
|
7
|
+
# the call is sent with `is_internal` set, like PySpark's connect client.
|
|
8
|
+
module Functions
|
|
9
|
+
module_function
|
|
10
|
+
|
|
11
|
+
# Convert a vector column into an array column.
|
|
12
|
+
#
|
|
13
|
+
# @param col [Column, String] a `VectorUDT` column.
|
|
14
|
+
# @param dtype [String] the element type of the result: "float64" or "float32" (Spark 4.0+).
|
|
15
|
+
# @return [Column]
|
|
16
|
+
def vector_to_array(col, dtype = "float64")
|
|
17
|
+
Functions.internal_call("vector_to_array", Functions.column_of(col), Column.to_col(dtype))
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Convert an array column of numbers into a dense vector column.
|
|
21
|
+
#
|
|
22
|
+
# @param col [Column, String]
|
|
23
|
+
# @return [Column]
|
|
24
|
+
def array_to_vector(col)
|
|
25
|
+
Functions.internal_call("array_to_vector", Functions.column_of(col))
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# @api private
|
|
29
|
+
# @return [Column] a column from a name or an existing column.
|
|
30
|
+
def column_of(col)
|
|
31
|
+
col.is_a?(Column) ? col : Column.from_name(col.to_s)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# @api private
|
|
35
|
+
# @return [Column] an unresolved call to Spark's internal function `name`.
|
|
36
|
+
def internal_call(name, *args)
|
|
37
|
+
Column.new(Proto::Expression.new(
|
|
38
|
+
unresolved_function: Proto::Expression::UnresolvedFunction.new(
|
|
39
|
+
function_name: name,
|
|
40
|
+
arguments: args.map(&:to_expr),
|
|
41
|
+
is_internal: true
|
|
42
|
+
)
|
|
43
|
+
))
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SparkConnect
|
|
4
|
+
module ML
|
|
5
|
+
# Local linear algebra values, mirroring `pyspark.ml.linalg`: dense and sparse
|
|
6
|
+
# vectors and matrices. They are accepted as ML params and literals, and are
|
|
7
|
+
# returned from model attributes and from DataFrames whose columns are
|
|
8
|
+
# `VectorUDT` / `MatrixUDT`.
|
|
9
|
+
module Linalg
|
|
10
|
+
# Base class for vectors.
|
|
11
|
+
class Vector
|
|
12
|
+
include Enumerable
|
|
13
|
+
|
|
14
|
+
# @return [Integer] the number of elements.
|
|
15
|
+
attr_reader :size
|
|
16
|
+
|
|
17
|
+
# @return [Array<Float>] the dense elements.
|
|
18
|
+
def to_a = Array.new(size) { |i| self[i] }
|
|
19
|
+
alias to_array to_a
|
|
20
|
+
|
|
21
|
+
# @param other [Vector]
|
|
22
|
+
# @return [Boolean]
|
|
23
|
+
def ==(other)
|
|
24
|
+
other.is_a?(Vector) && other.size == size && other.to_a == to_a
|
|
25
|
+
end
|
|
26
|
+
alias eql? ==
|
|
27
|
+
|
|
28
|
+
# @return [Integer]
|
|
29
|
+
def hash = [self.class, size, to_a].hash
|
|
30
|
+
|
|
31
|
+
# @param other [Vector, Array<Numeric>]
|
|
32
|
+
# @return [Float] the dot product.
|
|
33
|
+
def dot(other)
|
|
34
|
+
values = other.is_a?(Vector) ? other.to_a : other
|
|
35
|
+
raise IllegalArgumentError, "Dimension mismatch: #{size} vs #{values.size}" unless values.size == size
|
|
36
|
+
|
|
37
|
+
to_a.each_with_index.sum { |v, i| v * values[i] }
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# @return [Float] the Euclidean norm.
|
|
41
|
+
def norm = Math.sqrt(to_a.sum { |v| v * v })
|
|
42
|
+
|
|
43
|
+
# @return [Array<Float>] the elements, one per entry (Enumerable support).
|
|
44
|
+
def each(&) = to_a.each(&)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# A vector stored as a plain array of values.
|
|
48
|
+
class DenseVector < Vector
|
|
49
|
+
# @param values [Array<Numeric>]
|
|
50
|
+
def initialize(values)
|
|
51
|
+
super()
|
|
52
|
+
@values = values.map(&:to_f).freeze
|
|
53
|
+
@size = @values.size
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# @return [Array<Float>] the underlying values.
|
|
57
|
+
attr_reader :values
|
|
58
|
+
|
|
59
|
+
# @param index [Integer]
|
|
60
|
+
# @return [Float]
|
|
61
|
+
def [](index) = @values[index]
|
|
62
|
+
|
|
63
|
+
# @return [String]
|
|
64
|
+
def to_s = "[#{@values.map { |v| Linalg.format_double(v) }.join(',')}]"
|
|
65
|
+
|
|
66
|
+
# @return [String]
|
|
67
|
+
def inspect = "DenseVector(#{self})"
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# A vector stored as sorted indices and their non-zero values.
|
|
71
|
+
class SparseVector < Vector
|
|
72
|
+
# @param size [Integer]
|
|
73
|
+
# @param indices [Array<Integer>, Hash{Integer => Numeric}] indices with values, or a
|
|
74
|
+
# hash of index to value.
|
|
75
|
+
# @param values [Array<Numeric>, nil] the values when `indices` is an array.
|
|
76
|
+
def initialize(size, indices, values = nil)
|
|
77
|
+
super()
|
|
78
|
+
pairs = if indices.is_a?(Hash)
|
|
79
|
+
indices.to_a
|
|
80
|
+
else
|
|
81
|
+
raise IllegalArgumentError, "indices and values must have the same length" unless indices.size == values.size
|
|
82
|
+
|
|
83
|
+
indices.zip(values)
|
|
84
|
+
end
|
|
85
|
+
pairs = pairs.map { |i, v| [Integer(i), v.to_f] }.sort_by(&:first)
|
|
86
|
+
pairs.map(&:first).each do |i|
|
|
87
|
+
raise IllegalArgumentError, "index #{i} out of range for size #{size}" if i.negative? || i >= size
|
|
88
|
+
end
|
|
89
|
+
@size = size
|
|
90
|
+
@indices = pairs.map(&:first).freeze
|
|
91
|
+
@values = pairs.map(&:last).freeze
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# @return [Array<Integer>] the non-zero indices.
|
|
95
|
+
attr_reader :indices
|
|
96
|
+
|
|
97
|
+
# @return [Array<Float>] the non-zero values.
|
|
98
|
+
attr_reader :values
|
|
99
|
+
|
|
100
|
+
# @param index [Integer]
|
|
101
|
+
# @return [Float]
|
|
102
|
+
def [](index)
|
|
103
|
+
pos = @indices.bsearch_index { |i| i >= index }
|
|
104
|
+
pos && @indices[pos] == index ? @values[pos] : 0.0
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# @return [String]
|
|
108
|
+
def to_s = "(#{@size},[#{@indices.join(',')}],[#{@values.map { |v| Linalg.format_double(v) }.join(',')}])"
|
|
109
|
+
|
|
110
|
+
# @return [String]
|
|
111
|
+
def inspect = "SparseVector#{self}"
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Column-major (or transposed row-major) dense matrix.
|
|
115
|
+
class Matrix
|
|
116
|
+
# @return [Integer]
|
|
117
|
+
attr_reader :num_rows, :num_cols
|
|
118
|
+
|
|
119
|
+
# @return [Boolean]
|
|
120
|
+
attr_reader :is_transposed
|
|
121
|
+
|
|
122
|
+
# @return [Array<Array<Float>>] the matrix as rows.
|
|
123
|
+
def to_a
|
|
124
|
+
Array.new(num_rows) { |r| Array.new(num_cols) { |c| self[r, c] } }
|
|
125
|
+
end
|
|
126
|
+
alias to_array to_a
|
|
127
|
+
|
|
128
|
+
# @param other [Matrix]
|
|
129
|
+
# @return [Boolean]
|
|
130
|
+
def ==(other)
|
|
131
|
+
other.is_a?(Matrix) && other.num_rows == num_rows && other.num_cols == num_cols && other.to_a == to_a
|
|
132
|
+
end
|
|
133
|
+
alias eql? ==
|
|
134
|
+
|
|
135
|
+
# @return [Integer]
|
|
136
|
+
def hash = [self.class, num_rows, num_cols, to_a].hash
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# A dense matrix. Values are column-major unless `is_transposed` is true.
|
|
140
|
+
class DenseMatrix < Matrix
|
|
141
|
+
# @param num_rows [Integer]
|
|
142
|
+
# @param num_cols [Integer]
|
|
143
|
+
# @param values [Array<Numeric>] `num_rows * num_cols` values (column-major by default).
|
|
144
|
+
# @param is_transposed [Boolean]
|
|
145
|
+
def initialize(num_rows, num_cols, values, is_transposed: false)
|
|
146
|
+
super()
|
|
147
|
+
values = values.map(&:to_f)
|
|
148
|
+
raise IllegalArgumentError, "expected #{num_rows * num_cols} values, got #{values.size}" unless values.size == num_rows * num_cols
|
|
149
|
+
|
|
150
|
+
@num_rows = num_rows
|
|
151
|
+
@num_cols = num_cols
|
|
152
|
+
@values = values.freeze
|
|
153
|
+
@is_transposed = is_transposed
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# @return [Array<Float>] the raw values as stored.
|
|
157
|
+
attr_reader :values
|
|
158
|
+
|
|
159
|
+
# @return [Float]
|
|
160
|
+
def [](row, col)
|
|
161
|
+
idx = is_transposed ? (row * num_cols) + col : (col * num_rows) + row
|
|
162
|
+
@values[idx]
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# @return [String]
|
|
166
|
+
def inspect = "DenseMatrix(#{num_rows}, #{num_cols}, [#{@values.map { |v| Linalg.format_double(v) }.join(', ')}], #{is_transposed})"
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# A compressed-sparse-column matrix.
|
|
170
|
+
class SparseMatrix < Matrix
|
|
171
|
+
# @param num_rows [Integer]
|
|
172
|
+
# @param num_cols [Integer]
|
|
173
|
+
# @param col_ptrs [Array<Integer>] `num_cols + 1` column pointers.
|
|
174
|
+
# @param row_indices [Array<Integer>]
|
|
175
|
+
# @param values [Array<Numeric>]
|
|
176
|
+
# @param is_transposed [Boolean]
|
|
177
|
+
def initialize(num_rows, num_cols, col_ptrs, row_indices, values, is_transposed: false)
|
|
178
|
+
super()
|
|
179
|
+
raise IllegalArgumentError, "colPtrs must have #{num_cols + 1} entries" unless col_ptrs.size == num_cols + 1
|
|
180
|
+
raise IllegalArgumentError, "rowIndices and values must have the same length" unless row_indices.size == values.size
|
|
181
|
+
|
|
182
|
+
@num_rows = num_rows
|
|
183
|
+
@num_cols = num_cols
|
|
184
|
+
@col_ptrs = col_ptrs.map(&:to_i).freeze
|
|
185
|
+
@row_indices = row_indices.map(&:to_i).freeze
|
|
186
|
+
@values = values.map(&:to_f).freeze
|
|
187
|
+
@is_transposed = is_transposed
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
# @return [Array<Integer>]
|
|
191
|
+
attr_reader :col_ptrs, :row_indices, :values
|
|
192
|
+
|
|
193
|
+
# @return [Float]
|
|
194
|
+
def [](row, col)
|
|
195
|
+
row, col = col, row if is_transposed
|
|
196
|
+
start = @col_ptrs[col]
|
|
197
|
+
stop = @col_ptrs[col + 1]
|
|
198
|
+
pos = (start...stop).find { |k| @row_indices[k] == row }
|
|
199
|
+
pos ? @values[pos] : 0.0
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
# @return [String]
|
|
203
|
+
def inspect = "SparseMatrix(#{num_rows}, #{num_cols}, #{col_ptrs}, #{row_indices}, #{values}, #{is_transposed})"
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
# Factory methods for vectors, like `pyspark.ml.linalg.Vectors`.
|
|
207
|
+
module Vectors
|
|
208
|
+
module_function
|
|
209
|
+
|
|
210
|
+
# @param values [Array<Numeric>, *Numeric]
|
|
211
|
+
# @return [DenseVector]
|
|
212
|
+
def dense(*values)
|
|
213
|
+
DenseVector.new(values.size == 1 && values.first.is_a?(Array) ? values.first : values)
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
# @param size [Integer]
|
|
217
|
+
# @param indices [Array<Integer>, Hash{Integer => Numeric}]
|
|
218
|
+
# @param values [Array<Numeric>, nil]
|
|
219
|
+
# @return [SparseVector]
|
|
220
|
+
def sparse(size, indices, values = nil)
|
|
221
|
+
SparseVector.new(size, indices, values)
|
|
222
|
+
end
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
# Factory methods for matrices, like `pyspark.ml.linalg.Matrices`.
|
|
226
|
+
module Matrices
|
|
227
|
+
module_function
|
|
228
|
+
|
|
229
|
+
# @return [DenseMatrix]
|
|
230
|
+
def dense(num_rows, num_cols, values, is_transposed: false)
|
|
231
|
+
DenseMatrix.new(num_rows, num_cols, values, is_transposed: is_transposed)
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
# @return [SparseMatrix]
|
|
235
|
+
def sparse(num_rows, num_cols, col_ptrs, row_indices, values, is_transposed: false)
|
|
236
|
+
SparseMatrix.new(num_rows, num_cols, col_ptrs, row_indices, values, is_transposed: is_transposed)
|
|
237
|
+
end
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
VECTOR_UDT = "org.apache.spark.ml.linalg.VectorUDT"
|
|
241
|
+
MATRIX_UDT = "org.apache.spark.ml.linalg.MatrixUDT"
|
|
242
|
+
|
|
243
|
+
module_function
|
|
244
|
+
|
|
245
|
+
# Render a double the way Spark's `toString` does (whole numbers keep `.0`).
|
|
246
|
+
# @api private
|
|
247
|
+
def format_double(value)
|
|
248
|
+
value == value.floor && value.abs < 1e15 ? format("%.1f", value) : value.to_s
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
# Build a vector from the Arrow struct value of a `VectorUDT` column.
|
|
252
|
+
#
|
|
253
|
+
# @param value [Hash] `{"type" => 0|1, "size" => ..., "indices" => [...], "values" => [...]}`
|
|
254
|
+
# @return [Vector, nil]
|
|
255
|
+
def vector_from_struct(value)
|
|
256
|
+
return nil if value.nil?
|
|
257
|
+
|
|
258
|
+
case fetch_key(value, "type")
|
|
259
|
+
when 0 then SparseVector.new(fetch_key(value, "size"), fetch_key(value, "indices") || [], fetch_key(value, "values") || [])
|
|
260
|
+
when 1 then DenseVector.new(fetch_key(value, "values") || [])
|
|
261
|
+
else raise IllegalArgumentError, "unknown VectorUDT type #{fetch_key(value, 'type').inspect}"
|
|
262
|
+
end
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
# Build a matrix from the Arrow struct value of a `MatrixUDT` column.
|
|
266
|
+
#
|
|
267
|
+
# @param value [Hash]
|
|
268
|
+
# @return [Matrix, nil]
|
|
269
|
+
def matrix_from_struct(value)
|
|
270
|
+
return nil if value.nil?
|
|
271
|
+
|
|
272
|
+
rows = fetch_key(value, "numRows")
|
|
273
|
+
cols = fetch_key(value, "numCols")
|
|
274
|
+
transposed = fetch_key(value, "isTransposed") ? true : false
|
|
275
|
+
case fetch_key(value, "type")
|
|
276
|
+
when 0
|
|
277
|
+
SparseMatrix.new(rows, cols, fetch_key(value, "colPtrs"), fetch_key(value, "rowIndices"),
|
|
278
|
+
fetch_key(value, "values"), is_transposed: transposed)
|
|
279
|
+
when 1
|
|
280
|
+
DenseMatrix.new(rows, cols, fetch_key(value, "values"), is_transposed: transposed)
|
|
281
|
+
else raise IllegalArgumentError, "unknown MatrixUDT type #{fetch_key(value, 'type').inspect}"
|
|
282
|
+
end
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
# @api private
|
|
286
|
+
def fetch_key(hash, key)
|
|
287
|
+
return hash[key] if hash.key?(key)
|
|
288
|
+
|
|
289
|
+
hash[key.to_sym]
|
|
290
|
+
end
|
|
291
|
+
|
|
292
|
+
# Replace the `VectorUDT`/`MatrixUDT` values of decoded rows with
|
|
293
|
+
# {Vector}/{Matrix} objects. Rows are returned unchanged when the result
|
|
294
|
+
# has no such column.
|
|
295
|
+
#
|
|
296
|
+
# @param rows [Array<Row>]
|
|
297
|
+
# @param schema [Spark::Connect::DataType, nil] the result schema proto.
|
|
298
|
+
# @return [Array<Row>]
|
|
299
|
+
def convert_rows(rows, schema)
|
|
300
|
+
return rows if schema.nil? || rows.empty?
|
|
301
|
+
return rows unless schema.kind == :struct
|
|
302
|
+
|
|
303
|
+
fields = Types.from_proto(schema).fields
|
|
304
|
+
udt_positions = fields.each_index.select { |i| fields[i].data_type.is_a?(Types::UserDefinedType) && fields[i].data_type.jvm_class }
|
|
305
|
+
return rows if udt_positions.empty?
|
|
306
|
+
|
|
307
|
+
rows.each do |row|
|
|
308
|
+
udt_positions.each do |i|
|
|
309
|
+
row.values[i] = convert_udt(row.values[i], fields[i].data_type)
|
|
310
|
+
end
|
|
311
|
+
end
|
|
312
|
+
rows
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
# Convert a value that a `VectorUDT`/`MatrixUDT` column holds into the
|
|
316
|
+
# local value class, given the column's Spark data type.
|
|
317
|
+
#
|
|
318
|
+
# @param value [Object] the decoded column value.
|
|
319
|
+
# @param data_type [Types::DataType]
|
|
320
|
+
# @return [Object]
|
|
321
|
+
def convert_udt(value, data_type)
|
|
322
|
+
return value unless data_type.is_a?(Types::UserDefinedType) && !value.nil?
|
|
323
|
+
|
|
324
|
+
case data_type.jvm_class
|
|
325
|
+
when VECTOR_UDT then vector_from_struct(value)
|
|
326
|
+
when MATRIX_UDT then matrix_from_struct(value)
|
|
327
|
+
else value
|
|
328
|
+
end
|
|
329
|
+
end
|
|
330
|
+
end
|
|
331
|
+
|
|
332
|
+
# Module-level shorthand for {Linalg::Vectors} and {Linalg::Matrices}.
|
|
333
|
+
Vectors = Linalg::Vectors
|
|
334
|
+
Matrices = Linalg::Matrices
|
|
335
|
+
end
|
|
336
|
+
end
|