简体   繁体   English

编写最小-最大缩放器功能

[英]Writing Min-Max scaler function

I want to write a function for calculating Min-Max scale in python that return a list. 我想在python中编写一个用于计算最小-最大比例的函数,该函数返回一个列表。

x = [1, 2, 3, 4]

def normalize(x):

    for i in range(len(x)):
        return [(x[i] - min(x)) / (max(x) - min(x))]

Then calling the function: 然后调用该函数:

normalize(x):

results: 结果:

[0.0]

I was expecting the result to be: 我期望的结果是:

[0.00, 0.33, 0.66, 1.00] 

Based on @shehan's solution: 基于@shehan的解决方案:

x = [1, 2, 3, 4]

def normalize(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: 对于答案的循环版本,以便op可以理解:

x = [1, 2, 3, 4]

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

print(normalize(x))

Try this. 尝试这个。

def normalize(x):
    return [(x[i] - min(x)) / (max(x) - min(x)) for i in range(len(x))]

You are dividing by max(x) , then subtracting min(x) : 您要除以max(x) ,然后减去min(x)

You are also recalculating max(x) , and min(x) repeatedly. 您还将重复计算max(x)min(x) You could do something like this instead: 您可以改为执行以下操作:

x = [1, 2, 3, 4]

def normalize(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: 您可以按照@ruturaj的建议对结果进行四舍五入,如果这是您要保持的精度:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM