Ethical Frameworks for Responsible AI

In the final section of this course, we’ll talk about the bigger picture of AI Engineering, including Job Trends and Career Development advice. First, though, we’re going to cover the important topic of Ethical AI.

Of all the information in this lesson, the most important to pay attention to are the “Common X” examples. Identifying ethical concerns can be difficult, and these examples should help train us to notice them more often.

As AI engineers, we should be concerned with building systems that are fair, transparent, and aligned with societal values. Here are four ethical frameworks that can help guide us.

This Lesson Will Cover
  • 🏛️ Ethical Frameworks for Responsible AI
  • ⚖️ Fairness Metrics and Debiasing Techniques
  • 🔍 Model Transparency and Explainability
  • 🛡️ Privacy-Preserving AI Methods
  • 📊 Responsible Data Collection and Usage
Ethical AI Pillars Mind Map
A high‑level mind‑map summarizing fairness, transparency, privacy, and responsible data practices for ethical AI.

Fairness Metrics and Debiasing Techniques

Why It’s Important

AI models often reflect and amplify biases present in the data used to train them. This can result in unfair outcomes, such as discrimination in hiring or credit decisions.

Ensuring fairness builds trust in AI systems.

Common Biases

Financial & Employment

  • Historical discrimination in lending data leading to lower approval rates for minority applicants
  • Resume screening tools favoring male candidates due to past hiring patterns
  • Income prediction models underestimating earnings for women

Healthcare & Medical

  • Medical diagnosis models showing reduced accuracy for elderly patients

Technology & Recognition Systems

  • Facial recognition systems performing poorly on darker skin tones due to training data imbalance
  • Speech recognition systems struggling with non-native English accents

Recommendations & Services

  • Product recommendation engines reinforcing gender stereotypes in suggested items
  • Geographic bias in service availability predictions disadvantaging rural areas

Language & Cultural

  • Language models perpetuating cultural stereotypes in text generation

Criminal Justice

  • Recidivism prediction systems showing racial disparities in risk assessments based on socioeconomic factors

Key Concepts

  • Fairness Metrics: Techniques for measuring bias in models, such as demographic parity, equal opportunity, or disparate impact.
  • Debiasing Methods: Strategies like reweighting, oversampling, or adversarial debiasing to mitigate unfairness in datasets and model outputs.
Bias Detection and Mitigation in ML - Workflow Flowchart
Workflow flowchart for bias detection and mitigation in ML.

Technical Example

Suppose we’re building a model to predict loan approvals. Without considering fairness, the model might inadvertently favor one demographic group over another. By applying fairness metrics, we can evaluate where the model falls short and use debiasing methods to address these gaps.

Using python, this could look something like the following, where we:

  1. Create a sample loan approval dataset
  2. Measure bias using disparate impact metric
  3. Apply reweighing to mitigate bias
  4. Train a fair model using the transformed data

Keep in mind that this example assumes a common bias that is not present in all datasets. This is not a formula to apply to all datasets that have genders.

In the example below, we manually added a bias in the form of gender approval data:

    'gender': [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] * 100, # Female=0, Male=1
    'approved': [1, 0, 0, 0, 0, 1, 1, 1, 0, 0] * 100, # Approved=1, Not approved=0

Notice that 1/5 females (label 0) in the training data were approved, whereas 3/5 males (label 1) were approved.

We’ll address this bias using aif360.

Bar Chart Reveals Initial Gender Bias in Synthetic Loan Approval Rates Before Any Fairness Intervention
Raw approval rates generated in this loan‑approval toy data set (n = 1,000). Bars for "Female (0)" and "Male (1)" highlight a 40‑percentage‑point gap (20% versus 60%) prior to any modelling or fairness corrections.
# Step 1: Import required libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from aif360.datasets import BinaryLabelDataset
from aif360.metrics import BinaryLabelDatasetMetric
from aif360.algorithms.preprocessing import Reweighing

# Step 2: Create synthetic dataset with loan application features
np.random.seed(42)  # Setting seed for reproducibility
data = pd.DataFrame({
    'income': np.random.normal(50000, 20000, 1000),
    'credit_score': np.random.normal(700, 50, 1000),
    'age': np.random.randint(18, 80, 1000),
    'gender': [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] * 100, # Female=0, Male=1
    'approved': [1, 0, 0, 0, 0, 1, 1, 1, 0, 0] * 100, # Approved=1, Not approved=0
})

