1

I recently started to learn F#, I have learnt about the fslab for data science, however I cannot seem to find any function similar to the PolynomialFeatures from Scikit-Learn (http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html)

A simple example for this function is

f [x;y] 2 -> [1;x;y;x**2;x*y;y**2]

I wonder if anyone has written a general function like PolynomialFeatures for F#, thanks.

Jose Vu
  • 621
  • 5
  • 13

1 Answers1

4

I guess not many people use F# nowsaday, I figured out the answer by looking at the PolynomialFeatures source code in scikit-learn (https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/data.py).

However, F# does not have the "combinations_w_r" (or any equivalent) as in Python, I then looked at the Rosettacode (http://rosettacode.org/wiki/Combinations_with_repetitions) and luckily their OCAML code is exactly same as F#, I combined them all to the following code

let PolyFeature ndgree (x:float list) = 
  let rec combsWithRep xxs k =
    match k, xxs with
    | 0,  _ -> [[]]
    | _, [] -> []
    | k, x::xs ->
        List.map (fun ys -> x::ys) (combsWithRep xxs (k-1))
        @ combsWithRep xs k
  let rec genCombtill n xlen =
      match n with
      | 0 -> List.empty
      | n -> (genCombtill (n-1) xlen) @ combsWithRep [0..(xlen-1)] n
  let rec mulList list1 =
     match list1 with
     | head :: tail -> head * (mulList tail)
     | [] -> 1.0
  let mul2List (b:float list) (a:int list) = [for i in a -> b.[i]] |>   mulList    
  1.0 :: ((genCombtill ndgree x.Length) |> List.map (mul2List x))

Test

> PolyFeature 2 [2.0;3.0];;
val it : float list = [1.0; 2.0; 3.0; 4.0; 6.0; 9.0]

The code works as expected, however I believe my code is not optimized and probably will be slow with large list and high order of polynomial.

Jose Vu
  • 621
  • 5
  • 13