• R语言
  • 帮忙看看这个优化函数那里写错了?

factanal.fit.uls <- function(cmat, factors, start=NULL, lower = 0.005, control = NULL, ...)

##算法出处

## [url]ftp://ftp.spss.com/pub/spss/statistics/spss/algorithms/[/url] factor.pdf

## http://www1.uni-hamburg.de/RRZ/Software/SPSS/Algorith.115/factor.pdf

##PP5-6

{

  FAfn <- function(Psi, S, q)

  {

    Sstar <- S - diag(Psi)

    E <- eigen(Sstar, symmetric = TRUE, only.values = TRUE)

    e <- E$values[-(1:q)]

    e <- sum(e^2/2)

    e

  }

 

  FAgr <- function(Psi, S, q)

  ## Incorrect

  {

    Sstar <- S - diag(Psi)

    E <- eigen(Sstar, symmetric = TRUE)

    L <- E$vectors[, -(1:q), drop = FALSE]

    e <- E$values[-(1:q)]

    gr <- 2*Psi*((L^2)%*%e)

    gr

  }



  p <- ncol(cmat)

  if(is.null(start))

    start <- (1 - 0.5*factors/p)/diag(solve(cmat))

  res <- optim(start, FAfn,

      #     FAgr,

          method="L-BFGS-B",

          lower = lower, upper = 1,

          control = c(list(fnscale=1,

          parscale = rep(0.01, length(start))), control),

          q = factors, S = cmat)

res

}



好像FAgr这个函数写错了。但是不知道应该如何写才对。



covmat <-

structure(c(1, 0.0920030858518061, 0.053952442382614, -0.0380048634941013,

0.237986469993129, 0.243144461077282, 0.0920030858518061, 1,

0.328163804480881, 0.142002180914605, -0.139369611642031, -0.0670944471678571,

0.053952442382614, 0.328163804480881, 1, 0.267648727315665, -0.0549987508157441,

-0.107488501744669, -0.0380048634941013, 0.142002180914605, 0.267648727315665,

1, -0.0566976575082817, -0.132943658387513, 0.237986469993129,

-0.139369611642031, -0.0549987508157441, -0.0566976575082817,

1, 0.352367996102745, 0.243144461077282, -0.0670944471678571,

-0.107488501744669, -0.132943658387513, 0.352367996102745, 1), .Dim = c(6L,

6L), .Dimnames = list(c("bg2cost1", "bg2cost2", "bg2cost3", "bg2cost4",

"bg2cost5", "bg2cost6"), c("bg2cost1", "bg2cost2", "bg2cost3",

"bg2cost4", "bg2cost5", "bg2cost6")))





> factanal.fit.uls(covmat,2)

$par

bg2cost1 bg2cost2 bg2cost3 bg2cost4 bg2cost5 bg2cost6

0.7454829 0.7191459 0.6969019 0.7611750 0.6940870 0.6930580



$value

[1] 0.02167674



$counts

function gradient

    21     21



$convergence

[1] 52



$message

[1] "ERROR: ABNORMAL_TERMINATION_IN_LNSRCH"