Как нормализовать массив с округлением результата (python, numpy, scipy) - PullRequest
0 голосов
/ 17 января 2020

Далее не правильный код. Как сделать это правильно, коротко и красиво?

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

1 Ответ

2 голосов
/ 17 января 2020
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 ...
...