-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
StratifiedKFold.ts
250 lines (195 loc) · 7.75 KB
/
StratifiedKFold.ts
1
2
3
4
5
6
7
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/* eslint-disable */
/* NOTE: This file is auto-generated. Do not edit it directly. */
import crypto from 'node:crypto'
import { PythonBridge, NDArray, ArrayLike, SparseMatrix } from '@/sklearn/types'
/**
Stratified K-Folds cross-validator.
Provides train/test indices to split data in train/test sets.
This cross-validation object is a variation of KFold that returns stratified folds. The folds are made by preserving the percentage of samples for each class.
Read more in the [User Guide](../cross_validation.html#stratified-k-fold).
For visualisation of cross-validation behaviour and comparison between common scikit-learn split methods refer to [Visualizing cross-validation behavior in scikit-learn](../../auto_examples/model_selection/plot_cv_indices.html#sphx-glr-auto-examples-model-selection-plot-cv-indices-py)
[Python Reference](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html)
*/
export class StratifiedKFold {
id: string
opts: any
_py: PythonBridge
_isInitialized: boolean = false
_isDisposed: boolean = false
constructor(opts?: {
/**
Number of folds. Must be at least 2.
@defaultValue `5`
*/
n_splits?: number
/**
Whether to shuffle each class’s samples before splitting into batches. Note that the samples within each split will not be shuffled.
@defaultValue `false`
*/
shuffle?: boolean
/**
When `shuffle` is `true`, `random\_state` affects the ordering of the indices, which controls the randomness of each fold for each class. Otherwise, leave `random\_state` as `undefined`. Pass an int for reproducible output across multiple function calls. See [Glossary](../../glossary.html#term-random_state).
*/
random_state?: number
}) {
this.id = `StratifiedKFold${crypto.randomUUID().split('-')[0]}`
this.opts = opts || {}
}
get py(): PythonBridge {
return this._py
}
set py(pythonBridge: PythonBridge) {
this._py = pythonBridge
}
/**
Initializes the underlying Python resources.
This instance is not usable until the `Promise` returned by `init()` resolves.
*/
async init(py: PythonBridge): Promise<void> {
if (this._isDisposed) {
throw new Error('This StratifiedKFold instance has already been disposed')
}
if (this._isInitialized) {
return
}
if (!py) {
throw new Error('StratifiedKFold.init requires a PythonBridge instance')
}
this._py = py
await this._py.ex`
import numpy as np
from sklearn.model_selection import StratifiedKFold
try: bridgeStratifiedKFold
except NameError: bridgeStratifiedKFold = {}
`
// set up constructor params
await this._py.ex`ctor_StratifiedKFold = {'n_splits': ${
this.opts['n_splits'] ?? undefined
}, 'shuffle': ${this.opts['shuffle'] ?? undefined}, 'random_state': ${
this.opts['random_state'] ?? undefined
}}
ctor_StratifiedKFold = {k: v for k, v in ctor_StratifiedKFold.items() if v is not None}`
await this._py
.ex`bridgeStratifiedKFold[${this.id}] = StratifiedKFold(**ctor_StratifiedKFold)`
this._isInitialized = true
}
/**
Disposes of the underlying Python resources.
Once `dispose()` is called, the instance is no longer usable.
*/
async dispose() {
if (this._isDisposed) {
return
}
if (!this._isInitialized) {
return
}
await this._py.ex`del bridgeStratifiedKFold[${this.id}]`
this._isDisposed = true
}
/**
Get metadata routing of this object.
Please check [User Guide](../../metadata_routing.html#metadata-routing) on how the routing mechanism works.
*/
async get_metadata_routing(opts: {
/**
A [`MetadataRequest`](sklearn.utils.metadata_routing.MetadataRequest.html#sklearn.utils.metadata_routing.MetadataRequest "sklearn.utils.metadata_routing.MetadataRequest") encapsulating routing information.
*/
routing?: any
}): Promise<any> {
if (this._isDisposed) {
throw new Error('This StratifiedKFold instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error(
'StratifiedKFold must call init() before get_metadata_routing()'
)
}
// set up method params
await this._py.ex`pms_StratifiedKFold_get_metadata_routing = {'routing': ${
opts['routing'] ?? undefined
}}
pms_StratifiedKFold_get_metadata_routing = {k: v for k, v in pms_StratifiedKFold_get_metadata_routing.items() if v is not None}`
// invoke method
await this._py
.ex`res_StratifiedKFold_get_metadata_routing = bridgeStratifiedKFold[${this.id}].get_metadata_routing(**pms_StratifiedKFold_get_metadata_routing)`
// convert the result from python to node.js
return this
._py`res_StratifiedKFold_get_metadata_routing.tolist() if hasattr(res_StratifiedKFold_get_metadata_routing, 'tolist') else res_StratifiedKFold_get_metadata_routing`
}
/**
Returns the number of splitting iterations in the cross-validator
*/
async get_n_splits(opts: {
/**
Always ignored, exists for compatibility.
*/
X?: any
/**
Always ignored, exists for compatibility.
*/
y?: any
/**
Always ignored, exists for compatibility.
*/
groups?: any
}): Promise<number> {
if (this._isDisposed) {
throw new Error('This StratifiedKFold instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('StratifiedKFold must call init() before get_n_splits()')
}
// set up method params
await this._py.ex`pms_StratifiedKFold_get_n_splits = {'X': ${
opts['X'] ?? undefined
}, 'y': ${opts['y'] ?? undefined}, 'groups': ${opts['groups'] ?? undefined}}
pms_StratifiedKFold_get_n_splits = {k: v for k, v in pms_StratifiedKFold_get_n_splits.items() if v is not None}`
// invoke method
await this._py
.ex`res_StratifiedKFold_get_n_splits = bridgeStratifiedKFold[${this.id}].get_n_splits(**pms_StratifiedKFold_get_n_splits)`
// convert the result from python to node.js
return this
._py`res_StratifiedKFold_get_n_splits.tolist() if hasattr(res_StratifiedKFold_get_n_splits, 'tolist') else res_StratifiedKFold_get_n_splits`
}
/**
Generate indices to split data into training and test set.
*/
async split(opts: {
/**
Training data, where `n\_samples` is the number of samples and `n\_features` is the number of features.
Note that providing `y` is sufficient to generate the splits and hence `np.zeros(n\_samples)` may be used as a placeholder for `X` instead of actual training data.
*/
X?: ArrayLike[]
/**
The target variable for supervised learning problems. Stratification is done based on the y labels.
*/
y?: ArrayLike
/**
Always ignored, exists for compatibility.
*/
groups?: any
}): Promise<NDArray> {
if (this._isDisposed) {
throw new Error('This StratifiedKFold instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('StratifiedKFold must call init() before split()')
}
// set up method params
await this._py.ex`pms_StratifiedKFold_split = {'X': np.array(${
opts['X'] ?? undefined
}) if ${opts['X'] !== undefined} else None, 'y': np.array(${
opts['y'] ?? undefined
}) if ${opts['y'] !== undefined} else None, 'groups': ${
opts['groups'] ?? undefined
}}
pms_StratifiedKFold_split = {k: v for k, v in pms_StratifiedKFold_split.items() if v is not None}`
// invoke method
await this._py
.ex`res_StratifiedKFold_split = bridgeStratifiedKFold[${this.id}].split(**pms_StratifiedKFold_split)`
// convert the result from python to node.js
return this
._py`res_StratifiedKFold_split.tolist() if hasattr(res_StratifiedKFold_split, 'tolist') else res_StratifiedKFold_split`
}
}