脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现PolynomialFeatures多项式的方法

python实现PolynomialFeatures多项式的方法

2021-08-22 00:35Dream-YH Python

这篇文章主要介绍了python实现PolynomialFeatures多项式的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

sklearn生成多项式

?
1
2
3
4
5
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生成多项式

编写实现函数如下:

?
1
2
3
4
5
6
7
8
9
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多项式的方法

和上面实现的一模一样

?
1
2
3
4
5
6
7
8
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维数组,又该怎么实现呢?

到此这篇关于python实现polynomialfeatures多项式的方法的文章就介绍到这了,更多相关python polynomialfeatures多项式内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_44700798/article/details/110508496

延伸 · 阅读

精彩推荐