【问题标题】:sklearn: how to get coefficients of polynomial featuressklearn:如何获得多项式特征的系数
【发布时间】:2023-04-03 11:15:02
【问题描述】:

我知道可以通过使用:polynomial_features.transform(X) 以数字形式获得多项式特征。根据manual,对于二度的特征是:[1, a, b, a^2, ab, b^2]。但是我如何获得对高阶特征的描述呢? .get_params() 不显示任何功能列表。

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    顺便说一句,现在有更合适的功能: PolynomialFeatures.get_feature_names.

    from sklearn.preprocessing import PolynomialFeatures
    import pandas as pd
    import numpy as np
    
    data = pd.DataFrame.from_dict({
        'x': np.random.randint(low=1, high=10, size=5),
        'y': np.random.randint(low=-1, high=1, size=5),
    })
    
    p = PolynomialFeatures(degree=2).fit(data)
    print p.get_feature_names(data.columns)
    

    这将输出如下:

    ['1', 'x', 'y', 'x^2', 'x y', 'y^2']
    

    注意出于某种原因,您必须先拟合 PolynomialFeatures 对象,然后才能使用 get_feature_names()。

    如果你是 Pandas 爱好者(就像我一样),你可以轻松地形成具有所有新功能的 DataFrame:

    features = DataFrame(p.transform(data), columns=p.get_feature_names(data.columns))
    print features
    

    结果将如下所示:

         1    x    y   x^2  x y  y^2
    0  1.0  8.0 -1.0  64.0 -8.0  1.0
    1  1.0  9.0 -1.0  81.0 -9.0  1.0
    2  1.0  1.0  0.0  1.0   0.0  0.0
    3  1.0  6.0  0.0  36.0  0.0  0.0
    4  1.0  5.0 -1.0  25.0 -5.0  1.0
    

    【讨论】:

    • 函数 get_feature_names 现已弃用,应使用 get_feature_names_out 代替。
    【解决方案2】:
    import numpy as np
    from sklearn.preprocessing import PolynomialFeatures
    
    X = np.array([2,3])
    
    poly = PolynomialFeatures(3)
    Y = poly.fit_transform(X)
    print Y
    # prints [[ 1  2  3  4  6  9  8 12 18 27]]
    print poly.powers_
    

    此代码将打印:

    [[0 0]
     [1 0]
     [0 1]
     [2 0]
     [1 1]
     [0 2]
     [3 0]
     [2 1]
     [1 2]
     [0 3]]
    

    所以如果第 i 个单元格是 (x,y),那意味着 Y[i]=(a**x)*(b**y)。 例如,在代码示例中,[2 1] 等于 (2**2)*(3**1)=12

    【讨论】:

      【解决方案3】:

      对于这样的数据框

      import pandas as pd
      import numpy as np
      from sklearn.preprocessing import PolynomialFeatures
      
      data = pd.DataFrame({
          'x': np.random.randint(low=1, high=10, size=5),
          'y': np.random.randint(low=-1, high=1, size=5)})
      

      这就是我的做法,

      PolyFeats = PolynomialFeatures(degree=2)
      dfPoly = pd.DataFrame(
          data=PolyFeats.fit_transform(data), 
          columns=PolyFeats.get_feature_names(data.columns))
      

      要得到这样的输出,

      In [50]: dfPoly
      Out[50]: 
           1    x    y   x^2  x y  y^2
      0  1.0  5.0  0.0  25.0  0.0  0.0
      1  1.0  6.0 -1.0  36.0 -6.0  1.0
      2  1.0  1.0 -1.0   1.0 -1.0  1.0
      3  1.0  5.0 -1.0  25.0 -5.0  1.0
      4  1.0  6.0  0.0  36.0  0.0  0.0
      

      【讨论】:

        猜你喜欢
        • 2020-01-14
        • 2016-03-26
        • 2015-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多