# Calculate approval rates by gender
approval_by_gender = data.groupby('gender')['approved'].mean()
print("\nApproval Rates by Gender:")
print(f"Female (0): {approval_by_gender[0]:.2f}")
print(f"Male (1): {approval_by_gender[1]:.2f}")
print(f"Difference: {abs(approval_by_gender[1] - approval_by_gender[0]):.2f}")

# Step 3: Convert to AIF360 dataset format for bias analysis
protected_attribute = 'gender'
label = 'approved'
features = ['income', 'credit_score', 'age']

binary_data = BinaryLabelDataset(
    df=data,
    label_names=[label],
    protected_attribute_names=[protected_attribute],
    favorable_label=1,
    unfavorable_label=0
)

# Step 4: Measure initial bias using available metrics
metrics = BinaryLabelDatasetMetric(binary_data,
                                 unprivileged_groups=[{'gender': 0}],
                                 privileged_groups=[{'gender': 1}])

# Initial Bias Metrics
initial_disparate_impact = metrics.disparate_impact()
initial_statistical_parity_difference = metrics.statistical_parity_difference()

# Step 5: Train model on original data to establish baseline
X_orig = data[features].values
y_orig = data[label].values

X_train_orig, X_test_orig, y_train_orig, y_test_orig = train_test_split(
    X_orig, y_orig, test_size=0.2, random_state=42
)

model_original = RandomForestClassifier(random_state=42)
model_original.fit(X_train_orig, y_train_orig)

# Evaluate original model
y_pred_orig = model_original.predict(X_test_orig)
accuracy_orig = accuracy_score(y_test_orig, y_pred_orig)

# Create a new DataFrame for original model test data
test_indices_orig = np.arange(len(data))[-len(X_test_orig):]
test_data_orig = pd.DataFrame({
    'gender': data.iloc[test_indices_orig]['gender'].values,
    'actual': y_test_orig,
    'predicted': y_pred_orig
})

# Calculate approval rates by gender in original model
orig_approval_by_gender = test_data_orig.groupby('gender')['predicted'].mean()
print("\nOriginal Model Approval Rates by Gender:")
print(f"Female (0): {orig_approval_by_gender[0]:.4f}")
print(f"Male (1): {orig_approval_by_gender[1]:.4f}")
print(f"Difference: {abs(orig_approval_by_gender[1] - orig_approval_by_gender[0]):.4f}")

# Step 6: Apply reweighing to mitigate bias
rw = Reweighing(unprivileged_groups=[{'gender': 0}],
                privileged_groups=[{'gender': 1}])
transformed_data = rw.fit_transform(binary_data)

# Step 7: Measure bias after transformation
metrics_transformed = BinaryLabelDatasetMetric(transformed_data,
                                             unprivileged_groups=[{'gender': 0}],
                                             privileged_groups=[{'gender': 1}])

# Bias Metrics After Reweighing
final_disparate_impact = metrics_transformed.disparate_impact()
final_statistical_parity_difference = metrics_transformed.statistical_parity_difference()

# Step 8: Prepare data for model training with reweighting
X = transformed_data.features
y = transformed_data.labels.ravel()
sample_weights = transformed_data.instance_weights.ravel()

X_train, X_test, y_train, y_test, w_train, w_test = train_test_split(
    X, y, sample_weights, test_size=0.2, random_state=42
)

# Step 9: Train Random Forest classifier with instance weights
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train, sample_weight=w_train)

# Step 10: Evaluate model accuracy and fairness after reweighting
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

# Save indices for test set to match with original data
test_indices = np.arange(len(X))[len(X_train):]

# Create a DataFrame with predictions on test data to analyze fairness
test_data = pd.DataFrame({
    'gender': transformed_data.protected_attributes[test_indices].ravel(),
    'actual': y_test,
    'predicted': y_pred
})

# Calculate approval rates by gender for reweighted model
approval_by_gender_rw = test_data.groupby('gender')['predicted'].mean()
print("\nReweighted Model Approval Rates by Gender:")
print(f"Female (0): {approval_by_gender_rw[0]:.4f}")
print(f"Male (1): {approval_by_gender_rw[1]:.4f}")
print(f"Difference: {abs(approval_by_gender_rw[1] - approval_by_gender_rw[0]):.4f}")

