Member-only story

Calculate class weights using a for loop in Python

Crystal X
3 min readJul 3, 2024

--

In my last post I devised a rather rudimentary way to calculate class weights using Python, and that post can be found here:- https://tracyrenee61.medium.com/use-python-to-calculate-class-weights-in-machine-learning-d91545f390d8

After I posted the post, it occurred to me that if I used a for loop I could streamline the code and make it more efficient. I thought about it and decided to modify the code to make it suitable for a multiclass target.

The histogram below is of a binary target and it can be seen that the classes must be balanced in an attempt to attain a more accurate prediction:-

The Python code below is a modification of the previous code that I have written. This code is suitable dor a target that has more than two classes:-

  1. Define the variable, class_values, which reveals the counts of each unique value in the target.
  2. Define the number of classes in the target.
  3. Define an empty list, weight.
  4. Create a for loop that will iterate through the number of classes and define the calculate the weight for each unique class in the target…

--

--

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