Skip to main content

Iris

Struct Iris 

Source
pub struct Iris { /* private fields */ }
Expand description

A struct that represents the Iris dataset with lazy loading.

The dataset loads only when you call a data accessor method. After the first load, the dataset caches the data for later accesses.

§About Dataset

The Iris dataset is a classic dataset for classification tasks. It includes three iris species, with 50 samples each, and properties of each flower. One flower species is linearly separable from the other two. The other two are not linearly separable from each other.

§Feature columns

ColumnsAttributesUnit
0sepal_lengthcm
1sepal_widthcm
2petal_lengthcm
3petal_widthcm

§Labels

  • species name (in &str): "setosa", "versicolor", "virginica"

See more information at https://archive.ics.uci.edu/dataset/53/iris

§Citation

R. A. Fisher. “Iris,” UCI Machine Learning Repository, [Online]. Available: https://doi.org/10.24432/C56C76

§Thread Safety

This struct implements Send and Sync automatically, because all fields implement them. This makes the struct safe to share across threads. The internal Dataset makes lazy initialization thread-safe.

§Example

use dataset_ml::iris::Iris;

let download_dir = "./iris"; // the code creates the directory if it does not exist

let mut dataset = Iris::new(download_dir);
let features = dataset.features().unwrap();
let labels = dataset.labels().unwrap();

let (features, labels) = dataset.data().unwrap(); // this also returns features and labels
assert_eq!(features.shape(), &[150, 4]);
assert_eq!(labels.len(), 150);

// `get_data()` borrows the cached arrays without reloading. `get_data_mut()`
// edits the arrays in place. This needs no clone and no reload. The change
// stays cached. Prefer this method over `.to_owned()` when you only need to
// change values.
if let Some((features, labels)) = dataset.get_data_mut() {
    features[[0, 0]] = 5.5;
    labels[0] = "setosa-modified";
}
assert!(dataset.get_data().is_some());

// `take_data()` moves owned arrays out (no `to_owned()` clone). It leaves the
// instance reusable. The next access reloads the data from the cached file.
let (owned_features, owned_labels) = dataset.take_data().unwrap();
assert_eq!(owned_features.shape(), &[150, 4]);
assert_eq!(owned_labels.len(), 150);

// `into_data()` also returns owned arrays with no clone, but consumes the
// instance (use it when you are done with the dataset).
let (owned_features, owned_labels) = dataset.into_data().unwrap();
assert_eq!(owned_features.shape(), &[150, 4]);
assert_eq!(owned_labels.len(), 150);

Implementations§

Source§

impl Iris

Source

pub fn new(storage_dir: &str) -> Self

Create a new Iris instance without loading data.

The dataset loads lazily, on your first call to a data accessor method. This is a lightweight operation that only stores the storage directory.

§Parameters
  • storage_dir - Directory where the dataset is stored.
§Returns
  • Self - Iris instance ready for lazy loading.
Source

pub fn features(&self) -> Result<&Array2<f64>, DatasetError>

Get a reference to the feature matrix.

This method triggers lazy loading on first call. Subsequent calls return the cached data instantly.

§Returns
  • &Array2<f64> - Reference to feature matrix with shape (150, 4) containing:
    • sepal length in cm
    • sepal width in cm
    • petal length in cm
    • petal width in cm
§Errors

Returns DatasetError if:

  • Download fails due to network issues
  • File extraction or I/O operations fail
  • Data format is invalid (wrong number of columns, unparseable values, or invalid labels)
  • Dataset size does not match expected dimensions (150 samples, 4 features)
Source

pub fn labels(&self) -> Result<&Array1<&'static str>, DatasetError>

Get a reference to the labels vector.

This method triggers lazy loading on first call. Subsequent calls return the cached data instantly.

§Returns
  • &Array1<&'static str> - Reference to labels vector with shape (150,) containing species names ("setosa", "versicolor", "virginica")
§Errors

Returns DatasetError if:

  • Download fails due to network issues
  • File extraction or I/O operations fail
  • Data format is invalid (wrong number of columns, unparseable values, or invalid labels)
  • Dataset size does not match expected dimensions (150 samples)
Source

