3
$\begingroup$

I have never understood how to use Cases to extract items from objects (other than exactly copying code written by others which, again, means I don't understand).

I have a LearnedDistribution object that upon using FullForm I see the item I want:

Rule["KernelSize", 0.5103377664280484`]

I've been able to obtain the "KernelSize" with the following:

SeedRandom[12345];
data = RandomVariate[NormalDistribution[0, 1], 100];
ld = LearnDistribution[data, Method -> "KernelDensityEstimation"]
kernelSize = Cases[ld, First@Association[_]][[1, 6, 2]]
(* 0.510338 *)

But using the index [[1, 6, 2]] has to be fragile at best. What is a less fragile and more Mathematica way to get that value?

This is related to my partial answer about exporting information to obtain random samples from a LearnedDistribution object.

$\endgroup$
3
$\begingroup$

Since the output of LearnDistribution is a LearnedDistribution object, and since its contents is an association, I'd recommend interrogating the association directly via its keys. To extract the kernel size, then, you could use:

First[ld]["Model", "KernelSize"]

(* Out: 0.510338 *)

In the above, First[ld] returns the association that contains all the juicy bits. I then found the rights keys to use on it by inspecting the InputForm of the LearnedDistribution object (which I find more readable than the FullForm at least for a first glance).


In passing, I like to use the combination ld // InputForm // SequenceForm which I've learned from Carl Woll here: it gives nice "parseable" text where e.g. multiple clicks work to expand selection like in regular code (which doesn't work directly on the normal output of InputForm).

$\endgroup$
2
  • $\begingroup$ Thank you for both answers: how to get the kernel size and InputForm// SequenceForm approach! $\endgroup$
    – JimB
    Mar 27 at 14:48
  • $\begingroup$ @JimB You are very welcome. Thank you for the accept as well! $\endgroup$
    – MarcoB
    Mar 27 at 19:36

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.