Can Python Optimize A Variable To Get Max Pearson's Correlation Coefficient?
If I have pandas dataframe includes 3 columns Col1 & Col2& Col3 and I need to get max Pearson's correlation coefficient between Col2 and Col3 By considering the values in C
Solution 1:
This should work
import pandas as pd
import numpy as np
from scipy.optimize import minimize
# dataframe with 20 rows
df = pd.DataFrame(data=np.random.randn(20,3),
columns=['Col1', 'Col2', 'Col3'])
# cost function
def cost_fun(B_array, df):
B = B_array[0]
new_col1 = np.power((df['Col1']), B)
new_col2 = np.array(df['Col2']) * new_col1
col3 = np.array(df['Col3'])
pearson = np.corrcoef(new_col2, col3)[1,0]
return -1*pearson # multiply by -1 to get max
# initial value
B_0 = 1.1
# run minimizer
res = minimize(cost_fun, [B_0], args=(df),
options={"maxiter": 100,
"disp": True})
# results
print(res)
Post a Comment for "Can Python Optimize A Variable To Get Max Pearson's Correlation Coefficient?"