Reproducible Assignment Template: Titanic Survival Analysis
This template provides a fully reproducible assignment for an introductory data science course. It uses Python (Jupyter Notebook), the Titanic dataset (from Seaborn), and tools like pytest for automated grading. Everything is self-contained:
Environment : Reproducible via environment.yml (Conda) or requirements.txt (pip).
Data : Auto-loaded from Seaborn (no external downloads needed).
Grading : Mix of automated tests (70% weight) + rubric (30% weight).
Feedback : Automated + manual template.
Reproducibility : Fixed random seeds, pinned versions.
Clone this as a GitHub repo or copy into a Jupyter environment. Total student time: 2-4 hours.
1. Setup Instructions (for Students & Instructor)
Environment File (environment.yml)
yaml Copy code
name: titanic-assignment
channels:
- conda-forge
dependencies:
- python=3.11
- jupyter
- pandas=2.1.4
- numpy=1.24.3
- seaborn=0.13.0
- matplotlib=3.8.2
- scikit-learn=1.3.2
- pytest=7.4.3
- pytest-notebook=0.2.0 # For notebook testing
Install: conda env create -f environment.yml && conda activate titanic-assignment
requirements.txt (Alternative for pip)
code Copy code
pandas==2.1.4
numpy==1.24.3
seaborn==0.13.0
matplotlib==3.8.2
scikit-learn==1.3.2
pytest==7.4.3
pytest-notebook==0.2.0
2. Assignment Description (assignment.ipynb)
Student Instructions : Complete the notebook student_submission.ipynb. Submit the filled notebook + student_report.md.
Task : Load the Titanic dataset. Perform EDA, build a logistic regression model to predict survived, and evaluate it. Achieve >75% accuracy on test set.
Requirements :
Use random_state=42 everywhere.
Include 3+ visualizations.
Write 1-2 sentences explaining key insights per section.
No external data/models.
Provided Starter Code (in student_submission.ipynb):
python Copy code
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import warnings
warnings.filterwarnings('ignore')
# Load data (reproducible)
sns.set_theme(style="whitegrid")
titanic = sns.load_dataset('titanic')
# Your code starts here...
print(titanic.head())
print(titanic.info())
Expected Student Outputs (examples, not exact):
EDA: Bar plot of survival by class.
Model: Accuracy ~0.78.
Report: Markdown summary.
3. Student Submission Template
student_submission.ipynb: Filled notebook.
student_report.md: Summary (e.g., insights, challenges).
4. Grading
Total: 100 points . Run pytest for automated score.
Automated Tests (70 points) - test_assignment.py
Save as test_assignment.py. Run: pytest test_assignment.py --notebook=student_submission.ipynb
python Copy code
import pytest
import nbformat
from pytest_notebook import run_notebook
import json
import re
@pytest.fixture
def nb():
with open('student_submission.ipynb') as f:
return nbformat.read(f, as_version=4)
def extract_output(nb, cell_idx, output_type='text'):
"""Helper to extract cell output."""
cell = nb.cells[cell_idx]
if cell.cell_type == 'code' and cell.outputs:
for out in cell.outputs:
if output_type in str(out):
return out
return None
def test_data_loaded(nb):
"""Test 1: Data loaded correctly (10 pts)"""
output = extract_output(nb, 5, 'text') # Assume cell 5 has info()
assert '891 entries' in str(output), "Dataset size mismatch"
assert 'Survived' in str(output), "Key column missing"
def test_eda_visualization(nb):
"""Test 2: At least 3 plots (15 pts)"""
plt_counts = sum(1 for cell in nb.cells if re.search(r'plt\.show\(\)|sns\.', str(cell.source), re.I))
assert plt_counts >= 3, f"Only {plt_counts} plots found"
def test_model_trained(nb):
"""Test 3: Model fit & accuracy >75% (20 pts)"""
output = extract_output(nb, -2, 'text') # Last code cell
acc_match = re.search(r'accuracy_score.*?([\d.]+)', str(output))
assert acc_match and float(acc_match.group(1)) > 0.75, "Accuracy too low"
def test_seed_used(nb):
"""Test 4: random_state=42 used (10 pts)"""
seed_count = sum(1 for cell in nb.cells if 'random_state=42' in str(cell.source))
assert seed_count >= 2, "Use random_state=42 for splits/model"
def test_report_exists():
"""Test 5: Report file (15 pts)"""
with open('student_report.md') as f:
content = f.read()
assert len(content) > 200, "Report too short"
assert 'insight' in content.lower(), "Add explanations"
Manual Rubric (30 points) - grading_rubric.md
Criterion Description Points Code Quality Clean, commented, efficient /10 Visualizations Insightful + labeled /10 Explanations Clear insights in notebook/report /10
Grading Script (grade.sh):
bash Copy code
#!/bin/bash
pytest test_assignment.py --notebook=student_submission.ipynb -v --tb=short
echo "Manual rubric: See grading_rubric.md"
5. Feedback Template
Automated Feedback : From pytest (e.g., "Test 3 failed: Accuracy too low").
Manual Feedback (feedback.md - Instructor fills):
code Copy code
Student: [Name]
Automated Score: 62/70
Manual Score: 25/30
Total: 87/100
Grade: A-
Strengths:
- Excellent EDA visualizations.
Issues:
- Model accuracy low: Try feature engineering (e.g., 'family_size = sibsp + parch').
- Missing labels on plots.
Suggestions:
- Use GridSearchCV for hyperparams.
- Next assignment: Try RandomForest.
Code Snippets to Improve:
```python
X['family_size'] = X['sibsp'] + X['parch']
Keep up the great work!
code Copy code
## Usage for Instructor
1. Share `assignment.ipynb`, `environment.yml`.
2. Students submit `student_submission.ipynb` + `student_report.md`.
3. Run `grade.sh` → Auto-score.
4. Fill rubric + `feedback.md`.
## Full Reproducibility Checklist
- [x] No internet required post-setup.
- [x] Fixed seeds/versions.
- [x] Tests pass on clean env: `pytest` score 70/70 on starter + solution.
- [x] Solution notebook: `solution.ipynb` (hidden, for instructor).
**Extend This Template**: Swap dataset/model for other assignments (e.g., Iris classification). Questions? Ask Sherlock! 🕵️