生成多项式特征(Polynomial Features)是一种常用的数据处理方法,用于将输入特征转换为多项式特征。

标准代码如下

def polynomial_features(X, degree):
    n_samples, n_features = np.shape(X)

    # Generate all combinations of feature indices for polynomial terms
    def index_combinations():
        combs = [combinations_with_replacement(range(n_features), i) for i in range(0, degree + 1)]
        flat_combs = [item for sublist in combs for item in sublist]
        return flat_combs
    
    combinations = index_combinations()
    n_output_features = len(combinations)
    X_new = np.empty((n_samples, n_output_features))
    
    # Compute polynomial features
    for i, index_combs in enumerate(combinations):  
        X_new[:, i] = np.prod(X[:, index_combs], axis=1)

    return X_new

本题也可以使用sklearn库的PolynomialFeatures模型实现,这里给出具体实现:

def polynomial_features(X, degree):
    from sklearn.preprocessing import PolynomialFeatures
    poly = PolynomialFeatures(degree=degree)
    return poly.fit_transform(X)