0
$\begingroup$

I have a cost function and I want to find which variables minimize it using the built-in method FindMinimum

My cost function is this (keep in mind that y is a list)

myCostFunction[y_, target_, expectedProbsTotal_] := 
 Module[{n, p, myCost, sumProbs, values, x},

  n = 3;
  myCost = 0;
  sumProbs = 0;

  p = Table[0, 3];

  For[i = 1, i <= n, i++,

   p[[i]] = 1/(1 + Exp[-y[[i]]]);
   sumProbs += p[[i]];

   ]; (* for *)

  values = Table[0, 3];

  For[i = 1, i <= 3, i++,
   values[[i]] = p[[i]]
   ];


  For[i = 1, i <= 3, i++,
   x = values[[i]] - target[[i]];
   myCost += x*x;
   ];

  myCost = Sqrt[myCost/n] + Abs[sumProbs - expectedProbsTotal];
  myCost

  ]

What I am trying to do, using the syntax found here is to find the values of list y that minimize my cost function, assuming that I have some initial values of

{0.6, -1.12, -1.5}

while myTarget = {1.5, 3.5, 5};

I tried this but it is not working

FindMinimum[
 myCostFunction[x, myTarget, 
  1], {{x[[1]], 0.6}, {x[[2]], -1.12}, {x[[3]], -1.5}}]

the error i get is:

FindMinimum::vloc: The variable x[1] cannot be localized so that it can be assigned to numerical values.

I also tried the constraint x[[1]]+x[[2]]+x[[3]]==1 but it doesn't work either.

$\endgroup$
2
$\begingroup$
FindMinimum[myCostFunction[{x1, x2 , x3}, myTarget,1], {{x1, 0.6`}, {x2, -1.12`}, {x3, -1.5`}}, Method -> "PrincipalAxis"]
(*{3.39899, {x1 -> 0.288232, x2 -> -1.12, x3 -> -1.5}}*)

works.

If list argument x=x1,x2,x3} is an issue:

x = {x1, x2, x3}
FindMinimum[myCostFunction[x, myTarget, 1],MapThread[{#1, #2} &, {x, {0.6,-1.12, -1.5}}], Method -> "PrincipalAxis"]    

gives the same result.

$\endgroup$
  • $\begingroup$ I was looking for a syntax like this, excellent, thanks $\endgroup$ – Tom Zinger Jul 25 '18 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.