[英]how to graph the log likelihood function
我想繪制-pi和pi之間的對數似然函數。
對數似然函數
llh <- function (teta,x) {
sum(log((1-cos(x-teta))/(2*pi)))
}
x=c(3.91,4.85,2.28,4.06,3.70,4.04,5.46,3.53,2.28,1.96,2.53,3.88,2.22,3.47,4.82,2.46,2.99,2.54,0.52,2.50)
teta=seq(-4,4, by=0.01)
y = llh(teta,x)
plot(teta, llh(teta,x), pch=16)
它無法繪制函數。 這是錯誤消息:
Warning message:
In x - teta :
longer object length is not a multiple of shorter object length
>
> plot(teta, llh(teta,x), pch=16)
Error in xy.coords(x, y, xlabel, ylabel, log) :
'x' and 'y' lengths differ
In addition: Warning message:
In x - teta :
longer object length is not a multiple of shorter object length
如上所述,您的函數將適用於teta
一個值和幾個x
值,或者幾個teta
值和一個x
值。 否則,您會收到不正確的值或警告。
示例: llh
for teta=1
且teta=2
:
> llh(1,x)
[1] -34.88704>
> llh(2,x)
[1] -60.00497
是不一樣的:
> llh(c(1,2),x)
[1] -49.50943
如果你嘗試做三個:
> llh(c(1,2,3),x)
[1] -49.52109
Warning message:
In x - teta :
longer object length is not a multiple of shorter object length
從根本上來自:
> cos(x-c(1,2,3))
[...]
Warning message:
In x - c(1, 2, 3) :
longer object length is not a multiple of shorter object length
因為R試圖從長度為20的向量中減去長度為3的向量。 它在長度為20的向量上重復長度為3的向量,直到它完成六次,然后它只剩下兩個元素。 嗯...認為R,我會這樣做,但它看起來不對,所以這是一個警告。
您可以重寫函數以處理兩個參數的向量,或者通過包裝來向量化函數。
> vllh = Vectorize(llh,"teta")
> vllh(c(1,2,3),x)
[1] -34.88704 -60.00497 -67.30765
> plot(teta, vllh(teta,x))
你需要使用sapply函數(read?sapply),因為你的代碼沒有矢量化
plot(teta, sapply(X=teta, FUN=function(teta) llh(teta, x=x)), type="l")
要么
矢量化你的功能:
llh2 <- function (teta,x) {
sapply(X=teta, FUN=function(teta) sum(log((1-cos(x-teta))/(2*pi))) )
}
plot(teta, llh2(teta,x), type="l")
使用外部的另一個解
llh <- function (teta,x) {
X <- outer(x, teta, "-")
Y <- log((1-cos(X))/(2*pi))
apply(Y, 2, sum)
}
x=c(3.91,4.85,2.28,4.06,3.70,4.04,5.46,3.53,2.28,1.96,2.53,3.88,2.22,3.47,4.82,2.46,2.99,2.54,0.52,2.50)
teta=seq(-4,4, by=0.01)
plot(teta, llh(teta,x), pch=16)
我同意間隔的人,Vectorize很有意思!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.