is this need to be gaussian distributed to check outlier in this way? Fungsi Z-score def…
- User
is this need to be gaussian distributed to check outlier in this way?
Fungsi Z-score
def zscore(s, window, thresh=1, return_all=False): # Menghitung nilai rata-rata bergerak (rolling mean) roll = s.rolling(window=window, min_periods=1, center=True) avg = roll.mean() # Menghitung nilai standar deviasi bergerak (rolling std) std = roll.std(ddof=0) # Menghitung nilai Z-score untuk setiap elemen z = s.sub(avg).div(std) # Menentukan elemen mana yang berada di dalam batas threshold (thresh) m = z.between(-thresh, thresh)
code# Jika return_all adalah True, kembalikan semua variabel if return_all: return z, avg, std, m # Jika tidak, hanya kembalikan data yang berada dalam batas dengan nilai rata-rata return s.where(m, avg)Assumption: 'REFGPS' is a column in DataFrame df
for i in range(0, 1000, 100): # Menerapkan Deteksi Z-score df_window = df['REFGPS'].tail(1000).iloc[i:i+100] z, avg, std, m = zscore(df_window, window=10, return_all=True)
code# Membuat plot deret waktu dengan outlier plt.figure(figsize=(10, 6)) # Menampilkan data asli dengan transparansi df_window.plot(label='data', alpha=0.6) # Menampilkan rata-rata bergerak (rolling mean) avg.plot(label='mean', color='orange') # Menampilkan outlier dengan penanda khusus df_window[~m].plot(label='outliers', marker='o', ls='', color='green') # Menampilkan penggantian nilai untuk outlier avg[~m].plot(label='replacement', marker='o', ls='', color='red') # Menambahkan legenda untuk membedakan elemen-elemen yang ditampilkan plt.legend() # Menambahkan judul pada grafik plt.title(f"REFGPS Data with Outliers and Rolling Mean {i} to {i+100}") plt.show() - Assistant
The z-score method for outlier detection assumes the data is normally (Gaussian) distributed. This is because the z-score is a measure of how many standard deviations an element is from the mean, and this is most meaningful under the assumption of normality.
However, in practice, you might use the z-score to detect outliers in data that is not perfectly Gaussian distributed, though it may not be as effective or may lead to incorrect identification of outliers. If your data is not normally distributed, you might consider the following alternatives:
-
Transform the Data: Use transformations (such as logarithmic or Box-Cox) to make your data more normally distributed before applying z-score outlier detection.
-
Use Robust Methods: Techniques like the Modified Z-score or using Median Absolute Deviation (MAD) instead of standard deviation can help in cases where data is not Gaussian.
-
: Use interquartile range (IQR) to determine outliers by looking for values that fall outside a certain range of quantiles.
-