python - 使用 numpy/python 从头开始​​进行多项式展开

标签 python pandas numpy regression polynomials

我正在不使用 Sklearn 构建多项式回归。 我现在在特征多项式展开方面遇到了麻烦。

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

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

变成A2 + 2AB + 2AC + 2BC + B2 + C2,6个不同的特征。我试图用 Python 和 Numpy 来概括这一点。

由于存在常数 c,我在数据框中创建了一个新列 C。然而,我对之后如何继续感到非常困惑。我尝试了 for 循环(特征数 * 度数 #)次,但对特征的组合感到困惑。

'''

    def polynomial_expansion(features_df, order):

        return expanded_df

'''

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

最佳答案

我创建了一个简单的示例,说明您需要做什么才能从头开始创建多项式特征。代码的第一部分创建 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   

关于python - 使用 numpy/python 从头开始​​进行多项式展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58867481/

相关文章:

python - 如何计算pandas数据框中从一个数据点到所有其他数据点的欧几里德距离之和?

python - 在 pandas 中插入日期

python - 组中最后一项的虚拟变量

python - 使用 [ :] syntax 的 numpy 维度问题

python - 如何解决TypeError : unsupported operand type(s) for +: 'float' and 'tuple'

javascript - Python 到 JavaScript 转换器

python - 元组错误中的元组

python - 如何格式化 tqdm 进度条以显示每分钟而不是每秒的进度?

python - 什么数据库对于替换 numpy 数组的字典有用?

python - np.random.normal 的非随机采样版本