简体   繁体   中英

Different results for polynomial regression in R and Python

I'm trying to reproduce a piece of python code in R. This code uses the fit_transform() function from the sklearn.preprocessing.PolynomialFeatures package and I'm not understanding why R's poly() function is not outputting the same results. Does anyone know how to achieve the same number of the python code in R and why poly() is not returning the same results as fit_transform() ?

R Code

poly(c(17:25),4, simple = TRUE)

R output

               1          2             3          4
 [1,] -0.5163978  0.5318160 -4.449492e-01  0.3128931
 [2,] -0.3872983  0.1329540  2.224746e-01 -0.4693397
 [3,] -0.2581989 -0.1519474  4.131671e-01 -0.2458446
 [4,] -0.1290994 -0.3228883  2.860388e-01  0.2011456
 [5,]  0.0000000 -0.3798686  2.352347e-17  0.4022911
 [6,]  0.1290994 -0.3228883 -2.860388e-01  0.2011456
 [7,]  0.2581989 -0.1519474 -4.131671e-01 -0.2458446
 [8,]  0.3872983  0.1329540 -2.224746e-01 -0.4693397
 [9,]  0.5163978  0.5318160  4.449492e-01  0.3128931

Python Code

import numpy as np
from sklearn.preprocessing import PolynomialFeatures

poly = PolynomialFeatures(degree = 4)
foo = np.array([range(17,26)]).reshape(-1,1)
print(poly.fit_transform(foo))

Python Output

[[1.00000e+00 1.70000e+01 2.89000e+02 4.91300e+03 8.35210e+04]
 [1.00000e+00 1.80000e+01 3.24000e+02 5.83200e+03 1.04976e+05]
 [1.00000e+00 1.90000e+01 3.61000e+02 6.85900e+03 1.30321e+05]
 [1.00000e+00 2.00000e+01 4.00000e+02 8.00000e+03 1.60000e+05]
 [1.00000e+00 2.10000e+01 4.41000e+02 9.26100e+03 1.94481e+05]
 [1.00000e+00 2.20000e+01 4.84000e+02 1.06480e+04 2.34256e+05]
 [1.00000e+00 2.30000e+01 5.29000e+02 1.21670e+04 2.79841e+05]
 [1.00000e+00 2.40000e+01 5.76000e+02 1.38240e+04 3.31776e+05]
 [1.00000e+00 2.50000e+01 6.25000e+02 1.56250e+04 3.90625e+05]]

It turns out that all I needed to do was setting raw = TRUE in the R's poly() function to bring the raw and not orthogonal polynomials. R's output is in common notation and sklearn's output is in scientific notation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM