nabla_ml/nab_array.rs
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 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
use rand::Rng;
use rand_distr::StandardNormal;
use std::ops::{Add, Sub, Mul};
#[derive(Debug, Clone)]
pub struct NDArray {
pub data: Vec<f64>,
pub shape: Vec<usize>,
}
impl NDArray {
pub fn new(data: Vec<f64>, shape: Vec<usize>) -> Self {
let total_size: usize = shape.iter().product();
assert_eq!(data.len(), total_size, "Data length must match shape dimensions");
NDArray { data, shape }
}
pub fn from_vec(data: Vec<f64>) -> Self {
let len = data.len();
Self::new(data, vec![len])
}
#[allow(dead_code)]
pub fn from_matrix(data: Vec<Vec<f64>>) -> Self {
let rows = data.len();
let cols = data.get(0).map_or(0, |row| row.len());
let flat_data: Vec<f64> = data.into_iter().flatten().collect();
Self::new(flat_data, vec![rows, cols])
}
pub fn shape(&self) -> &[usize] {
&self.shape
}
pub fn ndim(&self) -> usize {
self.shape.len()
}
/// Returns a reference to the data of the array
pub fn data(&self) -> &[f64] {
&self.data
}
/// Creates a 2D array (matrix) of random numbers between 0 and 1
///
/// # Arguments
///
/// * `rows` - The number of rows in the matrix.
/// * `cols` - The number of columns in the matrix.
///
/// # Returns
///
/// A 2D NDArray filled with random numbers.
#[allow(dead_code)]
pub fn rand_2d(rows: usize, cols: usize) -> Self {
let mut rng = rand::thread_rng();
let data: Vec<f64> = (0..rows * cols).map(|_| rng.gen()).collect();
Self::new(data, vec![rows, cols])
}
/// Creates a 1D array of random numbers following a normal distribution
///
/// # Arguments
///
/// * `size` - The number of elements in the array.
///
/// # Returns
///
/// A 1D NDArray filled with random numbers from a normal distribution.
#[allow(dead_code)]
pub fn randn(size: usize) -> Self {
let mut rng = rand::thread_rng();
let data: Vec<f64> = (0..size).map(|_| rng.sample(StandardNormal)).collect();
Self::from_vec(data)
}
/// Creates a 2D array (matrix) of random numbers following a normal distribution
///
/// # Arguments
///
/// * `rows` - The number of rows in the matrix.
/// * `cols` - The number of columns in the matrix.
///
/// # Returns
///
/// A 2D NDArray filled with random numbers from a normal distribution.
#[allow(dead_code)]
pub fn randn_2d(rows: usize, cols: usize) -> Self {
let mut rng = rand::thread_rng();
let data: Vec<f64> = (0..rows * cols).map(|_| rng.sample(StandardNormal)).collect();
Self::new(data, vec![rows, cols])
}
/// Creates a 1D array of random integers between `low` and `high`
///
/// # Arguments
///
/// * `low` - The lower bound (inclusive).
/// * `high` - The upper bound (exclusive).
/// * `size` - The number of elements in the array.
///
/// # Returns
///
/// A 1D NDArray filled with random integers.
#[allow(dead_code)]
pub fn randint(low: i32, high: i32, size: usize) -> Self {
let mut rng = rand::thread_rng();
let data: Vec<f64> = (0..size).map(|_| rng.gen_range(low..high) as f64).collect();
Self::from_vec(data)
}
/// Creates a 2D array (matrix) of random integers between `low` and `high`
///
/// # Arguments
///
/// * `low` - The lower bound (inclusive).
/// * `high` - The upper bound (exclusive).
/// * `rows` - The number of rows in the matrix.
/// * `cols` - The number of columns in the matrix.
///
/// # Returns
///
/// A 2D NDArray filled with random integers.
#[allow(dead_code)]
pub fn randint_2d(low: i32, high: i32, rows: usize, cols: usize) -> Self {
let mut rng = rand::thread_rng();
let data: Vec<f64> = (0..rows * cols).map(|_| rng.gen_range(low..high) as f64).collect();
Self::new(data, vec![rows, cols])
}
/// Reshapes the array to the specified shape, allowing one dimension to be inferred
///
/// # Arguments
///
/// * `new_shape` - A vector representing the new shape, with at most one dimension as `-1`.
///
/// # Returns
///
/// A new NDArray with the specified shape.
pub fn reshape(&self, mut new_shape: Vec<isize>) -> Self {
let total_elements = self.data.len();
let mut inferred_index = None;
let mut specified_size = 1;
for (i, &dim) in new_shape.iter().enumerate() {
if dim == -1 {
if inferred_index.is_some() {
panic!("Only one dimension can be inferred");
}
inferred_index = Some(i);
} else {
specified_size *= dim as usize;
}
}
if let Some(index) = inferred_index {
new_shape[index] = (total_elements / specified_size) as isize;
}
let new_shape_usize: Vec<usize> = new_shape.iter().map(|&x| x as usize).collect();
assert_eq!(total_elements, new_shape_usize.iter().product::<usize>(), "New shape must have the same number of elements as the original array");
Self::new(self.data.clone(), new_shape_usize)
}
/// Returns the maximum value in the array
///
/// # Returns
///
/// The maximum value as an f64.
#[allow(dead_code)]
pub fn max(&self) -> f64 {
*self.data.iter().max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap()
}
/// Returns the index of the maximum value in the array
///
/// # Returns
///
/// The index of the maximum value.
#[allow(dead_code)]
pub fn argmax(&self) -> usize {
self.data.iter().enumerate().max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()).map(|(i, _)| i).unwrap()
}
/// Returns the minimum value in the array
///
/// # Returns
///
/// The minimum value as an f64.
#[allow(dead_code)]
pub fn min(&self) -> f64 {
*self.data.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap()
}
/// Creates an NDArray from a flat vector and a specified shape
///
/// # Arguments
///
/// * `data` - A vector of f64 values representing the array's data.
/// * `shape` - A vector of usize values representing the dimensions of the array.
///
/// # Returns
///
/// A new NDArray instance.
#[allow(dead_code)]
pub fn from_vec_reshape(data: Vec<f64>, shape: Vec<usize>) -> Self {
let total_size: usize = shape.iter().product();
assert_eq!(data.len(), total_size, "Data length must match shape dimensions");
NDArray { data, shape }
}
/// Extracts a single sample from a batch of N-dimensional arrays
///
/// # Arguments
///
/// * `sample_index` - The index of the sample to extract
///
/// # Returns
///
/// A new NDArray containing just the specified sample with N-1 dimensions
#[allow(dead_code)]
pub fn extract_sample(&self, sample_index: usize) -> Self {
assert!(self.ndim() >= 2, "Array must have at least 2 dimensions");
assert!(sample_index < self.shape[0], "Sample index out of bounds");
let sample_size: usize = self.shape.iter().skip(1).product();
let start_index = sample_index * sample_size;
let end_index = start_index + sample_size;
// Create new shape without the first dimension
let new_shape: Vec<usize> = self.shape.iter().skip(1).cloned().collect();
NDArray::new(
self.data[start_index..end_index].to_vec(),
new_shape
)
}
/// Pretty prints an N-dimensional array
///
/// # Arguments
///
/// * `precision` - The number of decimal places to round each value to.
#[allow(dead_code)]
pub fn pretty_print(&self, precision: usize) {
let indent_str = " ".repeat(precision);
let format_value = |x: f64| -> String {
if x == 0.0 {
format!("{:.1}", x)
} else {
format!("{:.*}", precision, x)
}
};
match self.ndim() {
1 => println!("{}[{}]", indent_str, self.data.iter()
.map(|&x| format_value(x))
.collect::<Vec<_>>()
.join(" ")),
2 => {
println!("{}[", indent_str);
for i in 0..self.shape[0] {
print!("{} [", indent_str);
for j in 0..self.shape[1] {
print!("{}", format_value(self.get_2d(i, j)));
if j < self.shape[1] - 1 {
print!(" ");
}
}
println!("]");
}
println!("{}]", indent_str);
},
_ => {
println!("{}[", indent_str);
for i in 0..self.shape[0] {
let slice = self.extract_sample(i);
slice.pretty_print(precision + 2);
}
println!("{}]", indent_str);
}
}
}
/// Returns a specific element from the array
///
/// # Arguments
///
/// * `index` - The index of the element to retrieve.
///
/// # Returns
///
/// The element at the specified index.
#[allow(dead_code)]
pub fn get(&self, index: usize) -> f64 {
self.data[index]
}
/// Creates a 1D array with a range of numbers
///
/// # Arguments
///
/// * `start` - The starting value of the range (inclusive).
/// * `stop` - The stopping value of the range (exclusive).
/// * `step` - The step size between each value in the range.
///
/// # Returns
///
/// A 1D NDArray containing the range of numbers.
#[allow(dead_code)]
pub fn arange(start: f64, stop: f64, step: f64) -> Self {
let mut data = Vec::new();
let mut current = start;
while current < stop {
data.push(current);
current += step;
}
Self::from_vec(data)
}
/// Creates a 1D array filled with zeros
///
/// # Arguments
///
/// * `size` - The number of elements in the array.
///
/// # Returns
///
/// A 1D NDArray filled with zeros.
#[allow(dead_code)]
pub fn zeros(size: usize) -> Self {
Self::from_vec(vec![0.0; size])
}
/// Creates a 2D array (matrix) filled with zeros
///
/// # Arguments
///
/// * `rows` - The number of rows in the matrix.
/// * `cols` - The number of columns in the matrix.
///
/// # Returns
///
/// A 2D NDArray filled with zeros.
#[allow(dead_code)]
pub fn zeros_2d(rows: usize, cols: usize) -> Self {
Self::new(vec![0.0; rows * cols], vec![rows, cols])
}
/// Creates a 1D array filled with ones
///
/// # Arguments
///
/// * `size` - The number of elements in the array.
///
/// # Returns
///
/// A 1D NDArray filled with ones.
#[allow(dead_code)]
pub fn ones(size: usize) -> Self {
Self::from_vec(vec![1.0; size])
}
/// Creates a 2D array (matrix) filled with ones
///
/// # Arguments
///
/// * `rows` - The number of rows in the matrix.
/// * `cols` - The number of columns in the matrix.
///
/// # Returns
///
/// A 2D NDArray filled with ones.
#[allow(dead_code)]
pub fn ones_2d(rows: usize, cols: usize) -> Self {
Self::new(vec![1.0; rows * cols], vec![rows, cols])
}
/// Creates a 1D array with evenly spaced numbers over a specified interval
///
/// # Arguments
///
/// * `start` - The starting value of the interval.
/// * `end` - The ending value of the interval.
/// * `num` - The number of evenly spaced samples to generate.
/// * `precision` - The number of decimal places to round each value to.
///
/// # Returns
///
/// A 1D NDArray containing the evenly spaced numbers.
#[allow(dead_code)]
pub fn linspace(start: f64, end: f64, num: usize, precision: usize) -> Self {
assert!(num > 1, "Number of samples must be greater than 1");
let step = (end - start) / (num - 1) as f64;
let mut data = Vec::with_capacity(num);
let factor = 10f64.powi(precision as i32);
for i in 0..num {
let value = start + step * i as f64;
let rounded_value = (value * factor).round() / factor;
data.push(rounded_value);
}
Self::from_vec(data)
}
/// Creates an identity matrix of size `n x n`
///
/// # Arguments
///
/// * `n` - The size of the identity matrix.
///
/// # Returns
///
/// An `n x n` identity matrix as an NDArray.
#[allow(dead_code)]
pub fn eye(n: usize) -> Self {
let mut data = vec![0.0; n * n];
for i in 0..n {
data[i * n + i] = 1.0;
}
Self::new(data, vec![n, n])
}
/// Creates a 1D array of random numbers between 0 and 1
///
/// # Arguments
///
/// * `size` - The number of elements in the array.
///
/// # Returns
///
/// A 1D NDArray filled with random numbers.
#[allow(dead_code)]
pub fn rand(size: usize) -> Self {
let mut rng = rand::thread_rng();
let data: Vec<f64> = (0..size).map(|_| rng.gen()).collect();
Self::from_vec(data)
}
/// Returns a sub-matrix from a 2D array
///
/// # Arguments
///
/// * `row_start` - The starting row index of the sub-matrix.
/// * `row_end` - The ending row index of the sub-matrix (exclusive).
/// * `col_start` - The starting column index of the sub-matrix.
/// * `col_end` - The ending column index of the sub-matrix (exclusive).
///
/// # Returns
///
/// A new NDArray representing the specified sub-matrix.
#[allow(dead_code)]
pub fn sub_matrix(&self, row_start: usize, row_end: usize, col_start: usize, col_end: usize) -> Self {
assert_eq!(self.ndim(), 2, "sub_matrix is only applicable to 2D arrays");
let cols = self.shape[1];
let mut data = Vec::new();
for row in row_start..row_end {
for col in col_start..col_end {
data.push(self.data[row * cols + col]);
}
}
Self::new(data, vec![row_end - row_start, col_end - col_start])
}
/// Sets a specific element in the array
///
/// # Arguments
///
/// * `index` - The index of the element to set.
/// * `value` - The value to set the element to.
#[allow(dead_code)]
pub fn set(&mut self, index: usize, value: f64) {
self.data[index] = value;
}
/// Sets a range of elements in the array to a specific value
///
/// # Arguments
///
/// * `start` - The starting index of the range.
/// * `end` - The ending index of the range (exclusive).
/// * `value` - The value to set the elements to.
#[allow(dead_code)]
pub fn set_range(&mut self, start: usize, end: usize, value: f64) {
for i in start..end {
self.data[i] = value;
}
}
/// Returns a copy of the array
///
/// # Returns
///
/// A new NDArray that is a copy of the original.
#[allow(dead_code)]
pub fn copy(&self) -> Self {
Self::new(self.data.clone(), self.shape.clone())
}
/// Returns a view (slice) of the array from start to end (exclusive)
///
/// # Arguments
///
/// * `start` - The starting index of the view.
/// * `end` - The ending index of the view (exclusive).
///
/// # Returns
///
/// A slice of f64 values representing the specified view.
#[allow(dead_code)]
pub fn view(&self, start: usize, end: usize) -> &[f64] {
&self.data[start..end]
}
/// Returns a mutable view (slice) of the array from start to end (exclusive)
///
/// # Arguments
///
/// * `start` - The starting index of the view.
/// * `end` - The ending index of the view (exclusive).
///
/// # Returns
///
/// A mutable slice of f64 values representing the specified view.
#[allow(dead_code)]
pub fn view_mut(&mut self, start: usize, end: usize) -> &mut [f64] {
&mut self.data[start..end]
}
/// Returns a specific element from a 2D array
///
/// # Arguments
///
/// * `row` - The row index of the element.
/// * `col` - The column index of the element.
///
/// # Returns
///
/// The element at the specified row and column.
#[allow(dead_code)]
pub fn get_2d(&self, row: usize, col: usize) -> f64 {
assert_eq!(self.ndim(), 2, "get_2d is only applicable to 2D arrays");
let cols = self.shape[1];
self.data[row * cols + col]
}
/// Sets a specific element in a 2D array
///
/// # Arguments
///
/// * `row` - The row index of the element.
/// * `col` - The column index of the element.
/// * `value` - The value to set the element to.
#[allow(dead_code)]
pub fn set_2d(&mut self, row: usize, col: usize, value: f64) {
assert_eq!(self.ndim(), 2, "set_2d is only applicable to 2D arrays");
let cols = self.shape[1];
self.data[row * cols + col] = value;
}
/// Adds a new axis to the array at the specified position
///
/// # Arguments
///
/// * `axis` - The position at which to add the new axis.
///
/// # Returns
///
/// A new NDArray with an additional axis.
#[allow(dead_code)]
pub fn new_axis(&self, axis: usize) -> Self {
let mut new_shape = self.shape.clone();
new_shape.insert(axis, 1);
Self::new(self.data.clone(), new_shape)
}
/// Expands the dimensions of the array by adding a new axis at the specified index
///
/// # Arguments
///
/// * `axis` - The index at which to add the new axis.
///
/// # Returns
///
/// A new NDArray with expanded dimensions.
#[allow(dead_code)]
pub fn expand_dims(&self, axis: usize) -> Self {
self.new_axis(axis)
}
/// Returns a boolean array indicating whether each element satisfies the condition
///
/// # Arguments
///
/// * `threshold` - The threshold value to compare each element against.
///
/// # Returns
///
/// A vector of boolean values indicating whether each element is greater than the threshold.
#[allow(dead_code)]
pub fn greater_than(&self, threshold: f64) -> Vec<bool> {
self.data.iter().map(|&x| x > threshold).collect()
}
/// Returns a new array containing only the elements that satisfy the condition
///
/// # Arguments
///
/// * `condition` - A closure that takes an f64 and returns a boolean.
///
/// # Returns
///
/// A new NDArray containing only the elements that satisfy the condition.
#[allow(dead_code)]
pub fn filter(&self, condition: impl Fn(&f64) -> bool) -> Self {
let data: Vec<f64> = self.data.iter().cloned().filter(condition).collect();
Self::from_vec(data)
}
/// Returns the data type of the elements in the array
///
/// # Returns
///
/// A string representing the data type of the elements.
#[allow(dead_code)]
pub fn dtype(&self) -> &'static str {
"f64" // Since we're using f64 for all elements
}
/// Returns the total number of elements in the array
///
/// # Returns
///
/// The total number of elements in the array.
#[allow(dead_code)]
pub fn size(&self) -> usize {
self.data.len()
}
/// Returns the index of the minimum value in the array
///
/// # Returns
///
/// The index of the minimum value.
#[allow(dead_code)]
pub fn argmin(&self) -> usize {
self.data.iter().enumerate().min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()).map(|(i, _)| i).unwrap()
}
/// Returns a slice of the array from start to end (exclusive)
///
/// # Arguments
///
/// * `start` - The starting index of the slice.
/// * `end` - The ending index of the slice (exclusive).
///
/// # Returns
///
/// A new NDArray containing the specified slice.
#[allow(dead_code)]
pub fn slice(&self, start: usize, end: usize) -> Self {
let data = self.data[start..end].to_vec();
Self::from_vec(data)
}
/// Converts an NDArray of labels into a one-hot encoded NDArray
///
/// # Arguments
///
/// * `labels` - An NDArray containing numerical labels
///
/// # Returns
///
/// A new NDArray with one-hot encoded labels where each row corresponds to one label
///
/// # Panics
///
/// Panics if the input contains non-integer values
pub fn one_hot_encode(labels: &NDArray) -> Self {
// Verify that all values are integers
for &value in labels.data() {
// Check if the value is effectively an integer
if value.fract() != 0.0 {
panic!("All values must be integers for one-hot encoding");
}
}
// Convert values to integers and find unique classes
let labels_int: Vec<i32> = labels.data()
.iter()
.map(|&x| x as i32)
.collect();
// Find min and max to determine the range of classes
let min_label = labels_int.iter().min().unwrap();
let max_label = labels_int.iter().max().unwrap();
let num_classes = (max_label - min_label + 1) as usize;
let mut data = vec![0.0; labels_int.len() * num_classes];
// Shift indices by min_label to handle negative values
for (i, &label) in labels_int.iter().enumerate() {
let shifted_label = (label - min_label) as usize;
data[i * num_classes + shifted_label] = 1.0;
}
NDArray::new(data, vec![labels_int.len(), num_classes])
}
}
impl Add for NDArray {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
assert_eq!(self.shape, other.shape, "Shapes must match for element-wise addition");
let data = self.data.iter().zip(other.data.iter()).map(|(a, b)| a + b).collect();
NDArray::new(data, self.shape.clone())
}
}
impl Add<f64> for NDArray {
type Output = Self;
fn add(self, scalar: f64) -> Self::Output {
let data = self.data.iter().map(|a| a + scalar).collect();
NDArray::new(data, self.shape.clone())
}
}
impl Sub for NDArray {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
assert_eq!(self.shape, other.shape, "Shapes must match for element-wise subtraction");
let data = self.data.iter().zip(other.data.iter()).map(|(a, b)| a - b).collect();
NDArray::new(data, self.shape.clone())
}
}
impl Mul<f64> for NDArray {
type Output = Self;
fn mul(self, scalar: f64) -> Self::Output {
let data = self.data.iter().map(|a| a * scalar).collect();
NDArray::new(data, self.shape.clone())
}
}
// Add std::fmt::Display implementation for convenient printing
impl std::fmt::Display for NDArray {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.display())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_ndarray() {
let data = vec![1.0, 2.0, 3.0, 4.0];
let shape = vec![2, 2];
let array = NDArray::new(data.clone(), shape.clone());
assert_eq!(array.data(), &data);
assert_eq!(array.shape(), &shape);
}
#[test]
fn test_from_vec() {
let data = vec![1.0, 2.0, 3.0];
let array = NDArray::from_vec(data.clone());
assert_eq!(array.data(), &data);
assert_eq!(array.shape(), &[3]);
}
#[test]
fn test_arange() {
let array = NDArray::arange(0.0, 5.0, 1.0);
assert_eq!(array.data(), &[0.0, 1.0, 2.0, 3.0, 4.0]);
}
#[test]
fn test_element_wise_addition() {
let arr1 = NDArray::from_vec(vec![1.0, 2.0, 3.0]);
let arr2 = NDArray::from_vec(vec![4.0, 5.0, 6.0]);
let sum = arr1.clone() + arr2;
assert_eq!(sum.data(), &[5.0, 7.0, 9.0]);
}
#[test]
fn test_scalar_multiplication() {
let arr = NDArray::from_vec(vec![1.0, 2.0, 3.0]);
let scaled = arr.clone() * 2.0;
assert_eq!(scaled.data(), &[2.0, 4.0, 6.0]);
}
#[test]
fn test_reshape() {
let arr = NDArray::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let reshaped = arr.reshape(vec![2, 3]);
assert_eq!(reshaped.data(), &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
}
#[test]
fn test_element_wise_subtraction() {
let arr1 = NDArray::from_vec(vec![5.0, 7.0, 9.0]);
let arr2 = NDArray::from_vec(vec![1.0, 2.0, 3.0]);
let diff = arr1 - arr2;
assert_eq!(diff.data(), &[4.0, 5.0, 6.0]);
}
#[test]
fn test_scalar_addition() {
let arr = NDArray::from_vec(vec![1.0, 2.0, 3.0]);
let result = arr + 1.0;
assert_eq!(result.data(), &[2.0, 3.0, 4.0]);
}
#[test]
#[allow(non_snake_case)]
fn test_combined_operations() {
let X = NDArray::from_vec(vec![1.0, 2.0, 3.0]);
let theta_1 = 2.0;
let theta_0 = 1.0;
let predictions = X.clone() * theta_1 + theta_0;
assert_eq!(predictions.data(), &[3.0, 5.0, 7.0]);
}
#[test]
fn test_one_hot_encode() {
let labels = NDArray::from_vec(vec![0.0, 1.0, 2.0, 1.0, 0.0]);
let one_hot = NDArray::one_hot_encode(&labels);
let expected = vec![
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, 1.0, 0.0,
1.0, 0.0, 0.0
];
assert_eq!(one_hot.shape(), &[5, 3]);
assert_eq!(one_hot.data(), &expected);
}
#[test]
fn test_one_hot_encode_negative() {
let labels = NDArray::from_vec(vec![-1.0, 0.0, 1.0, 0.0, -1.0]);
let one_hot = NDArray::one_hot_encode(&labels);
let expected = vec![
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, 1.0, 0.0,
1.0, 0.0, 0.0
];
assert_eq!(one_hot.shape(), &[5, 3]);
assert_eq!(one_hot.data(), &expected);
}
#[test]
#[should_panic(expected = "All values must be integers")]
fn test_one_hot_encode_non_integer() {
let labels = NDArray::from_vec(vec![0.0, 1.5, 2.0]);
NDArray::one_hot_encode(&labels);
}
}