【问题标题】:How to normalize an array with rounding the result (python, numpy, scipy)如何通过舍入结果来规范化数组(python、numpy、scipy)
【发布时间】:2020-05-03 21:25:07
【问题描述】:

进一步不是正确的代码。 如何让它正确、简短、美观?

def normalize_weights(weights, threshold=0.01):
    total = sum(weights)
    result = [x / total for x in weights]
    result = [int((1.0 / threshold) * x) * threshold for x in result]
    result[-1] = 1.0 - sum(result[:-1])
    print(result)
    result[-1] = int((1.0 / threshold) * result[-1]) * threshold
    print(result)

normalize_weights([1.0, 1.0, 1.0])
[0.33, 0.33, 0.33999999999999997]
[0.33, 0.33, 0.34]  # ok

normalize_weights([1.0, 3.0, 1.0])
[0.2, 0.6, 0.19999999999999996]
[0.2, 0.6, 0.19]  # wrong

提前致谢

编辑:结果的总和应该等于 1.0

【问题讨论】:

  • 第二次调用函数的期望输出是什么?
  • [0.2,0.6,0.2] 结果的总和应该等于 1.0。

标签: python numpy normalize


【解决方案1】:
a = numpy.array([1.0,3.0,1.0])
normalized_a = numpy.round(a/numpy.linalg.norm(a,1.0),2)
# [0.2,0.6,0.2]

也许?

a = numpy.array([1.0,1.0,1.0])
normalized_a = numpy.round(a/numpy.linalg.norm(a,1.0),2)
# [0.33,0.33,0.33]

如果您想保留 2 位小数并强制使用 1.0,只需修复它

normalized_a[0] += 1.0 - numpy.sum(normalized_a) # we could just as easily fix the -1 index ...

【讨论】:

  • 结果的总和应该等于1.0
  • 看起来不错。谢谢。
猜你喜欢
  • 2017-07-16
  • 1970-01-01
  • 2012-02-12
  • 2016-05-16
  • 2015-06-22
  • 1970-01-01
  • 2013-04-11
  • 2019-07-17
  • 2012-08-12
相关资源
最近更新 更多