Message Boards Message Boards

[?] Prevent recalculation within Manipulate?

I use the following code for testing kernel density estimation on the base of a random sample.

Manipulate[X = RandomVariate[NormalDistribution[0, 2], k];
 U1 = LearnDistribution[X, TrainingProgressReporting -> None, 
   PerformanceGoal -> "Speed", 
   Method -> {"KernelDensityEstimation", Method -> "Fixed", 
     "KernelType" -> "Ball", "KernelSize" -> KS }];
 Y = Table[{X[[q]], 0}, {q, 1, k}];
 TableForm[
  {   StringJoin["N: ", ToString[ k], "; Width : ", ToString[KS]],  
   ListPlot[Y, Filling -> Axis, PlotStyle -> {PointSize[0.03], Red}, 
    Axes -> {True, False}, PlotRange -> {{-4, 4}, {-1, 1}}, 
    ImageSize -> {500, 200}], 
   Plot[   PDF[U1, x], {x, -4, 4}, ImageSize -> {500, 200}, 
    PlotStyle -> {Thickness[0.01], Red} ]}], 
 {k, 3, 50, 1}, {KS, 0.1, 0.5}]

Here k is a sample size, KS -- kernel size.

All works fine, but when the kernel size is changed, random sample X is recalculated as well. It is desirable to prevent this recalculation in order to see dependency of PDF on different kernel sizes.

POSTED BY: Konstantin Nosov
3 Replies

I would make explicit the dependence of U1, Y from KS and k:

Clear[U1, X, Y];
U1[kernelSize_, sample_] := 
  LearnDistribution[sample, TrainingProgressReporting -> None, 
   PerformanceGoal -> "Speed", 
   Method -> {"KernelDensityEstimation", Method -> "Fixed", 
     "KernelType" -> "Ball", "KernelSize" -> kernelSize}];
Y[n_] := Table[{X[n][[q]], 0}, {q, 1, n}];
Manipulate[With[{dist = U1[KS, X[k]]},
  TableForm[{StringJoin["N: ", ToString[k], "; Width : ", 
     ToString[KS]], 
    ListPlot[Y[k], Filling -> Axis, 
     PlotStyle -> {PointSize[0.03], Red}, Axes -> {True, False}, 
     PlotRange -> {{-4, 4}, {-1, 1}}, ImageSize -> {500, 200}], 
    Plot[PDF[dist, x], {x, -4, 4}, ImageSize -> {500, 200}, 
     PlotStyle -> {Thickness[0.01], Red}]}]],
 {k, 3, 50, 1}, {KS, 0.1, 0.5}]
POSTED BY: Gianluca Gorni

I forgot the definition of X:

X[n_] := X[n] = RandomVariate[NormalDistribution[0, 2], n];
POSTED BY: Gianluca Gorni

Thank you. Your code does not work at my PC, but later I'll remove all errors.

POSTED BY: Konstantin Nosov
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract