> ## Content Index
> Fetch the complete content index at: https://bongholee.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# A/B테스트 진행시 체크해야 하는 이슈 중 하나인 SRM
- URL: https://bongholee.com/a-bteseuteu-jinhaengsi-cekeuhaeya-haneun-isyu-jung-hanain-srm/
- Published: 2024-07-08T06:01:56.000Z
- Updated: 2024-07-08T06:01:56.000Z
- Author: Bongho Lee
- Tags: Data, #Import 2026-11-22 06:32

### Definition

- \*\*Sample Ratio Mismatch(SRM)\*\*는 실험 설계나 데이터 수집 과정에서 샘플의 비율이 의도한 비율과 일치하지 않는 상황을 의미합니다
- 예를 들어, A/B 테스트에서 두 그룹(A와 B)로 사용자 트래픽을 균등하게 나누려고 했으나, 실제 데이터에서는 비율이 맞지 않는 경우가 SRM입니다.
- SRM은 실험의 무작위성(randomness)을 보장하고, 통계적 검증의 신뢰성을 높이기 위해 중요한 개념입니다.
- SRM이 발생하면 실험 결과의 유효성이 의심될 수 있으며, 결과 해석에 오류가 발생할 수 있습니다.

### Pros

1. **문제 조기 발견**: SRM을 감지하면 실험 설계나 데이터 수집 과정에서의 문제를 조기에 발견할 수 있습니다.
2. **데이터 무결성 보장**: 샘플 비율이 올바르게 유지되면 데이터의 무결성을 보장할 수 있습니다.
3. **신뢰성 향상**: 무작위성을 보장하여 실험 결과의 신뢰성을 높일 수 있습니다.

### Cons

1. **추가 작업 필요**: SRM을 감지하고 수정하기 위해 추가 작업이 필요할 수 있습니다.
2. **복잡성 증가**: 실험 설계 및 데이터 수집 과정에서 SRM을 감지하고 수정하는 작업이 추가되면 복잡성이 증가할 수 있습니다.
3. **리소스 소모**: SRM을 감지하고 수정하는 과정에서 리소스가 소모될 수 있습니다.

### Action Item

1. **모니터링 시스템 도입**: 실험 중 실시간으로 샘플 비율을 모니터링하여 SRM을 조기에 감지합니다.
2. **사전 검증**: 실험 시작 전에 샘플링 프로세스를 검증하여 SRM 발생 가능성을 줄입니다.
3. **데이터 재수집**: SRM이 감지된 경우, 데이터를 재수집하여 샘플 비율을 맞춥니다.

### Sample

```python
import numpy as np  
import matplotlib.pyplot as plt  
  
def detect_srm(group_a, group_b, tolerance=0.05):  
    n_a = len(group_a)  
    n_b = len(group_b)  
    total = n_a + n_b  
  
    ratio_a = n_a / total  
    ratio_b = n_b / total  
  
    expected_ratio = 0.5  
    srm_detected = abs(ratio_a - expected_ratio) > tolerance or abs(ratio_b - expected_ratio) > tolerance  
      
    return srm_detected, ratio_a, ratio_b  
  
def resample_data(group_a, group_b):  
    min_len = min(len(group_a), len(group_b))  
    resampled_a = np.random.choice(group_a, min_len, replace=False)  
    resampled_b = np.random.choice(group_b, min_len, replace=False)  
    return resampled_a, resampled_b  
  
# 샘플 데이터 생성  
np.random.seed(42)  
group_a = np.random.binomial(1, 0.5, 1000)  
group_b = np.random.binomial(1, 0.5, 1200)  # 의도한 비율이 맞지 않음  
  
# SRM 감지  
srm_detected, ratio_a, ratio_b = detect_srm(group_a, group_b)  
  
print(f"Group A ratio: {ratio_a:.2f}")  
print(f"Group B ratio: {ratio_b:.2f}")  
  
if srm_detected:  
    print("Sample Ratio Mismatch detected. Resampling data...")  
    group_a, group_b = resample_data(group_a, group_b)  
    srm_detected, ratio_a, ratio_b = detect_srm(group_a, group_b)  
    print(f"After resampling - Group A ratio: {ratio_a:.2f}, Group B ratio: {ratio_b:.2f}")  
else:  
    print("No Sample Ratio Mismatch detected.")  
  
# 시각화  
labels = ['Group A', 'Group B']  
ratios = [ratio_a, ratio_b]  
  
plt.bar(labels, ratios, color=['blue', 'orange'])  
plt.axhline(y=0.5, color='red', linestyle='--')  
plt.title('Sample Ratios')  
plt.ylabel('Ratio')  
plt.ylim(0, 1)  
plt.show()

```

![](https://i.imgur.com/rFAJgdT.png)