簡體   English   中英

如何在 R 中的 Kernel 密度 plot 中找到拐點?

[英]How to find inflection points in a Kernel density plot in R?

我試圖找到我用密度計算的 Kernel 密度 plot 曲線中拐點的 x 值() function。

我發現以下已回答的問題有助於找到轉折點:

當 window 寬度變化時,如何找到 kernel 密度曲線上的所有轉折點

所以我認為也必須有一種方法來找到拐點的 x 值。 如果有人有小費會很棒。

根據定義,拐點是 function 的二階導數為零的點。 在實踐中,這意味着拐點將是斜率從增加變為減少的點,或者 vv 使用這個定義,我采用了這種近似且非自動的方法:假設您有一個 dataframe,我將調用all ,其中包含第一列中的 x 值,以及第二列中的密度計算結果。 從這個 dataframe,我們可以計算出兩個連續點的斜率,如下所示:

slopes <- vector()
for(i in (2:nrow(all))){
  x1 <- all[i-1, 1]
  x2 <- all[i, 1]
  y1 <- all[i-1, 2]
  y2 <- all[i, 2]
  slope_i <- (y2-y1)/(x2-x1)
  slopes <- append(slopes, slope_i)
}

根據拐點的定義,我們現在可以計算從一個點到另一個點的斜率是變大還是變小:

increment <- vector()
for(j in 2:length(slopes)){
  increment_j <- slopes[j] - slopes[j-1]
  increment <- append(increment, increment_j)
}

拐點將是這個增量從正到負傳遞的那些點,或 vv

現在,讓我們將這些增量分為正數和負數:

pos <- which(increment>0)
neg <- which(increment<0

現在,只要這些posneg向量發生跳躍,就意味着我們有一個拐點。 所以,再一次:

steps_p <- vector()
for(k in 2:length(pos)){
  steps_k <- pos[k] - pos[k-1]
  steps_p <- append(steps_p, steps_k)
}
steps_n <- vector()
for(k in 2:length(neg)){
  steps_k <- neg[k] - neg[k-1]
  steps_n <- append(steps_n, steps_k)
}

現在,只需詢問 R:

which(steps_p>1)
which(steps_n>1)

這是您的拐點的索引,現在只是 go 到您原來的 dataframe 並詢問 x 值:

all[pos[which(steps_p>1)],1]
all[neg[which(steps_n>1)],1]

請記住,x 值將接近精確,但並不完全,因為在每個循環中我們都會丟失一個索引,但它仍然是一個非常接近的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM