跳轉至內容

R 程式設計/最佳化

來自 Wikibooks,開放世界中的開放書籍

數值方法

[編輯 | 編輯原始碼]

一維問題

[編輯 | 編輯原始碼]

一維問題

> func <- function(x){
+ 	return ( (x-2)^2 )
+ 	}
> (func(-2))
[1] 16
>
> # plot your function using the 'curve function'
> curve(func,-4,8) 
>
> # Here is another way to plot the function
> # using a grid
> grid <- seq(-10,10,by=.1) 
> func(grid)
> plot(grid,func(grid))
> 
> # you can find the minimum using the optimize function
> optimize(f=func,interval=c(-10,10))
$minimum
[1] 2

$objective
[1] 0

牛頓-拉夫森方法

[編輯 | 編輯原始碼]
  • nlm()提供了一個牛頓演算法。
  • maxLik 包用於似然函式的最大化。此包包含牛頓-拉夫森方法。
  • newtonraphson()spuRs包中。


> func <- function(x){
+ 	out <- (x[1]-2)^2 + (x[2]-1)^2
+ 	return <- out
+ 	}> 
> optim(par=c(0,0), fn=func, gr = NULL,
+       method = c("BFGS"),
+       lower = -Inf, upper = Inf,
+       control = list(), hessian = T)
> optim(par=c(0,0), fn=func, gr = NULL,
+       method = c("L-BFGS-B"),
+       lower = -Inf, upper = Inf,
+       control = list(), hessian = T)

共軛梯度法

[編輯 | 編輯原始碼]
  • optim() 使用 method="cg"

置信域方法

[編輯 | 編輯原始碼]


Nelder-Mead單純形方法

[編輯 | 編輯原始碼]
> func <- function(x){
+ 	out <- (x[1]-2)^2 + (x[2]-1)^2
+ 	return <- out
+ 	}
> 
> optim(par=c(0,0), fn=func, gr = NULL,
+       method = c("Nelder-Mead"),
+       lower = -Inf, upper = Inf,
+       control = list(), hessian = T)


  • boot包包含另一種單純形方法

模擬方法

[編輯 | 編輯原始碼]

模擬退火

[編輯 | 編輯原始碼]
  • 模擬退火是一種用於最大化非光滑函式的演算法。它在以下方面得到了預先實現optim().
> func <- function(x){
+ 	out <- (x[1]-2)^2 + (x[2]-1)^2
+ 	return <- out
+ 	}> 
> optim(par=c(0,0), fn=func, gr = NULL,
+       method = c("SANN"),
+       lower = -Inf, upper = Inf,
+       control = list(), hessian = T)

EM演算法

[編輯 | 編輯原始碼]

遺傳演算法

[編輯 | 編輯原始碼]
  • rgenoud包用於遺傳演算法[3]
  • gaoptim包用於遺傳演算法[4]
  • ga是一個通用的最佳化包,使用遺傳演算法。它提供了一套靈活的工具,用於在連續和離散情況下實現遺傳演算法搜尋,無論是否有約束。[5]

參考文獻

[編輯 | 編輯原始碼]


上一頁:數學 索引 下一頁:機率分佈
華夏公益教科書