I have a dictionary like this:
a = {'a': [0.2,0.3,0.6], 'b': [0.4,0.5,0.9], 'c': [0.7,0.1,0.6]}
I want to calculate the overall entropy of each list of this dictionary. To this end, I first need to calculate the entropy for each of probabilities within each list. I tried the below code:
lista_all = []
for i in a.values():
c = [0 - (p * -log2(p)) for p in i ]
lista_all.append(c)
But my result show that the loop is appending the same list to my empty list. So, my current result is:
[[-0.46438561897747244, -0.5210896782498619,
-0.44217935649972373], [-0.46438561897747244, -0.5210896782498619,
-0.44217935649972373], [-0.46438561897747244, -0.5210896782498619,
-0.44217935649972373]]
My desired output would be something like:
[
[-0.464, -0.521,-0.442],
[-0.529, -0.500, --0.137],
[-0.360, -0.332, -0.521]
]
Can someone help me to achieve this goal?
CodePudding user response:
Adding the round(num, digits) function for every element of the sub list, like this:
i = [round(0 - (p * - log2(p)),4) for p in i ]
P.S. I suppose the p in b
was p in i
some help here: https://www.w3schools.com/python/ref_func_round.asp
CodePudding user response:
I found a solution for my problem. I realized that I was using the incorrect variables. The code for the expected result is below:
lista=[]
for p in a.values():
c = [0 - (s * -log2(s)) for s in p]
lista.append(c)
I have also edited my question to fix the problem in the question as well.