# Step 12: Summary
print("\nSummary:")
print("+" + "-"*50 + "+" + "-"*12 + "+")
print("|{:^50}|{:^12}|".format("Metric", "Value"))
print("+" + "-"*50 + "+" + "-"*12 + "+")
print("|{:<50}|{:>11.4f}|".format("Original model accuracy", accuracy_orig))
print("|{:<50}|{:>11.4f}|".format("Reweighted model accuracy", accuracy))
print("|{:<50}|{:>11.4f}|".format("Original disparate impact", initial_disparate_impact))
print("|{:<50}|{:>11.4f}|".format("Final disparate impact", final_disparate_impact))
print("|{:<50}|{:>11.4f}|".format("Original gender approval difference", abs(orig_approval_by_gender[1] - orig_approval_by_gender[0])))
print("|{:<50}|{:>11.4f}|".format("Final statistical Parity Difference", initial_statistical_parity_difference))
print("|{:<50}|{:>11.4f}|".format("Original statistical Parity Difference", final_statistical_parity_difference))
print("|{:<50}|{:>11.4f}|".format("Reweighted gender approval difference", abs(approval_by_gender_rw[1] - approval_by_gender_rw[0])))
print("+" + "-"*50 + "+" + "-"*12 + "+")

The purpose of this example is to show how we can quantitatively measure and mitigate bias while still building an effective predictive model.

First I’ll show the output and then we’ll talk about it.

Approval Rates by Gender:
Female (0): 0.20
Male (1): 0.60
Difference: 0.40

Original Model Approval Rates by Gender:
Female (0): 0.2500
Male (1): 0.3600
Difference: 0.1100

Reweighted Model Approval Rates by Gender:
Female (0): 0.3700
Male (1): 0.3900
Difference: 0.0200

Summary:
+--------------------------------------------------+------------+
|                      Metric                      |   Value    |
+--------------------------------------------------+------------+
|Model Accuracy (original)                         |     0.5250|
|Model Accuracy (re-weighted)                      |     0.5500|
|Disparate Impact (original)                       |     0.3333|
|Disparate Impact (re-weighted)                    |     1.0000|
|Statistical Parity Difference (original)          |    -0.4000|
|Statistical Parity Difference (re-weighted)       |     0.0000|
|Gender Approval Difference (original)             |     0.1100|
|Gender Approval Difference (re-weighted)          |     0.0200|
+--------------------------------------------------+------------+

We can see the initial approval rates by gender are heavily biased for males, resulting in:

  • 36% approval rate for males
  • 25% approval rate for females (significantly lower)
Side‑by‑Side Comparison of Original vs Re‑weighted Random‑Forest Loan Approval Predictions by Gender
This grouped bar plot contrasts model outputs before and after the AIF360 Reweighing algorithm. Purple bars represent gender 0 (female) and orange bars gender 1 (male). Female approval rates move from 0.25 to 0.37 and male rates from 0.36 to 0.39, reducing the gap from 11 to 2 percentage points.

After bias analysis and re-weighting the training data accordingly, we shift this to:

  • 39% approval rates for males
  • 37% approval rates for females (comparable)

In terms of the model accuracy, we can see that both models (original and re-weighted) are comparable (just over 50%). Since we generated the features randomly, any patterns the model was able to find within each gender segment was simply the training algorithm overfitting on noise.

Lastly, we see the impact of re-weighting on the bias metrics:

  • Disparate impact score improved from 0.33 (substantial bias against the unprivileged group) to 1 (no bias)
  • Statistical parity improved from -0.4 (again indicating substantial bias) to 0 (no bias)
Fairness Metrics Dashboard - Disparate Impact and Statistical Parity Difference Pre and Post‑Mitigation.png
Disparate Impact leaps from 0.33 (substantial bias) to the ideal 1.00 and Statistical Parity Difference rises from -0.40 to 0.00.

Model Transparency and Explainability

Why It’s Important

AI systems often act as black boxes, making decisions that are difficult to understand.

Transparency and explainability allow users and stakeholders to trust these decisions, especially in high-stakes applications like healthcare or criminal justice.

Examples of Models that Benefit from Explainability

Financial Systems

  • Credit scoring models explaining key factors that are influencing approval decisions
  • Fraud detection algorithms providing evidence for flagged transactions
  • Automated trading systems documenting decision-making processes

