Skip to content

Implement Display for Dataset. #78

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: development
Choose a base branch
from
Open
Changes from all commits
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
69 changes: 69 additions & 0 deletions src/dataset/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,69 @@ pub(crate) fn deserialize_data(
Ok((x, y, num_samples, num_features))
}

impl<X: Copy + std::fmt::Debug, Y: Copy + std::fmt::Debug> std::fmt::Display for Dataset<X, Y> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.num_features == self.feature_names.len() {
struct Target<Y> {
name: String,
value: Y,
}
struct Feature<X> {
name: String,
value: X,
}
struct DataPoint<X, Y> {
labels: Vec<Target<Y>>,
features: Vec<Feature<X>>,
}
impl<X: Copy + std::fmt::Debug, Y: Copy + std::fmt::Debug> std::fmt::Display for DataPoint<X, Y> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} : {}",
self.labels
.iter()
.map(|target| format!("{}:{:?}, ", target.name, target.value))
.collect::<String>(),
self.features
.iter()
.map(|feature| format!("{}:{:?}, ", feature.name, feature.value))
.collect::<String>()
)
}
}
let mut datapoints = Vec::new();
for sample_index in 0..self.num_samples {
let mut features = Vec::new();
for feature_index in 0..self.feature_names.len() {
features.push(Feature {
name: self.feature_names[feature_index].to_owned(),
value: self.data[sample_index * self.num_features + feature_index],
});
}
let mut targets = Vec::new();
for target_index in 0..self.target_names.len() {
targets.push(Target {
name: self.target_names[target_index].to_owned(),
value: self.target[sample_index * self.target_names.len() + target_index],
});
}
datapoints.push(DataPoint {
labels: targets,
features,
})
}
let mut out = format!("{}\n", self.description);
for point in datapoints {
out.push_str(&format!("{}\n", point));
}
write!(f, "{}", out)
} else {
write!(f, "{:?}", self)
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -143,4 +206,10 @@ mod tests {
assert_eq!(m[0].len(), 5);
assert_eq!(*m[1][3], 9);
}

#[test]
fn display() {
let dataset = iris::load_dataset();
println!("{}", dataset);
}
}
Loading