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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use f64;
use ;
use ;
// use prettytable::{row, Table};
use ;
use *;
/// Generates random test data with the given number of samples and features.
///
/// # Arguments
/// * `num_samples` - The number of samples to generate.
/// * `num_features` - The number of features (columns) per sample.
///
/// # Returns
/// A `Vec<f64>` containing the randomly generated data.
///
/// This function uses the `rand` crate to generate a flat vector of random floating-point values.
/// Converts a vector of `f64` values into a `Tensor<B, 2>` for the specified backend.
///
/// # Arguments
/// * `data` - A vector of `f64` values representing the data to convert.
/// * `num_samples` - The number of samples (rows).
/// * `num_features` - The number of features (columns).
/// * `device` - The device to place the tensor on (e.g., CPU, GPU).
///
/// # Returns
/// A `Tensor<B, 2>` containing the data arranged as samples x features.
///
/// This function uses the `TensorData` struct to create a tensor from the given data, then places it
/// on the specified device (`CPU` or `GPU`).
/// Prints the content of a tensor in a table format with index and tensor values.
///
/// # Arguments
/// * `data` - The tensor to print, with a generic backend and dimensionality `D`.
///
/// This function prints the tensor's data in a table with each row corresponding to one sample.
/// The tensor data is printed in a format that makes it easy to inspect.
// pub fn print_tensor<B: Backend, const D: usize>(data: &Tensor<B, D>) {
// let dims = data.dims();
// let n_samples = match dims.len() > 0 {
// true => dims[0],
// false => 0,
// };
// let mut table = Table::new();
// table.add_row(row!["Index", "Tensor"]);
// for index in 0..n_samples {
// let row = data.clone().slice([index..index + 1]);
// let row = row.to_data().to_vec::<f32>().unwrap();
// let row = format!("{row:?}");
// table.add_row(row![index, format!("{:?}", row)]);
// }
// if dims.len() == 0 {
// let row = data.to_data().to_vec::<f32>().unwrap();
// let row = row.get(0).unwrap();
// table.add_row(row![0, format!("{:?}", row)]);
// }
// table.printstd();
// }
/// Prints the content of a tensor with a title.
///
/// # Arguments
/// * `title` - A string title to print before displaying the tensor data.
/// * `data` - The tensor to print.
///
/// This function is similar to `print_tensor`, but with an added title to help distinguish different tensor prints.
// pub fn print_tensor_with_title<B: Backend, const D: usize>(title: &str, data: &Tensor<B, D>) {
// println!("{title}");
// print_tensor(data);
// }
/// Converts a 2D tensor into a `Vec<Vec<f64>>` for easier inspection or manipulation.
///
/// # Arguments
/// * `data` - A 2D tensor (samples x features) to convert into a vector of vectors.
///
/// # Returns
/// A `Vec<Vec<f64>>` where each inner `Vec<f64>` represents a row (sample) of the tensor.
///
/// This function extracts the data from a tensor and converts it into a `Vec<Vec<F>>` format. The conversion
/// assumes that the tensor is in a 2D shape and the precision is `f32` within the tensor.
/// Formats a `Duration` into a human-readable string in hours, minutes, and seconds format.
///
/// # Arguments
/// * `duration` - The duration to format.
///
/// # Returns
/// A formatted string representing the duration in the format `HH:MM:SS`.
///
/// This function is useful for displaying elapsed times or durations in a more readable format.
// a constant used to offset division by zero in the normalization function below
const SMALL_STD_DEV: f64 = 1e-6;
/// Normalizes the given dataset by centering each feature (column) to have mean 0
/// and standard deviation 1.
///
/// # Arguments
/// * `data` - A mutable slice representing the dataset, where each row is a sample,
/// and each column represents a feature. The data is assumed to be stored in
/// row-major order (i.e., `data[sample_idx * num_features + feature_idx]`).
/// * `num_samples` - The number of samples (rows) in the dataset.
/// * `num_features` - The number of features (columns) in the dataset.
///
/// # Example
/// ```
/// let mut data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
/// let num_samples = 2;
/// let num_features = 3;
/// normalize_data(&mut data, num_samples, num_features);
/// ```
/// The function will normalize each feature (column) across all samples (rows).
///
/// # Note
/// This function assumes that the dataset has at least one sample and one feature.
/// The data is normalized in-place, meaning the original data is modified directly.
/// Normalizes a 1D tensor using min-max normalization.
///
/// This function performs min-max normalization on a 1D tensor, scaling its values
/// to a range between 0 and 1. If the minimum and maximum values of the tensor are
/// equal (i.e., the tensor has no variance), the original tensor is returned unmodified.
///
/// # Type Parameters
///
/// - `B`: The autodiff backend type. This should implement the `AutodiffBackend` trait,
/// which provides support for automatic differentiation.
///
/// # Arguments
///
/// - `tensor`: A 1D tensor of type `Tensor<B, 1>`, which represents the input data to be normalized.
///
/// # Returns
///
/// - A new tensor of the same type and shape as the input tensor, with normalized values.
/// If the minimum and maximum values of the tensor are equal, the original tensor is returned unchanged.
///
/// # Explanation
///
/// The normalization is performed using the following formula:
///
/// ```
/// normalized = (tensor - min) / (max - min + epsilon)
/// ```
///
/// Where:
/// - `min`: The minimum value in the tensor.
/// - `max`: The maximum value in the tensor.
/// - `epsilon`: A small constant (`1e-6`) added to prevent division by zero, ensuring numerical stability.
///
/// The function first checks if the minimum and maximum values are equal. If they are, it avoids division by zero
/// and simply returns the original tensor. If they are not equal, it applies the min-max normalization formula.
///
/// # Example
///
/// ```rust
/// let tensor = Tensor::<B, 1>::from_data(vec![1.0, 2.0, 3.0], &device);
/// let normalized_tensor = normalize_tensor(tensor);
/// ```
/// Print a raw [`FloatTensor`] primitive to stdout in a grid layout.
///
/// Wraps the primitive in a typed [`Tensor`] and delegates to [`print_tensor`].
///
/// # Arguments
///
/// * `tensor` — The raw float-tensor primitive to display.
/// * `rows` — Maximum number of rows to print (clamped to at least `MIN_SIZE`).
/// * `cols` — Maximum number of columns to print (clamped to at least `MIN_SIZE`).
/// Minimum number of rows / columns shown by [`print_tensor`] when `rows` or
/// `cols` is smaller than this value.
const MIN_SIZE: usize = 10;
/// Print the first `rows × cols` elements of a 2-D tensor to stdout.
///
/// Each element is formatted in scientific notation with three decimal places
/// (`{:10.3e}`). Values beyond `rows` or `cols` are silently omitted.
///
/// # Arguments
///
/// * `tensor` — The 2-D tensor to display.
/// * `rows` — Maximum number of rows to print (floored to `MIN_SIZE`).
/// * `cols` — Maximum number of columns to print (floored to `MIN_SIZE`).