0

My problem is to create a function that optimizes the weights to reduce the MAPE between the actual and predicted values, the weights should range from 0.01 to 0.99....and then find the lease MAPE and the weights used to achieve that MAPE.

I've taken just two lists in the predicted, but i want to take 3 lists in that predicted list and the weights to be distributed among them...

actual   = [2,5,7,9,2]
print("The actual values are: ", actual)
predicted =np.array([[2,6,8,9,3], [2,4,6,8,2]]).astype(float)
print("The predicted values from models are: ", predicted)
mape=[]
for i in range(len(predicted)):
    mape_ = []
    for j in range(len(actual)):
        percentage_error = (actual[j]-predicted[i][j])/actual[j]
        percentage_error=abs(percentage_error)
        mape_.append(percentage_error)
    mape.append(np.array(mape_).mean())
print("The mape initially is: ",mape)
weights=[0.30,0.70]
print("The random weights are: ",weights)
newpredw1=weights[0]*predicted[0]
newpredw2=weights[1]*predicted[1]
newpred=[[newpredw1],[newpredw2]]
print("the newpred values are: ",newpred)
es1=np.sum(newpred, axis=0)
print("The sum of the newpred array is: ",es1)
mape=[]
for i in range(len(es1)):
    mape_ = []
    for j in range(len(actual)):
        percentage_error = (actual[j]-es1[i][j])/actual[j]
        percentage_error=abs(percentage_error)
        mape_.append(percentage_error)
    mape.append(np.array(mape_).mean())
print("The mape after adding weights: ",mape,"\n")

print("The mapes after adding list of weights: \n")

weights1 = [0.25, 0.22, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6 , 0.7 , 0.8, 0.9]
from sklearn.metrics import mean_absolute_percentage_error as MAPE
mape = []
for i in range(len(weights1)):
    temp_arr1 =predicted[0]*weights1[i]
    temp_arr2 =predicted[1]*(1-weights1[i])
    output = temp_arr1+temp_arr2
    mape.append(MAPE(actual, output))        
print("The new mapes after weighted average are:", mape)
print("The minimum value of mape is: ", min(mape), "and position is: ", mape.index(min(mape)))
print("The weights corresponding to it is: ", weights1[mape.index(min(mape))])

0 Answers0