Python equivalent to R poly() function?

前端 未结 2 681
花落未央
花落未央 2021-02-15 18:25

I\'m trying to understand how to replicate the poly() function in R using scikit-learn (or other module).

For example, let\'s say I have a vector in R:

a         


        
2条回答
  •  逝去的感伤
    2021-02-15 18:56

    The answer by K. A. Buhr is full and complete.

    The R poly function also calculates interactions of different degrees of the members. That's why I was looking for the R poly equivalent.
    sklearn.preprocessing.PolynomialFeatures Seems to provide such, you can do the np.linalg.qr(X)[0][:,1:] step after to get the orthogonal matrix.

    Something like this:

    import numpy as np
    import pprint
    import sklearn.preprocessing
    PP = pprint.PrettyPrinter(indent=4)
    
    MATRIX = np.array([[ 4,  2],[ 2,  3],[ 7,  4]])
    poly = sklearn.preprocessing.PolynomialFeatures(2)
    PP.pprint(MATRIX)
    X = poly.fit_transform(MATRIX)
    PP.pprint(X)
    

    Results in:

    array([[4, 2],
           [2, 3],
           [7, 4]])
    array([[ 1.,  4.,  2., 16.,  8.,  4.],
           [ 1.,  2.,  3.,  4.,  6.,  9.],
           [ 1.,  7.,  4., 49., 28., 16.]])
    

提交回复
热议问题