
引言
受Netfix帖子的啟發(fā),我決定寫一篇如何利用R語言實現(xiàn)該異常值檢驗的博文。
有好幾個非常棒的軟件包可以實現(xiàn)這個功能,本文所采用的是AnomalyDetection包。
你可以從這里下載完整的R語言代碼。
正常值 vs.異常值
異常值的定義是:和大多數(shù)樣本表現(xiàn)不一致的個體。
數(shù)據(jù)噪聲:就好比當你收聽一個信號不好的無線廣播時,你會聽到許多背景噪聲。

圖中紅圈中的數(shù)據(jù)是噪聲數(shù)據(jù)嗎?抑或是某種未發(fā)現(xiàn)趨勢的峰值呢?
一個好的算法可以檢測出異常值并將其剔除掉,AnomalyDetection包種的AnomalyDetectionTs函數(shù)可以很好地實現(xiàn)這個功能。
異常值檢測實例
本文案例采用的是維基百科的數(shù)據(jù),我們可以利用R通過API接口下載某個特定詞項每日瀏覽量的數(shù)據(jù)。
本文的研究數(shù)據(jù)是:英文詞語fifa從2013-02-22至今每日瀏覽量的數(shù)據(jù)。

應用上文提到的算法,我們可以繪制出原始的時間序列圖并標注出異常值的位置。
算法解析
算法中的參數(shù)max_anoms=0.01表示在最終結果中標注出0.01%的異常值;而參數(shù)direction=”pos”則表示檢測高于平均水平的異常值。
如下表所示,該算法不僅可以檢測出異常值,還會返回對應的平均水平值。

發(fā)現(xiàn)異常情況
新聞核實
詞語fifa瀏覽量的異常值與國際足聯(lián)的新聞消息息息相關,第一組異常值出現(xiàn)在2014年世界杯期間(2014年6 – 7月),而第二組異常值出現(xiàn)在國際足聯(lián)丑聞事件期間(2015年5月)。
洛杉磯時報中展示了國際足聯(lián)丑聞事件進展的時間表,正如我們算法所檢測出的異常值,該丑聞事件有兩個重要的時間點:5月27日和28日。
附錄(R Code)
install.packages(“devtools”)
devtools::install_github(“petermeissner/wikipediatrend”)
devtools::install_github(“twitter/AnomalyDetection”)
install.packages(“Rcpp”)
library(wikipediatrend) ## Library containing API wikipedia access
library(AnomalyDetection)
library(ggplot2)
Download wiki webpage “fifa”
fifa_data = wp_trend(“fifa”, from=”2013-03-18”, lang = “en”)
Plotting data
ggplot(fifa_data, aes(x=date, y=count, color=count)) + geom_line()
Convert date variable
fifa_data<img alt=”date=as.POSIXct(fift_data”data-cke-saved-src=”https://chart.googleapis.com/chart?cht=tx&chl=date%20%3D%20as.POSIXct(fifa_data”>date)
Keep only desiered variables (date & page views)
fifa_data=fifa_data[,c(1,2)]
Apply anomaly detection
data_anomaly = AnomalyDetectionTs(fifa_data, max_anoms=0.01, direction=”pos”, plot=TRUE, e_value = T)
jpeg(“03_fifa_wikipedia_term_page_views_anomaly_detection.jpg”, width= 8.25, height= 5.25, units=”in”, res=500, pointsize = 4)
Plot original data + anomalies points
data_anomaly$plot
dev.off()
Calculate deviation percentage from the expected value
data_anomalyperc_diff=round(100*(data_anomaly
expected_value-data_anomaly
anoms)/data_anomaly
expected_value)
Plot anomalies table
anomaly_table=data_anomaly$anoms
?
原文:Anomaly Detection in R
End.
轉載請注明來自36大數(shù)據(jù)(36dsj.com):36大數(shù)據(jù) » 【R】異常值檢測
愛盈利(aiyingli.com) 移動互聯(lián)網(wǎng)最具影響力的盈利指導網(wǎng)站。定位于服務移動互聯(lián)網(wǎng)創(chuàng)業(yè)者,移動盈利指導。我們的目標是讓盈利目標清晰可見!降低門檻,讓缺乏經驗、資金有限的個人和團隊獲得經驗和機會,提高熱情,激發(fā)產品。