Search code examples
pythonpandasoptimizationlinear-algebrascipy-optimize

Optimise a step function in Pandas using data


I have two dataframes (df_1 & df_2) and some variables (A,B,C):

df_1 = pd.DataFrame({'O' : [1,2,3], 'M' : [2,8,3]})
df_2 = pd.DataFrame({'O' : [1,1,1, 2,2,2, 3,3,3],
                     'M' : [9,2,4, 6,7,8, 5,3,4],
                     'X' : [2,4,6, 4,8,7, 3,1,9],
                     'Y' : [3,6,1, 4,6,5, 1,0,7],
                     'Z' : [2,4,8, 3,5,4, 7,5,1]})

I have an algorithm, below, that uses A,B,C to calculate a score (S) for each row in df_2. It finds the row in df_2 with the highest score (S). It compares the highest scoring row in df_2 with df_1 and calculates p_hat, a measure of the similarity between them:

M_G = df_1.M
df_1 = df_1.set_index('O')
        
A = 1
B = 1
C = 1
 
# Score
df_2['S'] = df_2['X']*A + df_2['Y']*B + df_2['Z']*C
        
# Top score
df_Sort = df_2.sort_values(['S', 'X', 'M'], ascending=[False, True, True])
df_O    = df_Sort.set_index('O')
M_Top   = df_O[~df_O.index.duplicated(keep='first')].M
M_Top   = M_Top.sort_index()
        
# Compare the top scoring row for each O to df_1
df_1_M = df_1.M
df_1_M = df_1_M.sort_index()
df_1_R = df_1_M.reindex(M_Top.index)
T_N_T  = M_Top == df_1_R

# Record the results for the given values of A,B,C
df_Res = pd.DataFrame({'it_is':T_N_T}) # is this row of df_1 the same as this row of M_Top?
        
# p_hat =         TP / (TP + FP)
p_hat = df_Res.sum() / len(df_Res.index)

For the values of A,B,C in the example, it gives p_hat = 0.333. I would like to find the values of A,B,C that give the maximum possible value of p_hat. I would like to use an optimisation algorithm to make sure that I get the maximum value please.

The graph is for C=2:

enter image description here How can I find the maximum p_hat please?


Solution

  • I found a way to do it using global, brute force optimisation:

    from scipy.optimize import brute
    
    df_1 = pd.DataFrame({'O' : [1,2,3], 'M' : [2,8,3]})
    
    df_2 = pd.DataFrame({'O' : [1,1,1, 2,2,2, 3,3,3],
                         'M' : [9,2,4, 6,7,8, 5,3,4],
                         'X' : [2,4,6, 4,8,7, 3,1,9],
                         'Y' : [3,6,1, 4,6,5, 1,0,7],
                         'Z' : [2,4,8, 3,5,4, 7,5,1]})
    
    
    
    # Range
    min_ = -2
    max_ = 2
    step = .5
    ran_ge = slice(min_, max_+step, step)
    ranges = (ran_ge,ran_ge,ran_ge)
    
    # Params
    params = (df_1, df_2)
    
    # Index
    df_1 = df_1.set_index('O')
    df_1_M = df_1.M
    df_1_M = df_1_M.sort_index()
    
    # Fun
    def fun(z, *params):
        A,B,C = z
            
        # Score
        df_2['S'] = df_2['X']*A + df_2['Y']*B + df_2['Z']*C
        
        # Top score
        df_Sort = df_2.sort_values(['S', 'X', 'M'], ascending=[False, True, True])
        df_O    = df_Sort.set_index('O')
        M_Top   = df_O[~df_O.index.duplicated(keep='first')].M
        M_Top   = M_Top.sort_index()
            
        # Compare the top scoring row for each O to df_1
        df_1_R = df_1_M.reindex(M_Top.index) # Nan
        T_N_T  = M_Top == df_1_R
    
        # Record the results for the given values of A,B,C
        df_Res = pd.DataFrame({'it_is':T_N_T}) # is this row of df_1 the same as this row of M_Top?
            
        # p_hat =         TP / (TP + FP)
        p_hat = df_Res.sum() / len(df_Res.index)
        
        return -p_hat
    
    # Brute
    resbrute = brute(fun,
                     ranges,
                     args=params,
                     full_output=True,
                     finish=None)
    
    print('Global maximum ',                   resbrute[0])
    print('Function value at global maximum ',-resbrute[1])
    

    It gives:

    Global maximum  [-2.   0.5  1.5]
    Function value at global maximum  0.6666666666666666