【问题标题】:Write PolynomialFeatures function from scikit-learn for F#从 scikit-learn 为 F# 编写 PolynomialFeatures 函数
【发布时间】:2018-10-03 05:47:55
【问题描述】:

我最近开始学习 F#,我了解了用于数据科学的 fslab,但是我似乎找不到任何类似于 Scikit-Learn (http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html) 中的 PolynomialFeatures 的函数

这个函数的一个简单例子是

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

我想知道是否有人为 F# 编写了像 PolynomialFeatures 这样的通用函数,谢谢。

【问题讨论】:

    标签: f# scikit-learn mathnet-numerics


    【解决方案1】:

    我猜现在使用 F# 的人不多,我通过查看 scikit-learn (https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/data.py) 中的 PolynomialFeatures 源代码找到了答案。

    但是,F# 没有 Python 中的“combinations_w_r”(或任何等价物),然后我查看了 Rosettacode (http://rosettacode.org/wiki/Combinations_with_repetitions),幸运的是他们的 OCAML 代码与 F# 完全相同,我将它们全部组合到以下代码

    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))
    

    测试

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

    代码按预期工作,但是我相信我的代码没有优化,并且可能会因为大列表和高阶多项式而变慢。

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 2020-04-30
      • 2015-07-25
      • 1970-01-01
      • 2018-08-01
      • 2016-09-15
      • 1970-01-01
      • 2016-04-22
      • 2015-06-26
      相关资源
      最近更新 更多