Member-only story

Calculate class weights using a made from scratch function in Python

Crystal X
3 min readJul 3, 2024

--

In my most recent post I discussed calculating class weights using a for loop in Python and that work can be found here:- https://tracyrenee61.medium.com/calculate-class-weights-using-a-for-loop-in-python-55130ffa97c8

Once I had written the post, however, I realised that I could improve upon the code by converting it to a function, so that is the purpose of this post.

Whenever working on a machine learning project, it is important to ensure that the classification target is balanced, otherwise the target may have erroneous predictions.

The screenshot below is of an unbalanced classification target, which needs to be balanced:-

In order to achieve a targets with balanced weights, it is necessary to use the below formula for each class:-

weight _for_each_class = len(target) / (number_of_classes * number_of_samples_for each_class)

I have written a function that will encapsulate the formula in it, being:-

  1. Define the function, calc_class_weights, which will accept the target, y, as input.

--

--

Crystal X
Crystal X

Written by Crystal X

I have over five decades experience in the world of work, being in fast food, the military, business, non-profits, and the healthcare sector.

No responses yet