sklearn生成多项式

import numpy as np
from sklearn.preprocessing import PolynomialFeatures  #这哥用于生成多项式
x=np.arange(6).reshape(3,2) #生成三行二列数组
reg = PolynomialFeatures(degree=3) #这个3看下面的解释
reg.fit_transform(x)

python实现PolynomialFeatures多项式的方法

x是下面这样:

python实现PolynomialFeatures多项式的方法

我们发现规律如下:

python实现PolynomialFeatures多项式的方法

Python生成多项式

编写实现函数如下:

def multi_feature(x,n):
  c = np.empty((x.shape[0],0)) #np.empty((3,1))并不会生成一个3行1列的空数组,np.empty((3,0))才会生成3行1列空数组
  for i in range(n+1):
    for m in range(i,-1,-1):
      h=(x[:,0]**m) * (x[:,1]**(i-m))
      c=np.c_[c,h]
  return c

multi_feature(x,3)

python实现PolynomialFeatures多项式的方法

和上面实现的一模一样

print('n=4时,sklearn的输出是:')
reg = PolynomialFeatures(degree=4) 
print(reg.fit_transform(x))
print('\n')

#对比
print('n=4时,函数的输出是:')
print(multi_feature(x,4))

python实现PolynomialFeatures多项式的方法

也是一样的,当然这个函数仅适用于2维数组,如果是n维数组,又该怎么实现呢?

风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com