pub fn data(&self) -> Result<&(Array2<f64>, Array1<&'static str>), DatasetError>

Get both features and labels as references.

This method triggers lazy loading on first call. Subsequent calls return the cached data instantly.

§Returns
  • &IrisData - reference to the cached (features, labels) tuple: the feature matrix has shape (150, 4) (sepal length/width, petal length/width, all in cm) and the label vector has shape (150,) containing species names ("setosa", "versicolor", "virginica").
§Errors

Returns DatasetError if:

  • Download fails due to network issues
  • File extraction or I/O operations fail
  • Data format is invalid (wrong number of columns, unparseable values, or invalid labels)
  • Dataset size does not match expected dimensions (150 samples, 4 features)
Source

pub fn get_data(&self) -> Option<&(Array2<f64>, Array1<&'static str>)>

Get both features and labels as references without triggering loading.

Unlike Iris::data, which loads the dataset on first call, this method never runs the loader. If the data has not loaded yet, this method returns None instead of downloading and parsing it. Use this method when you want the data only if it is already cached. This avoids the download and parse cost when the data is not yet cached.

§Returns
  • Some(&IrisData) - reference to the cached (features, labels) tuple (feature matrix (150, 4), label vector (150,)), if loaded.
  • None - if the dataset has not been loaded yet.
Source

pub fn get_data_mut( &mut self, ) -> Option<&mut (Array2<f64>, Array1<&'static str>)>

Get mutable references to features and labels for in-place editing.

This lets you change the cached arrays directly, for example to normalize features or replace label values. It needs no to_owned() clone, and it does not remove the arrays from the cache. The changes persist, so later calls to Iris::features, Iris::data, or Iris::get_data observe them.

Like Iris::get_data, this method does not trigger loading. It returns None if the dataset has not loaded yet. If you need the data to be present, call a loading accessor first, for example Iris::data.

§Returns
  • Some(&mut IrisData) - mutable reference to the cached (features, labels) tuple (feature matrix (150, 4), label vector (150,)), if loaded.
  • None - if the dataset has not been loaded yet.
Source

pub fn into_data( self, ) -> Result<(Array2<f64>, Array1<&'static str>), DatasetError>

Consume the dataset and return owned features and labels.

Unlike Iris::data, which borrows the cached data, this method moves the data out and returns owned arrays directly. It needs no to_owned() clone. If the dataset has not loaded yet, it loads on first access.

This method consumes self, so you cannot use the instance afterward. If you want owned data but need to keep using the instance, use Iris::take_data instead. It takes &mut self and leaves the instance reusable.

§Returns
  • (Array2<f64>, Array1<&'static str>) - owned feature matrix with shape (150, 4) and owned label vector with shape (150,).
§Errors

Returns DatasetError if loading fails (network, file I/O, parsing, invalid labels, or a dimension mismatch).

Source

pub fn take_data( &mut self, ) -> Result<(Array2<f64>, Array1<&'static str>), DatasetError>

Take owned features and labels out of the dataset. This leaves the instance reusable.

Like Iris::into_data, this method returns owned arrays with no to_owned() clone. But instead of consuming the instance, it takes &mut self and moves the cached data out. This resets the instance to its unloaded state. The next accessor call, for example Iris::features or Iris::data, loads the dataset again.

If you are done with the instance, use Iris::into_data instead.

§Returns
  • (Array2<f64>, Array1<&'static str>) - owned feature matrix with shape (150, 4) and owned label vector with shape (150,).
§Errors

Returns DatasetError if loading fails (network, file I/O, parsing, invalid labels, or a dimension mismatch).

Trait Implementations§

Source§

impl Debug for Iris

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl MlDataset for Iris

Source§

const NAME: &'static str = "iris"

The dataset’s identifier, matching the one used in its error messages (for example, "iris", "sms_spam").
Source§

type Data = (ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>, ArrayBase<OwnedRepr<&'static str>, Dim<[usize; 1]>>)

What this loader parses into: the module’s …Data type alias. Read more
Source§

fn dataset(&self) -> &Dataset<Self::Data, DatasetError>

Borrow the underlying container.
Source§

fn dataset_mut(&mut self) -> &mut Dataset<Self::Data, DatasetError>

Borrow the underlying container mutably.
Source§

fn into_dataset(self) -> Dataset<Self::Data, DatasetError>

Consume the loader and return the underlying container.
Source§

fn load(&self) -> Result<&Self::Data, DatasetError>

Load the dataset if needed and borrow the parsed data. Read more
Source§

fn load_mut(&mut self) -> Result<&mut Self::Data, DatasetError>

Load the dataset if needed and borrow the parsed data mutably. Read more
Source§

fn peek(&self) -> Option<&Self::Data>

Borrow the parsed data without triggering loading. Read more
Source§

fn unload(&mut self) -> Option<Self::Data>

Move the parsed data out, leaving the loader reusable and unloaded. Read more
Source§

fn is_loaded(&self) -> bool

Whether the cache currently holds the data. Read more
Source§

fn storage_dir(&self) -> &str

The directory this loader stores its files in.
Source§

fn invalidate(&mut self)

Drop the cached data, keeping the loader usable. Read more
Source§

fn n_samples(&self) -> Result<usize, DatasetError>

The number of samples in the dataset, loading it if needed. Read more

Auto Trait Implementations§

§

impl !Freeze for Iris

§

impl !RefUnwindSafe for Iris

§

impl !UnwindSafe for Iris

§

impl Send for Iris

§

impl Sync for Iris

§

impl Unpin for Iris

§

impl UnsafeUnpin for Iris

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.