Skip to content

Add reshape methods #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/matrix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ impl<T: Num + PartialOrd + Copy> DynamicMatrix<T> {
Self::fill(shape, T::one())
}

pub fn reshape(&self, shape: &Shape) -> Result<DynamicMatrix<T>, ShapeError> {
if shape.order() != 2 {
return Err(ShapeError::new("Shape must have order of 2"));
}
let result = self.tensor.reshape(shape)?;
Ok(DynamicMatrix { tensor: result })
}

pub fn flatten(&self) -> DynamicVector<T> {
let data = self.tensor.raw().iter().cloned().collect::<Vec<T>>();
DynamicVector::new(&data).unwrap()
}

pub fn sum(&self, axes: Axes) -> DynamicVector<T> {
let result = self.tensor.sum(axes);
DynamicVector::from_tensor(result).unwrap()
Expand Down Expand Up @@ -328,6 +341,43 @@ mod tests {
assert_eq!(matrix[coord![1, 1].unwrap()], 1.0);
}

#[test]
fn test_reshape() {
let shape = shape![2, 2].unwrap();
let data = vec![1.0, 2.0, 3.0, 4.0];
let matrix = DynamicMatrix::new(&shape, &data).unwrap();
let new_shape = shape![4, 1].unwrap();
let reshaped_matrix = matrix.reshape(&new_shape).unwrap();
assert_eq!(reshaped_matrix.shape(), &new_shape);
assert_eq!(reshaped_matrix[coord![0, 0].unwrap()], 1.0);
assert_eq!(reshaped_matrix[coord![1, 0].unwrap()], 2.0);
assert_eq!(reshaped_matrix[coord![2, 0].unwrap()], 3.0);
assert_eq!(reshaped_matrix[coord![3, 0].unwrap()], 4.0);
}

#[test]
fn test_reshape_fail() {
let shape = shape![2, 2].unwrap();
let data = vec![1.0, 2.0, 3.0, 4.0];
let matrix = DynamicMatrix::new(&shape, &data).unwrap();
let new_shape = shape![3, 2].unwrap();
let result = matrix.reshape(&new_shape);
assert!(result.is_err());
}

#[test]
fn test_flatten() {
let shape = shape![2, 2].unwrap();
let data = vec![1.0, 2.0, 3.0, 4.0];
let matrix = DynamicMatrix::new(&shape, &data).unwrap();
let flattened_vector = matrix.flatten();
assert_eq!(flattened_vector.shape(), &shape![4].unwrap());
assert_eq!(flattened_vector[0], 1.0);
assert_eq!(flattened_vector[1], 2.0);
assert_eq!(flattened_vector[2], 3.0);
assert_eq!(flattened_vector[3], 4.0);
}

#[test]
fn test_size() {
let shape = shape![2, 2].unwrap();
Expand Down
2 changes: 1 addition & 1 deletion src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::coordinate::Coordinate;
use crate::error::ShapeError;
use crate::shape::Shape;

#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Clone)]
pub struct DynamicStorage<T> {
data: Vec<T>,
}
Expand Down
42 changes: 41 additions & 1 deletion src/tensor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,29 @@ impl<T: Num + PartialOrd + Copy> Tensor<T> {
Tensor::fill(shape, T::one())
}

pub fn reshape(&self, shape: &Shape) -> Result<Tensor<T>, ShapeError> {
if self.shape.size() != shape.size() {
return Err(ShapeError::new("Data length does not match shape size"));
}
Ok(Tensor {
data: self.data.clone(),
shape: shape.clone(),
})
}

// Properties
pub fn raw(&self) -> &DynamicStorage<T> {
&self.data
}

pub fn shape(&self) -> &Shape {
&self.shape
}
pub fn size(&self) -> usize {
self.shape.size()
}

// Access methods
pub fn get(&self, coord: &Coordinate) -> Result<&T, ShapeError> {
Ok(&self.data[self.data.flatten(coord, &self.shape)?])
}
Expand All @@ -66,7 +81,7 @@ impl<T: Num + PartialOrd + Copy> Tensor<T> {
Ok(())
}

// // Reduction operations
// Reduction operations
pub fn sum(&self, axes: Axes) -> Tensor<T> {
let all_axes = (0..self.shape.order()).collect::<Vec<_>>();
let remaining_axes = all_axes
Expand Down Expand Up @@ -594,6 +609,31 @@ mod tests {
assert_eq!(tensor.data, DynamicStorage::new(vec![1.0; shape.size()]));
}

#[test]
fn test_reshape_tensor() {
let shape = shape![2, 3].unwrap();
let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
let tensor = Tensor::new(&shape, &data).unwrap();

let new_shape = shape![3, 2].unwrap();
let reshaped_tensor = tensor.reshape(&new_shape).unwrap();

assert_eq!(reshaped_tensor.shape(), &new_shape);
assert_eq!(reshaped_tensor.data, DynamicStorage::new(data));
}

#[test]
fn test_reshape_tensor_shape_mismatch() {
let shape = shape![2, 3].unwrap();
let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
let tensor = Tensor::new(&shape, &data).unwrap();

let new_shape = shape![4, 2].unwrap();
let result = tensor.reshape(&new_shape);

assert!(result.is_err());
}

#[test]
fn test_fill_tensor() {
let shape = shape![2, 3].unwrap();
Expand Down