从零开始使用numpy / python进行多项式扩展

时间:2019-11-14 22:30:16

标签: python pandas numpy regression polynomials

我在不使用Sklearn的情况下建立多项式回归。 我现在无法使用功能的多项式扩展。

我有一个带有A和B列的数据框。 当我从Sklearn导入并运行PolynomialFeatures(2级)时,我发现它返回6个不同的特征。

我知道2个特征变成6个特征,因为它是(A + B +常数)*(A + B +常数)

变为A2 + 2AB + 2AC + 2BC + B2 + C2,有6种不同的功能。我正在尝试使用Python和Numpy对此进行概括。

由于存在常数c,所以我在数据框中创建了一个新列C。但是,我对如何进行此操作非常执着。我尝试了(特征数*度数)次的循环,但对特征的组合感到困惑。

'''

    def polynomial_expansion(features_df, order):

        return expanded_df

'''

有人可以帮我吗?在这种情况下,我可以使用什么Python / Numpy / Pandas方法? 谢谢。

1 个答案:

答案 0 :(得分:1)

我创建了一个简单的示例,说明了从头开始创建多项式特征所需执行的操作。代码的第一部分从Scikit Learn创建结果:

from sklearn.preprocessing import PolynomialFeatures
import pandas as pd
import numpy as np

df = pd.DataFrame.from_dict({
    'x': [2],
    'y': [5],
    'z': [6]})

p = PolynomialFeatures(degree=2).fit(df)
f = pd.DataFrame(p.transform(df), columns=p.get_feature_names(df.columns))
print('deg 2\n', f)
p = PolynomialFeatures(degree=3).fit(df)
f = pd.DataFrame(p.transform(df), columns=p.get_feature_names(df.columns))
print('deg 3\n', f)

结果如下:

deg 2
      1    x    y    z  x^2   x y   x z   y^2   y z   z^2
0  1.0  2.0  5.0  6.0  4.0  10.0  12.0  25.0  30.0  36.0
deg 3
      1    x    y    z  x^2   x y   x z   y^2   y z   z^2  x^3  x^2 y  x^2 z  x y^2  x y z  x z^2    y^3  y^2 z  y z^2    z^3
0  1.0  2.0  5.0  6.0  4.0  10.0  12.0  25.0  30.0  36.0  8.0   20.0   24.0   50.0   60.0   72.0  125.0  150.0  180.0  216.0

现在要在没有Scikit Learn的情况下创建类似的功能,我们可以这样编写代码:


row = [2, 5, 6]

#deg = 1
result = [1]
result.extend(row)

#deg = 2
for i in range(len(row)):
    for j in range(len(row)):
        res=row[i]*row[j]
        if res not in result:
            result.append(res)
print("deg 2", result)

#deg = 3
for i in range(len(row)):
    for j in range(len(row)):
            for z in range(len(row)):
                res=row[i]*row[j]*row[z]
                if res not in result:
                    result.append(res)
print("deg 3", result)

结果如下:

deg 2 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36]
deg 3 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36, 8, 20, 24, 50, 60, 72, 125, 150, 180, 216]

要递归获得相同的结果,可以使用以下代码:

row = [2, 5, 6]
def poly_feats(input_values, degree):
    if degree==1:
        if 1 not in input_values:
            result = input_values.insert(0,1)
        result=input_values
        return result
    elif degree > 1:
        new_result=[]
        result = poly_feats(input_values, degree-1)
        new_result.extend(result)
        for item in input_values:
            for p_item in result:
                res=item*p_item
                if (res not in result) and (res not in new_result):
                    new_result.append(res)
        return new_result

print('deg 2', poly_feats(row, 2))
print('deg 3', poly_feats(row, 3))

结果将是:

deg 2 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36]
deg 3 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36, 8, 20, 24, 50, 60, 72, 125, 150, 180, 216]

此外,如果您需要使用Pandas数据框作为该功能的输入,则可以使用以下内容:

def get_poly_feats(df, degree):
    result = {}
    for index, row in df.iterrows():
        result[index] = poly_feats(row.tolist(), degree)
    return result