Healthcare & Diagnostics

  • Medical diagnosis systems highlighting symptoms that led to specific conclusions
  • Risk assessment models detailing factors behind risk scores

Computer Vision & Content

  • Image recognition systems highlighting areas of the image that influenced classification
  • Content moderation systems explaining policy violations in removed content

User Interaction & Recommendations

  • Recommendation engines clarifying why certain items were suggested
  • Chatbots explaining their reasoning behind responses

Human Resources

  • HR screening tools showing criteria used for candidate rankings

Key Concepts

  • Model Explainability: Tools like SHAP (SHapley Additive exPlanations) or LIME (Local Interpretable Model-agnostic Explanations) help illuminate why models make certain predictions.
  • Transparency: Providing clear documentation about how a model was developed, trained, and tested.

Example: Medical Diagnosis Explainability with SHAP

Consider an AI-powered diagnostic tool that predicts the likelihood of a disease. By making the model explainable, physicians can better understand and validate its recommendations, ensuring ethical decision-making.

Using python, we can calculate SHAP values to explain predictions from a medical diagnosis model.

In a real-world setting, this would allow us to see exactly how factors like blood pressure, glucose levels, etc. influenced the model’s prediction, helping doctors validate the AI’s recommendations.

# Step 1: Import required libraries
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
import shap

np.random.seed(137)

# Step 2: Create synthetic patient dataset with medical features
data = pd.DataFrame({
    'age': np.random.normal(50, 15, 1000),              # Mean age 50, std dev 15
    'blood_pressure': np.random.normal(120, 20, 1000),  # Mean BP 120, std dev 20
    'glucose': np.random.normal(100, 25, 1000),         # Mean glucose 100, std dev 25
    'heart_rate': np.random.normal(75, 12, 1000),       # Mean HR 75, std dev 12
    'cholesterol': np.random.normal(200, 40, 1000)      # Mean cholesterol 200, std dev 40
})

# Step 3: Generate disease labels based on glucose and blood pressure thresholds
labels = (data['glucose'] > 126) & (data['blood_pressure'] > 140)  # Medical criteria
data['disease'] = labels.astype(int)  # Convert boolean to 0/1

# Step 4: Prepare features and target for model training
features = ['age', 'blood_pressure', 'glucose', 'heart_rate', 'cholesterol']
X = data[features]
y = data['disease']

# Step 5: Train a Random Forest classifier
model = RandomForestClassifier(random_state=42)
model.fit(X, y)

# Step 6: Create SHAP explainer for the trained model
explainer = shap.TreeExplainer(model)

# Step 7: Get SHAP values for first patient's prediction
patient = X.iloc[[0]]  # Select first patient
patient_outcome = y.iloc[0]
shap_values = explainer.shap_values(patient)

# Step 8: Print feature importance values for the prediction
for idx, feature in enumerate(features):
    print(f"{feature}: {shap_values[0][idx][patient_outcome]:.3f}")

This results in the following output:

age: -0.002
blood_pressure: -0.042
glucose: 0.054
heart_rate: 0.005
cholesterol: 0.001

The SHAP values show how each feature contributed to moving the model output from the base value (average model prediction) to the value for this specific prediction.

Interpretation: Positive values push prediction higher, negative values push it lower.

For our data above, we output the SHAP values for one particular patient:

>>> print(patient_outcome)
0

>>> print(patient)
    age         blood_pressure  glucose    heart_rate  cholesterol
0   66.361632   169.690375      74.759275  77.575502   229.881296

This patient was negative, so we look at the SHAP values associated with the negative prediction.

Interpreting the results, we can determine that

  • Glucose had the strongest positive influence (0.054) on the prediction, though still relatively small
  • Blood pressure had the strongest negative influence (-0.042) on the prediction (it “wanted” to push the prediction to the positive class)
  • The other features had negligible impact on the prediction
Patient‑Level SHAP Contribution Plot Shows Feature Push‑and‑Pull for First Negative Diagnosis
This diverging bar chart isolates SHAP values for Patient 0, illustrating how each feature nudged the prediction toward the negative class. Glucose exerts the strongest positive pressure (+0.054), while blood pressure applies the largest negative force (-0.042). The visual makes transparent the exact clinical factors behind the model's "no‑disease" verdict.

