Why class_weights doesn't work and error appear?

Issue

I defind classws_to_predict and I have class_weight code as below.

classes_to_predict = sorted(samples_df.bird.unique())
input_shape = (216,216, 3)
effnet_layers = EfficientNetB0(weights=None, include_top=False, input_shape=input_shape)

for layer in effnet_layers.layers:
    layer.trainable = True

dropout_dense_layer = 0.3

model = Sequential()
model.add(effnet_layers)
    
model.add(GlobalAveragePooling2D())
model.add(Dense(256, use_bias=False))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(dropout_dense_layer))

model.add(Dense(len(classes_to_predict), activation="softmax"))
from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight("balanced", classes_to_predict, samples_df.bird.values)
class_weights_dict = {i : class_weights[i] for i,label in enumerate(classes_to_predict)}

And error occure.

> --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call
> last) Input In [15], in <cell line: 1>()
> ----> 1 class_weights = class_weight.compute_class_weight("balanced", classes_to_predict, samples_df.bird.values)
>       2 class_weights_dict = {i : class_weights[i] for i,label in enumerate(classes_to_predict)}
> 
> TypeError: compute_class_weight() takes 1 positional argument but 3
> were given

How I can fix this error?
Thank you very much for supporting

Solution

Please check the documentation. All parameters but the first have to be named.

class_weights = class_weight.compute_class_weight("balanced", classes=classes_to_predict, y=samples_df.bird.values)`.

https://scikit-learn.org/stable/modules/generated/sklearn.utils.class_weight.compute_class_weight.html

Answered By – Tim Roberts

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published