Explanation Regularization (M05 RRR) API¶
ExplanationRegularization
¶
ExplanationRegularization(
lambda_rrr: float = 1.0,
lr: float = 0.0001,
n_epochs: int = 10,
batch_size: int = 8,
head: str | int = "logits",
device: str | device | None = None,
random_state: int | None = None,
)
Right for Right Reasons (RRR) - Ross et al. 2017.
Fine-tunes a model by penalizing input gradients on shortcut regions. Loss = L_task + lambda * sum(mask * (d log p(y|x)/dx)^2).
Parameters¶
lambda_rrr : float Weight for the gradient penalty on shortcut regions. lr : float Learning rate for Adam optimizer. n_epochs : int Number of training epochs. batch_size : int Batch size for training. head : str or int How to extract logits from model output. "logits" or 0 for first output. device : str or torch.device, optional Device to train on. random_state : int, optional Seed for reproducibility.
Source code in shortcut_detect/mitigation/explanation_regularization.py
Functions¶
fit
¶
fit(
model: Module,
images: Tensor,
labels: ndarray,
shortcut_masks: ndarray,
) -> ExplanationRegularization
Fine-tune model with RRR penalty. Model is updated in-place.
Parameters¶
model : torch.nn.Module Differentiable model (e.g., CNN). Will be put in train mode. images : torch.Tensor Input images, shape (N, C, H, W). Will be moved to device. labels : np.ndarray Task labels, shape (N,), integer class indices. shortcut_masks : np.ndarray Masks where 1 = shortcut region to penalize. Shape (N, H, W) or (H, W). Will be resized to match input spatial size if needed.
Returns¶
self : ExplanationRegularization
Source code in shortcut_detect/mitigation/explanation_regularization.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |