Created
January 6, 2022 16:30
-
-
Save theaspect/6ff613cf909e3fc2cd152cf452796ae4 to your computer and use it in GitHub Desktop.
segmentation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def to_buckets(lst, *buckets): | |
sums = [] | |
for i in buckets: | |
sums.append(sum(lst[:i])) | |
lst = lst[i:] | |
return sums | |
def std_dev(target, *values): | |
return math.sqrt(sum([(target-i)**2 for i in values])) | |
def recursive(freq, buckets, optimal, result, level, min_stdev, min_buckets): | |
# print(result, level) | |
# We don't iterate the last bucket, putting the rest of items | |
if(level>=buckets): | |
new_buckets = [*result, len(freq) - sum(result)] | |
#print(new_buckets) | |
b = to_buckets(freq, *new_buckets) | |
sd = std_dev(optimal, *b) | |
return (sd, new_buckets) | |
else: | |
s = sum(result) | |
for i in range(1,len(freq)+1): | |
if s + i < cnt: | |
(min_stdev2, min_buckets2) = recursive(freq, buckets, optimal, result+[i],level+1, min_stdev, min_buckets) | |
if min_stdev2 < min_stdev: | |
min_stdev = min_stdev2 | |
min_buckets = min_buckets2 | |
print(min_stdev, min_buckets) | |
return (min_stdev, min_buckets) | |
def segment(arr, cnt): | |
return recursive(arr, cnt, sum(arr)/cnt, [],1, 1, []) | |
freq = [ | |
0.0239, | |
0.044, | |
0.0953, | |
0.0183, | |
0.0551, | |
0.0096, | |
0.0024, | |
0.0283, | |
0.0766, | |
0, | |
0.0043, | |
0.0061, | |
0.0293, | |
0.0692, | |
0.0963, | |
0.1539, | |
0.0444, | |
0.0905, | |
0.0313, | |
0.0332, | |
0.0093, | |
0.0042, | |
0.0039, | |
0.0146, | |
0.0036, | |
0.0002, | |
0, | |
0, | |
0, | |
0.0094, | |
0.001, | |
0.0019 | |
] | |
print(segment(freq, 8)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment