python - 如何通过舍入结果来规范化数组(python、numpy、scipy)
问题描述
进一步不是正确的代码。如何让它正确、简短、美观?
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
解决方案
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 ...
推荐阅读
- node.js - cannot upload csv file on nodejs server
- python - 我已经设法在我的 Debian 系统上做了一些事情,而 Python-Cryptography 不允许我安装或删除任何东西
- java - 在java中动态添加类对象到ArrayList
- ruby-on-rails - 带有全局安装 gem 的 rails rake 任务
- python-3.x - 当脚本显示有货时,如何让脚本发送一个通知?
- swift - 初始化泛型类型的占位符空变量
- gcc - ARM 处理器的 GNU 工具链是否提供对 ARM11 等经典处理器的支持?
- c# - 如何从进程名称中获取进程 ID?(C#)
- java - Android:为什么按下按钮时我的活动没有出现?
- reactjs - Console.log 在 React.js 的构造函数和渲染函数中打印两次值