多项式特征Sklearn(许多参数)

时间:2018-08-10 11:00:44

标签: python scikit-learn

这是我的代码。

 import numpy as np
 from sklearn.preprocessing import PolynomialFeatures
 from sklearn.linear_model import LinearRegression
 X=np.array([[1, 2, 4]]).T
 print(X)
 y=np.array([1, 4, 16])
 print(y)
 X_poly = PolynomialFeatures(degree=2).fit_transform(X)
 print(X_poly)
 # fit_intercept = False since PolynomialFeatures will create a 0-order   
 polynomial as well.
 model = LinearRegression(fit_intercept = False)
 model.fit(X_poly,y)

print('Coefficients: \n', model.coef_)
print('Others: \n', model.intercept_)

请,如何更改此代码以使用许多参数。 型号示例:

y=a*x*x+b * z+ c* t (we have y, x, z and t)

非常感谢您的帮助。 亲切的问候。

1 个答案:

答案 0 :(得分:1)

只需在X中使用多个列表即可。

X = np.array([[1, 2, 4],
              [2, 3, 9]]).T     #<== Added a second list
print(X)
# Output
feature1  feature2
     1         2
     2         3
     4         9

y = np.array([1, 4, 16])

因此,这里的数据具有两个功能。现在,您可以简单地使用之前使用的相同代码:

X_poly = PolynomialFeatures(degree=2).fit_transform(data)
print(X_poly)
# Output
[[ 1.  1.  2.  1.  2.  4.]
 [ 1.  2.  3.  4.  6.  9.]
 [ 1.  4.  9. 16. 36. 81.]]


model = LinearRegression(fit_intercept = False)
model.fit(X_poly,y)
print('Coefficients: \n', model.coef_)
# Output
('Coefficients: \n', array([-0.10133796,  0.1456888 , -0.01660059,  0.54831516,  0.45019822,
                            -0.11496531]))

print('Others: \n', model.intercept_)
# Output
('Others: \n', 0.0)