dataset_ml/iris.rs
1//! Iris flower dataset.
2//!
3//! The classic Fisher Iris dataset for multi-class classification.
4//! It contains measurements for three Iris species: `setosa`, `versicolor`,
5//! and `virginica`.
6//!
7//! **Features (4):**
8//! - `sepal_length` - sepal length in cm
9//! - `sepal_width` - sepal width in cm
10//! - `petal_length` - petal length in cm
11//! - `petal_width` - petal width in cm
12//!
13//! **Target:** `species` - one of `setosa`, `versicolor`, or `virginica`
14//!
15//! **Samples:** 150 total, with 50 samples per species
16//! **Application:** Multi-class classification / species recognition
17//!
18//! **Source:** UCI Machine Learning Repository
19//! <https://doi.org/10.24432/C56C76>
20
21use csv::ReaderBuilder;
22use dataset_core::{Dataset, DatasetError, acquire_dataset, download_to};
23use ndarray::{Array1, Array2};
24use serde::Deserialize;
25use std::fs::File;
26
27/// The URL for the Iris dataset.
28///
29/// # Citation
30///
31/// R. A. Fisher. "Iris," UCI Machine Learning Repository, \[Online\].
32/// Available: <https://doi.org/10.24432/C56C76>
33const IRIS_DATA_URL: &str = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv";
34
35/// The name of the Iris dataset file.
36const IRIS_FILENAME: &str = "iris.csv";
37
38/// The SHA256 hash of the Iris dataset file.
39const IRIS_SHA256: &str = "c52742e50315a99f956a383faedf7575552675f6409ef0f9a47076dd08479930";
40
41/// The name of the dataset
42const IRIS_DATASET_NAME: &str = "iris";
43
44/// Type alias for the Iris dataset: (features, labels).
45type IrisData = (Array2<f64>, Array1<&'static str>);
46
47/// One CSV record of the Iris dataset: four `f64` measurements followed by the
48/// species label.
49///
50/// Fields are declared in CSV column order and deserialized **positionally**
51/// (the loader disables csv's header handling), so this struct is independent
52/// of the exact header spelling and of any byte-order mark on the header row.
53#[derive(Deserialize)]
54struct IrisRecord {
55 sepal_length: f64,
56 sepal_width: f64,
57 petal_length: f64,
58 petal_width: f64,
59 species: String,
60}
61
62/// A struct representing the Iris dataset with lazy loading.
63///
64/// The dataset is not loaded until you call one of the data accessor methods.
65/// Once loaded, the data is cached for subsequent accesses.
66///
67/// # About Dataset
68///
69/// The Iris dataset is a classic dataset for classification tasks. It includes three iris species
70/// with 50 samples each as well as some properties about each flower. One flower species is
71/// linearly separable from the other two, but the other two are not linearly separable from each other.
72///
73/// Features:
74/// - sepal length in cm
75/// - sepal width in cm
76/// - petal length in cm
77/// - petal width in cm
78///
79/// Labels:
80/// - species name (in `&str`): `"setosa"`, `"versicolor"`, `"virginica"`
81///
82/// See more information at <https://archive.ics.uci.edu/dataset/53/iris>
83///
84/// # Citation
85///
86/// R. A. Fisher. "Iris," UCI Machine Learning Repository, \[Online\].
87/// Available: <https://doi.org/10.24432/C56C76>
88///
89/// # Thread Safety
90///
91/// This struct automatically implements `Send` and `Sync` (All fields implement them), making it safe to share across threads.
92/// The internal [`Dataset`] ensures thread-safe lazy initialization.
93///
94/// # Example
95/// ```no_run
96/// use dataset_ml::iris::Iris;
97///
98/// let download_dir = "./iris"; // the code will create the directory if it doesn't exist
99///
100/// let mut dataset = Iris::new(download_dir);
101/// let features = dataset.features().unwrap();
102/// let labels = dataset.labels().unwrap();
103///
104/// let (features, labels) = dataset.data().unwrap(); // this is also a way to get features and labels
105/// assert_eq!(features.shape(), &[150, 4]);
106/// assert_eq!(labels.len(), 150);
107///
108/// // `get_data()` borrows the cached arrays without reloading; `get_data_mut()`
109/// // edits them in place — no clone, no reload, the change stays cached. Prefer
110/// // this over cloning with `.to_owned()` when you only need to tweak values.
111/// if let Some((features, labels)) = dataset.get_data_mut() {
112/// features[[0, 0]] = 5.5;
113/// labels[0] = "setosa-modified";
114/// }
115/// assert!(dataset.get_data().is_some());
116///
117/// // `take_data()` moves owned arrays out (no `to_owned()` clone) and leaves the
118/// // instance reusable — the next access reloads from the cached file.
119/// let (owned_features, owned_labels) = dataset.take_data().unwrap();
120/// assert_eq!(owned_features.shape(), &[150, 4]);
121/// assert_eq!(owned_labels.len(), 150);
122///
123/// // `into_data()` also returns owned arrays with no clone, but consumes the
124/// // instance (use it when you are done with the dataset).
125/// let (owned_features, owned_labels) = dataset.into_data().unwrap();
126/// assert_eq!(owned_features.shape(), &[150, 4]);
127/// assert_eq!(owned_labels.len(), 150);
128/// ```
129#[derive(Debug)]
130pub struct Iris {
131 dataset: Dataset<IrisData, DatasetError>,
132}
133
134impl Iris {
135 /// Create a new Iris instance without loading data.
136 ///
137 /// The dataset will be loaded lazily when you first call any data accessor method.
138 /// This is a lightweight operation that only stores the storage directory.
139 ///
140 /// # Parameters
141 ///
142 /// - `storage_dir` - Directory where the dataset will be stored.
143 ///
144 /// # Returns
145 ///
146 /// - `Self` - `Iris` instance ready for lazy loading.
147 pub fn new(storage_dir: &str) -> Self {
148 Iris {
149 dataset: Dataset::new(storage_dir, Self::load_data),
150 }
151 }
152
153 /// Acquire and parse the Iris dataset.
154 fn load_data(dir: &str) -> Result<IrisData, DatasetError> {
155 // Prepare the dataset file
156 let file_path = acquire_dataset(
157 dir,
158 IRIS_FILENAME,
159 IRIS_DATASET_NAME,
160 Some(IRIS_SHA256),
161 |temp_path| {
162 download_to(IRIS_DATA_URL, temp_path, None)?;
163 Ok(temp_path.join(IRIS_FILENAME))
164 },
165 )?;
166
167 // csv deserializes into the struct
168 let file = File::open(&file_path)?;
169 let mut rdr = ReaderBuilder::new().has_headers(false).from_reader(file);
170
171 let mut features = Vec::new();
172 let mut labels = Vec::new();
173
174 for (idx, result) in rdr.deserialize::<IrisRecord>().skip(1).enumerate() {
175 let IrisRecord {
176 sepal_length,
177 sepal_width,
178 petal_length,
179 petal_width,
180 species,
181 } = result.map_err(|e| DatasetError::csv_read_error(IRIS_DATASET_NAME, e))?;
182 let line_num = idx + 2; // +1 for 0-indexed, +1 for header
183
184 features.push(sepal_length);
185 features.push(sepal_width);
186 features.push(petal_length);
187 features.push(petal_width);
188
189 labels.push(match species.as_str() {
190 "setosa" => "setosa",
191 "versicolor" => "versicolor",
192 "virginica" => "virginica",
193 other => {
194 return Err(DatasetError::invalid_value(
195 IRIS_DATASET_NAME,
196 "label",
197 other,
198 line_num,
199 ));
200 }
201 });
202 }
203
204 let n_samples = labels.len();
205 if n_samples == 0 {
206 return Err(DatasetError::empty_dataset(IRIS_DATASET_NAME));
207 }
208
209 // Iris has a fixed schema of 4 numeric features per sample.
210 let features_array = Array2::from_shape_vec((n_samples, 4), features)
211 .map_err(|e| DatasetError::array_shape_error(IRIS_DATASET_NAME, "features", e))?;
212 let labels_array = Array1::from_vec(labels);
213
214 Ok((features_array, labels_array))
215 }
216
217 /// Get a reference to the feature matrix.
218 ///
219 /// This method triggers lazy loading on first call. Subsequent calls return
220 /// the cached data instantly.
221 ///
222 /// # Returns
223 ///
224 /// - `&Array2<f64>` - Reference to feature matrix with shape `(150, 4)` containing:
225 /// - sepal length in cm
226 /// - sepal width in cm
227 /// - petal length in cm
228 /// - petal width in cm
229 ///
230 /// # Errors
231 ///
232 /// Returns `DatasetError` if:
233 /// - Download fails due to network issues
234 /// - File extraction or I/O operations fail
235 /// - Data format is invalid (wrong number of columns, unparseable values, or invalid labels)
236 /// - Dataset size doesn't match expected dimensions (150 samples, 4 features)
237 pub fn features(&self) -> Result<&Array2<f64>, DatasetError> {
238 Ok(&self.dataset.load()?.0)
239 }
240
241 /// Get a reference to the labels vector.
242 ///
243 /// This method triggers lazy loading on first call. Subsequent calls return
244 /// the cached data instantly.
245 ///
246 /// # Returns
247 ///
248 /// - `&Array1<&'static str>` - Reference to labels vector with shape `(150,)` containing species names (`"setosa"`, `"versicolor"`, `"virginica"`)
249 ///
250 /// # Errors
251 ///
252 /// Returns `DatasetError` if:
253 /// - Download fails due to network issues
254 /// - File extraction or I/O operations fail
255 /// - Data format is invalid (wrong number of columns, unparseable values, or invalid labels)
256 /// - Dataset size doesn't match expected dimensions (150 samples)
257 pub fn labels(&self) -> Result<&Array1<&'static str>, DatasetError> {
258 Ok(&self.dataset.load()?.1)
259 }
260
261 /// Get both features and labels as references.
262 ///
263 /// This method triggers lazy loading on first call. Subsequent calls return
264 /// the cached data instantly.
265 ///
266 /// # Returns
267 ///
268 /// - `&IrisData` - reference to the cached `(features, labels)` tuple: the
269 /// feature matrix has shape `(150, 4)` (sepal length/width, petal
270 /// length/width, all in cm) and the label vector has shape `(150,)`
271 /// containing species names (`"setosa"`, `"versicolor"`, `"virginica"`).
272 ///
273 /// # Errors
274 ///
275 /// Returns `DatasetError` if:
276 /// - Download fails due to network issues
277 /// - File extraction or I/O operations fail
278 /// - Data format is invalid (wrong number of columns, unparseable values, or invalid labels)
279 /// - Dataset size doesn't match expected dimensions (150 samples, 4 features)
280 pub fn data(&self) -> Result<&IrisData, DatasetError> {
281 self.dataset.load()
282 }
283
284 /// Get both features and labels as references **without** triggering loading.
285 ///
286 /// Unlike [`Iris::data`], which loads the dataset on first call, this never
287 /// runs the loader: if the data has not been loaded yet, it returns `None`
288 /// instead of downloading and parsing. Use it when you only want the data if
289 /// it is already cached and want to avoid paying the download/parse cost
290 /// otherwise.
291 ///
292 /// # Returns
293 ///
294 /// - `Some(&IrisData)` - reference to the cached `(features, labels)` tuple
295 /// (feature matrix `(150, 4)`, label vector `(150,)`), if loaded.
296 /// - `None` - if the dataset has not been loaded yet.
297 pub fn get_data(&self) -> Option<&IrisData> {
298 self.dataset.get()
299 }
300
301 /// Get mutable references to features and labels for **in-place** editing.
302 ///
303 /// This lets you modify the cached arrays directly (e.g. normalize features,
304 /// replace label values) with no `to_owned()` clone and without removing them
305 /// from the cache: the changes persist, so later [`Iris::features`],
306 /// [`Iris::data`], or [`Iris::get_data`] calls observe them.
307 ///
308 /// Like [`Iris::get_data`], this does **not** trigger loading: it returns
309 /// `None` if the dataset has not been loaded. Call a loading accessor (e.g.
310 /// [`Iris::data`]) first if you need to ensure the data is present.
311 ///
312 /// # Returns
313 ///
314 /// - `Some(&mut IrisData)` - mutable reference to the cached
315 /// `(features, labels)` tuple (feature matrix `(150, 4)`, label vector
316 /// `(150,)`), if loaded.
317 /// - `None` - if the dataset has not been loaded yet.
318 pub fn get_data_mut(&mut self) -> Option<&mut IrisData> {
319 self.dataset.get_mut()
320 }
321
322 /// Consume the dataset and return **owned** features and labels.
323 ///
324 /// Unlike [`Iris::data`], which borrows the cached data, this moves it out and
325 /// returns owned arrays directly — no `to_owned()` clone needed. The dataset is
326 /// loaded on first access if it has not been loaded yet.
327 ///
328 /// This **consumes** `self`, so the instance cannot be used afterwards. If you
329 /// want owned data but need to keep using the instance, use [`Iris::take_data`]
330 /// instead — it takes `&mut self` and leaves the instance reusable.
331 ///
332 /// # Returns
333 ///
334 /// - `(Array2<f64>, Array1<&'static str>)` - owned feature matrix with shape
335 /// `(150, 4)` and owned label vector with shape `(150,)`.
336 ///
337 /// # Errors
338 ///
339 /// Returns `DatasetError` if loading fails (network, file I/O, parsing, invalid
340 /// labels, or a dimension mismatch).
341 pub fn into_data(self) -> Result<IrisData, DatasetError> {
342 self.dataset.load()?;
343 Ok(self
344 .dataset
345 .into_inner()
346 .expect("data is present after a successful load"))
347 }
348
349 /// Take **owned** features and labels out of the dataset, leaving it reusable.
350 ///
351 /// Like [`Iris::into_data`], this returns owned arrays with no `to_owned()`
352 /// clone. But instead of consuming the instance, it takes `&mut self` and moves
353 /// the cached data out, resetting the instance to its unloaded state: the next
354 /// accessor call (e.g. [`Iris::features`] or [`Iris::data`]) loads the dataset
355 /// again.
356 ///
357 /// Use [`Iris::into_data`] instead if you are done with the instance.
358 ///
359 /// # Returns
360 ///
361 /// - `(Array2<f64>, Array1<&'static str>)` - owned feature matrix with shape
362 /// `(150, 4)` and owned label vector with shape `(150,)`.
363 ///
364 /// # Errors
365 ///
366 /// Returns `DatasetError` if loading fails (network, file I/O, parsing, invalid
367 /// labels, or a dimension mismatch).
368 pub fn take_data(&mut self) -> Result<IrisData, DatasetError> {
369 self.dataset.load()?;
370 Ok(self
371 .dataset
372 .take()
373 .expect("data is present after a successful load"))
374 }
375}