【发布时间】:2012-03-12 20:34:16
【问题描述】:
我正在尝试设置一个优化脚本,该脚本将查看一组模型,将曲线拟合到模型,然后根据一些参数在它们之间进行优化。
基本上,我将收入作为成本的函数,呈递减函数,并且我对多个投资组合(例如 4 或 5 个)都有这个。作为输入,我有成本和收入数字,以设定的增量。我想要做的是将曲线拟合到收入 = A*成本^B 形式的投资组合,然后在不同的投资组合中进行优化,以找到每个投资组合在设定预算下的最佳成本分配。
下面的代码(我为它的不雅致歉,我确信有很多改进!)基本上读取我的数据,在这种情况下,模拟,创建必要的数据帧(这很可能我的不雅之处),为每个模拟计算曲线的必要变量并生成图形以检查数据的拟合曲线。
我的问题是现在我有 5 条曲线:
revenue = A * Cost ^ B(每个功能不同的 A、B 和成本)
我想知道,给定 5 个变量,我应该如何在它们之间分配成本,所以我想优化 5 条曲线的总和
成本
我知道我需要使用 constrOptim,但我已经花了好几个小时把头撞在桌子上(字面意思是几个小时,而不是真正地敲我的头......),但我仍然不知道如何设置功能,使其收入最大化,受成本约束...
这里的任何帮助将不胜感激,这已经困扰我好几个星期了。
谢谢!
丰富
## clear all previous data
rm(list=ls())
detach()
objects()
library(base)
library(stats)
## read in data
sim<-read.table("input19072011.txt",header=TRUE)
sim2<-data.frame(sim$Wrevenue,sim$Cost)
## identify how many simulations there are - here you can change the 20 to the number of steps but all simulations must have the same number of steps
portfolios<-(length(sim2$sim.Cost)/20)
## create a matrix to input the variables into
a<-rep(1,portfolios)
b<-rep(2,portfolios)
matrix<-data.frame(a,b)
## create dummy vector to hold the revenue predictions
k<-1
j<-20
for(i in 1:portfolios){
test<-sim2[k:j,]
rev9<-test[,1]
cost9<-test[,2]
ds<-data.frame(rev9,cost9)
rhs<-function(cost, b0, b1){
b0 * cost^b1
m<- nls(rev9 ~ rhs(cost9, intercept, power), data = ds, start = list(intercept = 5,power = 1))
matrix[i,1]<-summary(m)$coefficients[1]
matrix[i,2]<-summary(m)$coefficients[2]
k<-k+20
j<-j+20
}
## now there exists a matrix of all of the variables for the curves to optimise
matrix
multiples<-matrix[,1]
powers<-matrix[,2]
coststarts<-rep(0,portfolios)
## check accuracy of curves
k<-1
j<-20
for(i in 1:portfolios){
dev.new()
plot(sim$Wrevenue[k:j])
lines(multiples[i]*(sim$Cost[k:j]^powers[i]))
k<-k+20
j<-j+20
}
【问题讨论】:
标签: r