trevorstephens / gplearn

Genetic Programming in Python, with a scikit-learn inspired API
http://gplearn.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
1.56k stars 274 forks source link

Custom Fitness with predetermined weights #253

Closed Konparginos closed 2 years ago

Konparginos commented 2 years ago

I'm trying to create a custom fitness function for a Symbolic Regressor that requires data from a specific weight matrix.

Unfortunately, I can't figure out how to add specific weights to custom fitness and I'm ending up with errors : IndexError: invalid index to scalar variable.

A toy example to better understand what I'm trying is the following: Let's say that we want to predict the #amount of goods to sell 'y_pred', while we know the actual #amount of goods sold 'y'. I want to create a fitness function that: maximizes profit.

To make such a function we will need an external weight matrix: For our toy example will represent the prices (wmatrix[0]) and the cost (wmatrix[1]) of each #y ~ wmatrix=[[100,50,60,70,80....], [-10,-5,-6,-7,-8....]]

This is what I'm trying to do:

def _fitnessprofit(y, y_pred, wmatrix):

     GoodsSoldDelta = y - y_pred

     Revenue= y_pred * wmatrix[0]
     Profit= Revenue - GoodsSoldDelta*wmatrix[1]]

     return sum(Profit)

fitnessprofit = make_fitness(_fitnessprofit, greater_is_better=True)

Is there a way to add those predetermined weights in my custom fitness? Thank you in advance!

trevorstephens commented 2 years ago

The weights are for weighting certain samples (rows) and expects a vector. It works with sample weights and class weights. If it's a specified matrix you might be able to reference it or define it within your custom function but that argument you are using is expecting a vector, not a matrix