Python: create a polynomial of degree n

I have a feature set

[x1,x2....xm] 

Now I want to create a set of polynomial functions. This means that if the degree is two, then I have a set of functions

 [x1.... xm,x1^2,x2^2...xm^2, x1x2, x1x3....x1,xm......xm-1x1....xm-1xm] 

Thus, it only contains members of order 2. the same if the order is three ... then you will also have cubic terms.

How to do it?

Edit 1: I am working on a machine learning project where I have about 7 functions ... and non-linear regression on these linear functions gives a good result ... Therefore, I thought that getting more numbers in I could match these functions with more high size. Thus, one way is to consider the polynomial order of the vector function ... Also generating x1 * x1 is easy .. :) but getting the rest of the combinations is a bit difficult.

Can combinations give me x1x2x3 result if order 3?

+4
source share
3 answers

Using

 itertools.combinations(list, r) 

where list is the set of functions, and r is the order of the required polynomial features. Then multiply the subexpression elements above. This should give you {x1*x2, x1*x3, ...} . You will need to build others and then combine all the parts.

[Edit] Better: itertools.combinations_with_replacement(list, r) will nicely produce sorted roots of length-r with valid repeating elements.

+4
source

You can use itertools.product to create all possible sets of n values ​​selected from the original set; but keep in mind that this will generate (x2, x1) as well as (x1, x2) .

Similarly, itertools.combinations will create sets without repetition or reordering, but that means you will not get (x1, x1) , for example.

What exactly are you trying to do? What are these result values ​​for? Are you sure you want to use those terms like x1^2 (what does it mean to have the same function more than once)? What is a "function" in this context?

+3
source

Using Karl to respond as inspiration, try to use the product, and then use the given object. Sort of,

 set([set(comb) for comb in itertools.product(range(5),range(5)]) 

This will save you from repeated pairs. Then you can rotate the set back to the list and sort it or sort it out as you wish.

EDIT: this will actually destroy the terms x_m^2 , so build sorted tuples instead of sets. this will allow the terms to be hashed and non-repeating.

 set([tuple(sorted(comb)) for comb in itertools.product(range(5),range(5))]) 
0
source

Source: https://habr.com/ru/post/1387472/


All Articles