3
$\begingroup$

I have a couple of survey datasets that I am loading into Mathematica to do behavioral clustering.

I have columns of responses (Strings) where the users was given a fixed set of responses. The surveys are really high dimensions so I can't manually go through every question type and assign a value to each string in each one of these columns.

Is there a way I could encode the responses into numbers and do this for each column that has categorical responses like this?

For each column that looks like this food["apple","pear","apple","orange","pizza","pizza"] and convert it to food[1,2,1,3,4,4]

$\endgroup$
  • 2
    $\begingroup$ see ArrayComponents. $\endgroup$ – Kuba Oct 24 '17 at 16:45
6
$\begingroup$
food = {{"apple", "pizza"}, {"pear", "pizza"}, {"apple", 
    "orange"}, {"orange", "apple"}, {"pizza", "pear"}, {"pizza", 
    "apple"}};

enter image description here

fe = FeatureExtraction[
   food,
   {1 -> "IntegerVector", 2 -> "IndicatorVector"},
   FeatureTypes -> <|{1, 2} -> "Nominal"|>
   ];

fe@food // TableForm

enter image description here

fe@{"unknown_food", "unknown_food"}

{0, 0., 0., 0., 0.}

$\endgroup$
2
$\begingroup$

Try creating a range and and a rule to send the arguments to the range values.

food["apple","pear","apple","orange","pizza","pizza"]/.
 food[args___]:>With[{un=Union@{args}},With[{rng=Range@Length@un},
  food[args]/.Thread[un->rng]]]  
(*food[1,3,1,2,4,4]*)
$\endgroup$
2
$\begingroup$

NetEncoder is perfect for this:

encode[list_]:= NetEncoder[{"Class", DeleteDuplicates[list]}][list]

encode[{"apple","pear","apple","orange","pizza","pizza"}]

(*{1,2,1,3,4,4}*)
$\endgroup$

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.