Another way to use SHAP values for model explainability is by looking at the averages over many samples, from which we can infer overall feature importances. These are visualized in the figure below.

Mean Absolute SHAP Value Ranking Highlights Dominant Medical Features in Synthetic Disease‑Risk Model
Feature importances for the example above. Glucose and blood pressure dominate over age, cholesterol, and heart rate in this model.

Privacy-Preserving AI Methods

Why It’s Important

AI systems often handle sensitive data, raising concerns about privacy.

Without proper safeguards, these systems can expose individuals to risks such as identity theft or misuse of personal information.

Common Privacy Risks

Data Exposure & Breaches

  • Data breaches exposing personal health records in medical AI systems
  • Language models memorizing and revealing sensitive training data
  • Large language models inadvertently disclosing personal information
  • Location data leakage in personalized recommendation systems

Model Exploitation

  • Model inversion attacks reconstructing training data from AI systems
  • Membership inference attacks determining if specific data was used in training
  • Side-channel attacks extracting data from model parameters

Identity & Biometric Risks

  • Re-identification of anonymized individuals in public datasets
  • Voice cloning systems being misused for impersonation
  • Facial recognition systems storing biometric data without consent

Intellectual Property Issues

  • Generative AI accidentally recreating copyrighted or private content

Key Concepts

  • Differential Privacy: Adding noise to data to protect individual records while preserving statistical accuracy.
  • Federated Learning: Training models across distributed devices without sharing raw data, reducing privacy risks.
  • Encryption: Securely storing and transmitting sensitive data to prevent unauthorized access.

Responsible Data Collection and Usage

Why It’s Important

The quality and ethical implications of AI systems are heavily influenced by the data they consume. Irresponsible data practices can lead to biased, unethical, or even illegal outcomes.

Common Ethical Data Issues

Data Collection & Consent

  • Collecting more personal data than necessary for the application
  • Using data for purposes beyond what users initially consented to
  • Scraping data from unauthorized sources
  • Using biased or unrepresentative sampling methods
  • Failing to consider cultural sensitivities in data collection

Data Security & Privacy

  • Poor data security practices leading to unauthorized access
  • Mixing sensitive personal information with general datasets
  • Failing to properly anonymize data before analysis or sharing

Data Management & Documentation

  • Inadequate documentation of data collection and processing methods
  • Not verifying the source or quality of third-party datasets
  • Using outdated or inaccurate data that could harm individuals

User Rights & Control

  • Not providing users with ways to access or delete their data
  • Inadequate handling of user opt-out requests

Key Concepts

  • Diverse Datasets: Ensuring data represents all groups fairly to avoid skewed model behavior.
  • Informed Consent: Obtaining user permission for data collection and usage.
  • Data Minimization: Collecting only the necessary data for the task at hand.

Applying Ethical AI

Ethical frameworks like fairness, transparency, privacy, and responsible data practices can be easy to overlook or set aside, especially when we’re working on a tight deadline and balancing technical considerations.

My advice is to plan for ethics upfront and set aside dedicated time for this aspect of the project.

Conclusion

Maybe I’m feeling sentimental as we embark on the final section of this course, but I’m going to let you in on a dream of mine. It’s related to ethics, which is why it came to mind as I wrote this lesson.

My dream is to start a business that can make an impact on ethics in the animal food industry. I’ve already tried this once[1], and it didn’t go well. But I’m sure I’ll get closer to my dream the next time I take a run at it.

Key Takeaways

⚖️ Ethical AI requires careful consideration of fairness, transparency, privacy, and responsible data practices.

💰 Common biases can appear in various domains, including finance, healthcare, and criminal justice.

🛠️ Tools like fairness metrics, SHAP values, and differential privacy help build more ethical AI systems.

📊 Responsible data collection and usage is fundamental to ethical AI development.

🧠 Ethics should be planned for upfront, not treated as an afterthought.

🔍 AI systems should be regularly audited for bias and privacy concerns.

Next: Industry Trends and Applications

The next section is on industry trends. Exciting stuff coming up!

Footnotes


  1. I tried to sell digital labels to farmer’s market vendors. Long-story short: it was fun building the product but nobody wanted to buy it. I made a video on YouTube about my experience: My DIGITAL LABEL startup FAILED ↩︎

Comments (0)

No comments yet.