-1
$\begingroup$

I'm attempting to compute the class_weights for an highly imbalanced set of 9 classes based on the examples discussed in How to set class weights for imbalanced classes in Keras?. Here is the code:

import numpy as np
import math

# labels_dict : {ind_label: count_label}
# mu : parameter to tune 

def create_class_weight(labels_dict,mu=0.15):
    total = np.sum(labels_dict.values())
    keys = labels_dict.keys()
    class_weight = dict()

    for key in keys:
        score = math.log(mu*total/float(labels_dict[key]))
        class_weight[key] = score if score > 1.0 else 1.0

    return class_weight

# random labels_dict
labels_dict = {0: 3400, 1: 1700, 2: 4700, 3: 6800, 4: 3400, 5: 2300, 6: 8300, 7: 1000, 8:9600}

create_class_weight(labels_dict)

I'm getting an error log like this:

 File "<ipython-input-34-7a9feda1053b>", line 20, in <module>
    create_class_weight(labels_dict)

  File "<ipython-input-34-7a9feda1053b>", line 11, in create_class_weight
    score = math.log(mu*total/float(labels_dict[key]))

TypeError: unsupported operand type(s) for *: 'float' and 'dict_values'

I'm running the code with Python 3.6.3. What modifications am I supposed to make?

$\endgroup$
1
  • $\begingroup$ This is more of a StackOverflow question. Nothing related to Data Sciene. $\endgroup$ – enterML Jan 12 '18 at 16:50
1
$\begingroup$

You can't use numpy to sum the values of a dictionary. You have to use sum function.

total = sum(labels_dict.values())

Now you can check that total is an integer :

print(type(total))

class 'int'

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.