문제 설명
중첩 최적화에서 솔루션을 반환하는 방법은 무엇입니까? (How to return solutions in a nested optimization?)
다음과 같은 문제가 있습니다. 여러 차원에서 최적화 문제를 해결해야 합니다. 그러나 문제는 어떤 의미에서 좋습니다. 문제를 외부와 내부 최적화로 분할하여 차원을 줄일 수 있습니다. 내부 최적화는 매우 효율적으로 풀 수 있습니다(선형 대수). 코드가 다소 깁니다. 이러한 이유로 저는 장난감 모델을 만들었습니다.
out.obj <‑ function(x,storage){
inner.sol <‑ inner.obj(param = x)
storage <‑ append(storage,inner.sol)
return((x‑inner.sol)^2)
}
inner.obj <‑ function(x = NULL,param){
return(log(param)^2‑param)
}
storage <‑ c()
sol <‑ optim(par = c(3),fn = out.obj,storage = storage)
이 예는 수학적 관점에서 별로 의미가 없습니다. 그러나 내부 솔루션 추출에 관한 내 문제를 보여줍니다. 위의 코드에는 x1,x2라는 2dim 문제가 있습니다. 보시다시피 저는 외부 목적 함수에 대해 optim을 호출합니다. x1에 대한 값이 주어지면 x2에 대해 "해결"할 수 있습니다.
마지막으로 저는 x1과 x2에 대한 두 가지 최적 값을 갖고 싶습니다. 이를 위해 매개변수 저장소를 사용했습니다. 그러나 저장소는 로컬 버전을 가져오고 x2에 대한 최적의 값을 검색할 수 없습니다. 나는 또한 다음을 시도했다:
storage <‑ c()
out.obj <‑ function(x){
inner.sol <‑ inner.obj(param = x)
storage <‑ append(storage,inner.sol)
return((x‑inner.sol)^2)
}
inner.obj <‑ function(x = NULL,param){
return(log(param)^2‑param)
}
sol <‑ optim(par = c(3),fn = out.obj)
In this case storage should be globally defined. Still the values for x2 are not getting populated. How can I get this value?
**EDIT**
f2 <‑ function(y=NULL){
storage <‑ c()
sol <‑ optim(par = c(3),fn = out.obj)
return(list("sol" = sol,"storage"=storage))
}
f1 <‑ function(p=NULL){
temp <‑ f2(NULL)
return(temp)
}
out.obj <‑ function(x){
inner.sol <‑ inner.obj(param = x)
storage <<‑ append(storage,inner.sol)
return((x‑inner.sol)^2)
}
inner.obj <‑ function(x = NULL,param){
return(log(param)^2‑param)
}
참조 솔루션
방법 1:
Use <<‑
storage <<‑ append(storage,inner.sol)
or assign
:
assign("storage", append(storage, inner.sol), .GlobalEnv))
Regarding modified problem where storage
is not in the global environment pass the environment that storage
is in to out.obj
as shown:
f2 <‑ function(y=NULL){
storage <‑ c()
sol <‑ optim(par = c(3),fn = out.obj, e = environment())
return(list("sol" = sol,"storage"=storage))
}
out.obj <‑ function(x, e){
inner.sol <‑ inner.obj(param = x)
assign("storage", append(e$storage, inner.sol), e)
return((x‑inner.sol)^2)
}
The assign
line could alternatively be written as:
e$storage <‑ append(e$storage, inner.sol)
(by math、G. Grothendieck)