use scirs2_core::ndarray::{Array1, Array2, ArrayView1, Axis};
use sklears_core::error::{Result, SklearsError};
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct ProtectedAttribute {
pub name: String,
pub column_index: usize,
pub values: Vec<String>,
pub is_binary: bool,
pub privileged_group: Option<String>,
}
impl ProtectedAttribute {
pub fn new(
name: String,
column_index: usize,
values: Vec<String>,
privileged_group: Option<String>,
) -> Self {
let is_binary = values.len() == 2;
Self {
name,
column_index,
values,
is_binary,
privileged_group,
}
}
pub fn binary(
name: String,
column_index: usize,
privileged_group: String,
unprivileged_group: String,
) -> Self {
Self {
name,
column_index,
values: vec![privileged_group.clone(), unprivileged_group],
is_binary: true,
privileged_group: Some(privileged_group),
}
}
pub fn is_privileged(&self, value: &str) -> bool {
if let Some(ref priv_group) = self.privileged_group {
value == priv_group
} else {
false
}
}
}
#[derive(Debug, Clone)]
pub struct FairnessMetrics {
pub demographic_parity: f64,
pub equalized_odds: f64,
pub equal_opportunity: f64,
pub disparate_impact: f64,
pub calibration: f64,
pub individual_fairness: f64,
}
impl FairnessMetrics {
pub fn calculate(
y_true: &Array1<i32>,
y_pred: &Array1<i32>,
y_prob: Option<&Array2<f64>>,
protected_attr: &Array1<i32>,
privileged_group: i32,
) -> Result<Self> {
let demographic_parity =
Self::calculate_demographic_parity(y_pred, protected_attr, privileged_group)?;
let equalized_odds =
Self::calculate_equalized_odds(y_true, y_pred, protected_attr, privileged_group)?;
let equal_opportunity =
Self::calculate_equal_opportunity(y_true, y_pred, protected_attr, privileged_group)?;
let disparate_impact =
Self::calculate_disparate_impact(y_pred, protected_attr, privileged_group)?;
let calibration = if let Some(probs) = y_prob {
Self::calculate_calibration(y_true, probs, protected_attr, privileged_group)?
} else {
0.0
};
let individual_fairness = Self::calculate_individual_fairness(y_pred, protected_attr)?;
Ok(Self {
demographic_parity,
equalized_odds,
equal_opportunity,
disparate_impact,
calibration,
individual_fairness,
})
}
fn calculate_demographic_parity(
y_pred: &Array1<i32>,
protected_attr: &Array1<i32>,
privileged_group: i32,
) -> Result<f64> {
let privileged_mask = protected_attr.mapv(|x| x == privileged_group);
let unprivileged_mask = protected_attr.mapv(|x| x != privileged_group);
let privileged_positive_rate = Self::positive_rate(y_pred, &privileged_mask);
let unprivileged_positive_rate = Self::positive_rate(y_pred, &unprivileged_mask);
Ok((privileged_positive_rate - unprivileged_positive_rate).abs())
}
fn calculate_equalized_odds(
y_true: &Array1<i32>,
y_pred: &Array1<i32>,
protected_attr: &Array1<i32>,
privileged_group: i32,
) -> Result<f64> {
let privileged_mask = protected_attr.mapv(|x| x == privileged_group);
let unprivileged_mask = protected_attr.mapv(|x| x != privileged_group);
let (priv_tpr, priv_fpr) = Self::calculate_tpr_fpr(y_true, y_pred, &privileged_mask);
let (unpriv_tpr, unpriv_fpr) = Self::calculate_tpr_fpr(y_true, y_pred, &unprivileged_mask);
let tpr_diff = (priv_tpr - unpriv_tpr).abs();
let fpr_diff = (priv_fpr - unpriv_fpr).abs();
Ok((tpr_diff + fpr_diff) / 2.0)
}
fn calculate_equal_opportunity(
y_true: &Array1<i32>,
y_pred: &Array1<i32>,
protected_attr: &Array1<i32>,
privileged_group: i32,
) -> Result<f64> {
let privileged_mask = protected_attr.mapv(|x| x == privileged_group);
let unprivileged_mask = protected_attr.mapv(|x| x != privileged_group);
let (priv_tpr, _) = Self::calculate_tpr_fpr(y_true, y_pred, &privileged_mask);
let (unpriv_tpr, _) = Self::calculate_tpr_fpr(y_true, y_pred, &unprivileged_mask);
Ok((priv_tpr - unpriv_tpr).abs())
}
fn calculate_disparate_impact(
y_pred: &Array1<i32>,
protected_attr: &Array1<i32>,
privileged_group: i32,
) -> Result<f64> {
let privileged_mask = protected_attr.mapv(|x| x == privileged_group);
let unprivileged_mask = protected_attr.mapv(|x| x != privileged_group);
let privileged_positive_rate = Self::positive_rate(y_pred, &privileged_mask);
let unprivileged_positive_rate = Self::positive_rate(y_pred, &unprivileged_mask);
if privileged_positive_rate > 0.0 {
Ok(unprivileged_positive_rate / privileged_positive_rate)
} else {
Ok(1.0)
}
}
fn calculate_calibration(
y_true: &Array1<i32>,
y_prob: &Array2<f64>,
protected_attr: &Array1<i32>,
privileged_group: i32,
) -> Result<f64> {
let privileged_mask = protected_attr.mapv(|x| x == privileged_group);
let unprivileged_mask = protected_attr.mapv(|x| x != privileged_group);
let priv_calibration = Self::calculate_group_calibration(y_true, y_prob, &privileged_mask);
let unpriv_calibration =
Self::calculate_group_calibration(y_true, y_prob, &unprivileged_mask);
Ok((priv_calibration - unpriv_calibration).abs())
}
fn calculate_individual_fairness(
y_pred: &Array1<i32>,
protected_attr: &Array1<i32>,
) -> Result<f64> {
let privileged_mask = protected_attr.mapv(|x| x == 1);
let priv_predictions: Vec<f64> = y_pred
.iter()
.zip(privileged_mask.iter())
.filter(|(_, &is_priv)| is_priv)
.map(|(&pred, _)| pred as f64)
.collect();
let unpriv_predictions: Vec<f64> = y_pred
.iter()
.zip(privileged_mask.iter())
.filter(|(_, &is_priv)| !is_priv)
.map(|(&pred, _)| pred as f64)
.collect();
let priv_var = Self::calculate_variance(&priv_predictions);
let unpriv_var = Self::calculate_variance(&unpriv_predictions);
Ok((priv_var - unpriv_var).abs())
}
fn positive_rate(y_pred: &Array1<i32>, mask: &Array1<bool>) -> f64 {
let total: i32 = mask.iter().map(|&x| if x { 1 } else { 0 }).sum();
if total == 0 {
return 0.0;
}
let positive: i32 = y_pred
.iter()
.zip(mask.iter())
.map(|(&pred, &include)| if include && pred > 0 { 1 } else { 0 })
.sum();
positive as f64 / total as f64
}
fn calculate_tpr_fpr(
y_true: &Array1<i32>,
y_pred: &Array1<i32>,
mask: &Array1<bool>,
) -> (f64, f64) {
let mut tp = 0;
let mut fp = 0;
let mut tn = 0;
let mut fn_count = 0;
for ((&true_label, &pred_label), &include) in
y_true.iter().zip(y_pred.iter()).zip(mask.iter())
{
if include {
match (true_label > 0, pred_label > 0) {
(true, true) => tp += 1,
(false, true) => fp += 1,
(false, false) => tn += 1,
(true, false) => fn_count += 1,
}
}
}
let tpr = if tp + fn_count > 0 {
tp as f64 / (tp + fn_count) as f64
} else {
0.0
};
let fpr = if fp + tn > 0 {
fp as f64 / (fp + tn) as f64
} else {
0.0
};
(tpr, fpr)
}
fn calculate_group_calibration(
y_true: &Array1<i32>,
y_prob: &Array2<f64>,
mask: &Array1<bool>,
) -> f64 {
let mut calibration_error = 0.0;
let mut count = 0;
for ((&true_label, prob_row), &include) in y_true
.iter()
.zip(y_prob.axis_iter(Axis(0)))
.zip(mask.iter())
{
if include {
let predicted_prob = prob_row[1]; let actual = if true_label > 0 { 1.0 } else { 0.0 };
calibration_error += (predicted_prob - actual).abs();
count += 1;
}
}
if count > 0 {
calibration_error / count as f64
} else {
0.0
}
}
fn calculate_variance(values: &[f64]) -> f64 {
if values.is_empty() {
return 0.0;
}
let mean = values.iter().sum::<f64>() / values.len() as f64;
let variance =
values.iter().map(|&x| (x - mean).powi(2)).sum::<f64>() / values.len() as f64;
variance
}
}
#[derive(Debug, Clone)]
pub struct FairnessConstraints {
pub max_demographic_parity: f64,
pub max_equalized_odds: f64,
pub min_disparate_impact: f64,
pub protected_attributes: Vec<ProtectedAttribute>,
pub fairness_weight: f64,
pub enable_preprocessing: bool,
pub enable_inprocessing: bool,
pub enable_postprocessing: bool,
}
impl Default for FairnessConstraints {
fn default() -> Self {
Self {
max_demographic_parity: 0.1,
max_equalized_odds: 0.1,
min_disparate_impact: 0.8,
protected_attributes: Vec::new(),
fairness_weight: 0.1,
enable_preprocessing: true,
enable_inprocessing: true,
enable_postprocessing: false,
}
}
}
#[derive(Debug, Clone)]
pub struct FairSplittingCriterion {
pub base_criterion: SplitCriterion,
pub fairness_constraints: FairnessConstraints,
pub fairness_weight: f64,
}
#[derive(Debug, Clone)]
pub enum SplitCriterion {
Gini,
Entropy,
MSE,
}
impl FairSplittingCriterion {
pub fn new(base_criterion: SplitCriterion, fairness_constraints: FairnessConstraints) -> Self {
let fairness_weight = fairness_constraints.fairness_weight;
Self {
base_criterion,
fairness_constraints,
fairness_weight,
}
}
pub fn evaluate_split(
&self,
left_y: &Array1<i32>,
right_y: &Array1<i32>,
left_protected: &Array1<i32>,
right_protected: &Array1<i32>,
protected_attr: &ProtectedAttribute,
) -> Result<f64> {
let left_impurity = self.calculate_impurity(left_y)?;
let right_impurity = self.calculate_impurity(right_y)?;
let n_left = left_y.len() as f64;
let n_right = right_y.len() as f64;
let n_total = n_left + n_right;
let weighted_impurity =
(n_left / n_total) * left_impurity + (n_right / n_total) * right_impurity;
let fairness_penalty = self.calculate_fairness_penalty(
left_y,
right_y,
left_protected,
right_protected,
protected_attr,
)?;
let score = weighted_impurity + self.fairness_weight * fairness_penalty;
Ok(score)
}
fn calculate_impurity(&self, y: &Array1<i32>) -> Result<f64> {
if y.is_empty() {
return Ok(0.0);
}
match &self.base_criterion {
SplitCriterion::Gini => Ok(self.gini_impurity(y)),
SplitCriterion::Entropy => Ok(self.entropy_impurity(y)),
SplitCriterion::MSE => Ok(self.mse_impurity(y)),
}
}
fn gini_impurity(&self, y: &Array1<i32>) -> f64 {
let mut class_counts = HashMap::new();
for &label in y.iter() {
*class_counts.entry(label).or_insert(0) += 1;
}
let n = y.len() as f64;
let mut gini = 1.0;
for &count in class_counts.values() {
let p = count as f64 / n;
gini -= p * p;
}
gini
}
fn entropy_impurity(&self, y: &Array1<i32>) -> f64 {
let mut class_counts = HashMap::new();
for &label in y.iter() {
*class_counts.entry(label).or_insert(0) += 1;
}
let n = y.len() as f64;
let mut entropy = 0.0;
for &count in class_counts.values() {
if count > 0 {
let p = count as f64 / n;
entropy -= p * p.log2();
}
}
entropy
}
fn mse_impurity(&self, y: &Array1<i32>) -> f64 {
if y.is_empty() {
return 0.0;
}
let mean = y.iter().map(|&x| x as f64).sum::<f64>() / y.len() as f64;
let mse = y.iter().map(|&x| (x as f64 - mean).powi(2)).sum::<f64>() / y.len() as f64;
mse
}
fn calculate_fairness_penalty(
&self,
left_y: &Array1<i32>,
right_y: &Array1<i32>,
left_protected: &Array1<i32>,
right_protected: &Array1<i32>,
protected_attr: &ProtectedAttribute,
) -> Result<f64> {
let privileged_value = if let Some(ref priv_group) = protected_attr.privileged_group {
if priv_group == "1" || priv_group.to_lowercase() == "true" {
1
} else {
0
}
} else {
1 };
let left_dp = if !left_y.is_empty() {
FairnessMetrics::calculate_demographic_parity(left_y, left_protected, privileged_value)
.unwrap_or(0.0)
} else {
0.0
};
let right_dp = if !right_y.is_empty() {
FairnessMetrics::calculate_demographic_parity(
right_y,
right_protected,
privileged_value,
)
.unwrap_or(0.0)
} else {
0.0
};
let n_left = left_y.len() as f64;
let n_right = right_y.len() as f64;
let n_total = n_left + n_right;
if n_total > 0.0 {
let weighted_penalty = (n_left / n_total) * left_dp + (n_right / n_total) * right_dp;
Ok(weighted_penalty)
} else {
Ok(0.0)
}
}
}
pub struct FairDecisionTreeBuilder {
pub max_depth: Option<usize>,
pub min_samples_split: usize,
pub min_samples_leaf: usize,
pub criterion: FairSplittingCriterion,
pub random_state: Option<u64>,
}
impl FairDecisionTreeBuilder {
pub fn new(criterion: FairSplittingCriterion) -> Self {
Self {
max_depth: None,
min_samples_split: 2,
min_samples_leaf: 1,
criterion,
random_state: None,
}
}
pub fn fit(
&self,
x: &Array2<f64>,
y: &Array1<i32>,
protected_attrs: &Array2<i32>,
) -> Result<FairDecisionTree> {
let n_samples = x.nrows();
let sample_indices: Vec<usize> = (0..n_samples).collect();
let root = self.build_tree_recursive(x, y, protected_attrs, &sample_indices, 0)?;
Ok(FairDecisionTree {
root,
feature_importances: self.calculate_feature_importances(x, y)?,
fairness_metrics: None,
protected_attributes: self
.criterion
.fairness_constraints
.protected_attributes
.clone(),
})
}
fn build_tree_recursive(
&self,
x: &Array2<f64>,
y: &Array1<i32>,
protected_attrs: &Array2<i32>,
sample_indices: &[usize],
depth: usize,
) -> Result<FairTreeNode> {
let n_samples = sample_indices.len();
if self.should_stop(n_samples, depth, y, sample_indices) {
return self.create_leaf_node(y, sample_indices);
}
let best_split = self.find_best_fair_split(x, y, protected_attrs, sample_indices)?;
if let Some((feature_idx, threshold, left_indices, right_indices)) = best_split {
let left_child = Box::new(self.build_tree_recursive(
x,
y,
protected_attrs,
&left_indices,
depth + 1,
)?);
let right_child = Box::new(self.build_tree_recursive(
x,
y,
protected_attrs,
&right_indices,
depth + 1,
)?);
Ok(FairTreeNode {
is_leaf: false,
feature_idx: Some(feature_idx),
threshold: Some(threshold),
prediction: None,
left_child: Some(left_child),
right_child: Some(right_child),
sample_count: n_samples,
fairness_score: 0.0,
})
} else {
self.create_leaf_node(y, sample_indices)
}
}
fn should_stop(
&self,
n_samples: usize,
depth: usize,
y: &Array1<i32>,
sample_indices: &[usize],
) -> bool {
if n_samples < self.min_samples_split {
return true;
}
if let Some(max_depth) = self.max_depth {
if depth >= max_depth {
return true;
}
}
let first_label = y[sample_indices[0]];
if sample_indices.iter().all(|&idx| y[idx] == first_label) {
return true;
}
false
}
fn create_leaf_node(&self, y: &Array1<i32>, sample_indices: &[usize]) -> Result<FairTreeNode> {
let mut class_counts = HashMap::new();
for &idx in sample_indices {
*class_counts.entry(y[idx]).or_insert(0) += 1;
}
let prediction = class_counts
.iter()
.max_by_key(|(_, &count)| count)
.map(|(&class, _)| class)
.unwrap_or(0);
Ok(FairTreeNode {
is_leaf: true,
feature_idx: None,
threshold: None,
prediction: Some(prediction),
left_child: None,
right_child: None,
sample_count: sample_indices.len(),
fairness_score: 0.0,
})
}
fn find_best_fair_split(
&self,
x: &Array2<f64>,
y: &Array1<i32>,
protected_attrs: &Array2<i32>,
sample_indices: &[usize],
) -> Result<Option<(usize, f64, Vec<usize>, Vec<usize>)>> {
let n_features = x.ncols();
let mut best_score = f64::INFINITY;
let mut best_split = None;
for feature_idx in 0..n_features {
let mut feature_values: Vec<f64> = sample_indices
.iter()
.map(|&idx| x[[idx, feature_idx]])
.collect();
feature_values.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
feature_values.dedup_by(|a, b| (*a - *b).abs() < 1e-10);
for i in 0..feature_values.len() - 1 {
let threshold = (feature_values[i] + feature_values[i + 1]) / 2.0;
let (left_indices, right_indices) =
self.split_samples(x, sample_indices, feature_idx, threshold);
if left_indices.len() < self.min_samples_leaf
|| right_indices.len() < self.min_samples_leaf
{
continue;
}
let score = self.evaluate_split_fairness(
y,
protected_attrs,
&left_indices,
&right_indices,
)?;
if score < best_score {
best_score = score;
best_split = Some((feature_idx, threshold, left_indices, right_indices));
}
}
}
Ok(best_split)
}
fn split_samples(
&self,
x: &Array2<f64>,
sample_indices: &[usize],
feature_idx: usize,
threshold: f64,
) -> (Vec<usize>, Vec<usize>) {
let mut left_indices = Vec::new();
let mut right_indices = Vec::new();
for &idx in sample_indices {
if x[[idx, feature_idx]] <= threshold {
left_indices.push(idx);
} else {
right_indices.push(idx);
}
}
(left_indices, right_indices)
}
fn evaluate_split_fairness(
&self,
y: &Array1<i32>,
protected_attrs: &Array2<i32>,
left_indices: &[usize],
right_indices: &[usize],
) -> Result<f64> {
let left_y: Array1<i32> = left_indices.iter().map(|&idx| y[idx]).collect();
let right_y: Array1<i32> = right_indices.iter().map(|&idx| y[idx]).collect();
if !self
.criterion
.fairness_constraints
.protected_attributes
.is_empty()
{
let protected_attr = &self.criterion.fairness_constraints.protected_attributes[0];
let attr_col = protected_attr.column_index;
let left_protected: Array1<i32> = left_indices
.iter()
.map(|&idx| protected_attrs[[idx, attr_col]])
.collect();
let right_protected: Array1<i32> = right_indices
.iter()
.map(|&idx| protected_attrs[[idx, attr_col]])
.collect();
self.criterion.evaluate_split(
&left_y,
&right_y,
&left_protected,
&right_protected,
protected_attr,
)
} else {
let left_impurity = self.criterion.calculate_impurity(&left_y)?;
let right_impurity = self.criterion.calculate_impurity(&right_y)?;
let n_left = left_y.len() as f64;
let n_right = right_y.len() as f64;
let n_total = n_left + n_right;
Ok((n_left / n_total) * left_impurity + (n_right / n_total) * right_impurity)
}
}
fn calculate_feature_importances(
&self,
x: &Array2<f64>,
y: &Array1<i32>,
) -> Result<Array1<f64>> {
let n_features = x.ncols();
Ok(Array1::ones(n_features) / n_features as f64) }
}
#[derive(Debug, Clone)]
pub struct FairTreeNode {
pub is_leaf: bool,
pub feature_idx: Option<usize>,
pub threshold: Option<f64>,
pub prediction: Option<i32>,
pub left_child: Option<Box<FairTreeNode>>,
pub right_child: Option<Box<FairTreeNode>>,
pub sample_count: usize,
pub fairness_score: f64,
}
#[derive(Debug)]
pub struct FairDecisionTree {
pub root: FairTreeNode,
pub feature_importances: Array1<f64>,
pub fairness_metrics: Option<FairnessMetrics>,
pub protected_attributes: Vec<ProtectedAttribute>,
}
impl FairDecisionTree {
pub fn predict(&self, x: &Array2<f64>) -> Result<Array1<i32>> {
let n_samples = x.nrows();
let mut predictions = Array1::zeros(n_samples);
for i in 0..n_samples {
let sample = x.row(i);
predictions[i] = self.predict_single(&self.root, sample.view())?;
}
Ok(predictions)
}
fn predict_single(&self, node: &FairTreeNode, sample: ArrayView1<f64>) -> Result<i32> {
if node.is_leaf {
Ok(node.prediction.unwrap_or(0))
} else {
let feature_idx = node.feature_idx.expect("operation should succeed");
let threshold = node.threshold.expect("operation should succeed");
if sample[feature_idx] <= threshold {
if let Some(ref left_child) = node.left_child {
self.predict_single(left_child, sample)
} else {
Ok(0)
}
} else {
if let Some(ref right_child) = node.right_child {
self.predict_single(right_child, sample)
} else {
Ok(0)
}
}
}
}
pub fn evaluate_fairness(
&mut self,
x: &Array2<f64>,
y_true: &Array1<i32>,
protected_attrs: &Array2<i32>,
) -> Result<&FairnessMetrics> {
let y_pred = self.predict(x)?;
if !self.protected_attributes.is_empty() {
let protected_attr = &self.protected_attributes[0];
let attr_col = protected_attr.column_index;
let protected_values: Array1<i32> = (0..x.nrows())
.map(|i| protected_attrs[[i, attr_col]])
.collect();
let privileged_value = if let Some(ref priv_group) = protected_attr.privileged_group {
if priv_group == "1" || priv_group.to_lowercase() == "true" {
1
} else {
0
}
} else {
1
};
let metrics = FairnessMetrics::calculate(
y_true,
&y_pred,
None,
&protected_values,
privileged_value,
)?;
self.fairness_metrics = Some(metrics);
Ok(self.fairness_metrics.as_ref().expect("operation should succeed"))
} else {
Err(sklears_core::error::SklearsError::InvalidData {
reason: "No protected attributes defined".to_string(),
})
}
}
pub fn feature_importances(&self) -> &Array1<f64> {
&self.feature_importances
}
}
#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
use super::*;
use scirs2_core::ndarray::Array2;
#[test]
fn test_protected_attribute_creation() {
let attr = ProtectedAttribute::binary(
"gender".to_string(),
0,
"male".to_string(),
"female".to_string(),
);
assert_eq!(attr.name, "gender");
assert!(attr.is_binary);
assert!(attr.is_privileged("male"));
assert!(!attr.is_privileged("female"));
}
#[test]
fn test_fairness_metrics_calculation() {
let y_true = Array1::from(vec![1, 1, 0, 0, 1, 0]);
let y_pred = Array1::from(vec![1, 0, 0, 1, 1, 0]);
let protected = Array1::from(vec![1, 1, 0, 0, 1, 0]);
let metrics = FairnessMetrics::calculate(&y_true, &y_pred, None, &protected, 1);
assert!(metrics.is_ok());
let metrics = metrics.expect("operation should succeed");
assert!(metrics.demographic_parity >= 0.0);
}
#[test]
fn test_fair_splitting_criterion() {
let constraints = FairnessConstraints::default();
let criterion = FairSplittingCriterion::new(SplitCriterion::Gini, constraints);
let left_y = Array1::from(vec![1, 1, 0]);
let right_y = Array1::from(vec![0, 0, 1]);
let left_protected = Array1::from(vec![1, 0, 1]);
let right_protected = Array1::from(vec![0, 1, 0]);
let attr =
ProtectedAttribute::binary("test".to_string(), 0, "1".to_string(), "0".to_string());
let score =
criterion.evaluate_split(&left_y, &right_y, &left_protected, &right_protected, &attr);
assert!(score.is_ok());
}
#[test]
fn test_fair_decision_tree_creation() {
let constraints = FairnessConstraints::default();
let criterion = FairSplittingCriterion::new(SplitCriterion::Gini, constraints);
let builder = FairDecisionTreeBuilder::new(criterion);
assert_eq!(builder.min_samples_split, 2);
assert_eq!(builder.min_samples_leaf, 1);
}
}