Skip to content Skip to sidebar Skip to footer

Writing Min-max Scaler Function

I want to write a function for calculating Min-Max scale in python that return a list. x = [1, 2, 3, 4] def normalize(x): for i in range(len(x)): return [(x[i] - min(

Solution 1:

Based on @shehan's solution:

x = [1, 2, 3, 4]

defnormalize(x):
    return [round((i - min(x)) / (max(x) - min(x)), 2) for i in x]

print(normalize(x))

gives you exactly what you wanted. The result is rounded up unlike other solutions (as that's what you wanted).

result:

[0.0, 0.33, 0.67, 1.0]

For loop version of the answer so that op could understand:

x = [1, 2, 3, 4]

defnormalize(x):
    # A list to store all calculated values
    a = []
    for i inrange(len(x)):
        a.append([(x[i] - min(x)) / (max(x) - min(x))])
        # Notice I didn't return here# Return the list here, outside the loopreturn a

print(normalize(x))

Solution 2:

Try this.

defnormalize(x):
    return [(x[i] - min(x)) / (max(x) - min(x)) for i inrange(len(x))]

Solution 3:

You are dividing by max(x), then subtracting min(x):

You are also recalculating max(x), and min(x) repeatedly. You could do something like this instead:

x = [1, 2, 3, 4]

defnormalize(x):
    maxx, minx = max(x), min(x)
    max_minus_min = maxx - minx
    return [(elt - minx) / max_minus_min for elt in x]

You can round the results, as suggested by @ruturaj, if that is the precision you want to keep:

return [round((elt - minx) / max_minus_min, 2) for elt in x]

Post a Comment for "Writing Min-max Scaler Function"