How to find the maximum value of a function changi

2019-08-27 17:42发布

I have the following linearized plot:

enter image description here

a and b are vectors with data, c is a constant. The task is find a value of c that maximizes R^2 for a linear regression

a <- c(56.60, 37.56, 15.80, 27.65, 9.20, 5.05, 3.54)
b <- c(23.18, 13.49, 10.45, 7.24, 5.44, 4.19, 3.38)
c <- 1

x <- log(a)
y <- log((c*(a/b))-1)

rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(x, y)

optimise(rsq, maximum = TRUE)

1条回答
Explosion°爆炸
2楼-- · 2019-08-27 18:11

This works:

a <- c(56.60, 37.56, 15.80, 27.65, 9.20, 5.05, 3.54)
b <- c(23.18, 13.49, 10.45, 7.24, 5.44, 4.19, 3.38)

rsq <- function(c) {
  x <- log(a)
  y <- log((c*(a/b))-1)
  stopifnot(all(is.finite(y)))  
  summary(lm(y ~ x))$r.squared
}
optimise(rsq, maximum = TRUE, interval=c(0.8, 3))

.

# > optimise(rsq, maximum = TRUE, interval=c(0.8, 3))
# $maximum
# [1] 1.082352
# 
# $objective
# [1] 0.8093781

You can also have a nice plot:

plot(Vectorize(rsq), .8, 3)
grid()

To set a condition for the observations you can do

rsq <- function(c) {
  xy <- data.frame(a=a, y=(c*(a/b))-1)
  summary(lm(log(y) ~ log(a), data=subset(xy, y>0)))$r.squared
}
optimise(rsq, maximum = TRUE, interval=c(0.1, 3))

... and the interesting plot:

plot(Vectorize(rsq), .3, 1.5)
grid()

rsq(0.4) 
查看更多
登录 后发表回答