You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.8 KiB

7 years ago
import numpy as np
import pickle
from scipy.signal import argrelextrema
7 years ago
def is_intersect(target_segment, segments):
for segment in segments:
start = max(segment['start'], target_segment[0])
finish = min(segment['finish'], target_segment[1])
if start <= finish:
return True
return False
def exponential_smoothing(series, alpha):
result = [series[0]]
for n in range(1, len(series)):
result.append(alpha * series[n] + (1 - alpha) * result[n-1])
7 years ago
return result
class StepDetector:
def __init__(self, pattern):
self.pattern = pattern
7 years ago
self.segments = []
self.confidence = 1.5
def fit(self, dataframe, segments):
data = dataframe['value']
confidences = []
for segment in segments:
if segment['labeled']:
segment_data = data[segment['start'] : segment['finish'] + 1]
segment_min = min(segment_data)
segment_max = max(segment_data)
confidences.append(0.24 * (segment_max - segment_min))
if len(confidences) > 0:
self.confidence = min(confidences)
else:
self.confidence = 1.5
7 years ago
def predict(self, dataframe):
data = dataframe['value']
7 years ago
result = self.__predict(data)
7 years ago
result.sort()
if len(self.segments) > 0:
result = [segment for segment in result if not is_intersect(segment, self.segments)]
return result
def __predict(self, data):
7 years ago
window_size = 24
all_max_flatten_data = data.rolling(window=window_size).mean()
all_mins = argrelextrema(np.array(all_max_flatten_data), np.less)[0]
extrema_list = []
7 years ago
for i in exponential_smoothing(data - self.confidence, 0.03):
extrema_list.append(i)
7 years ago
segments = []
for i in all_mins:
if all_max_flatten_data[i] < extrema_list[i]:
7 years ago
segments.append(i - window_size)
7 years ago
7 years ago
return [(x - 1, x + 1) for x in self.__filter_prediction(segments, all_max_flatten_data)]
def __filter_prediction(self, segments, all_max_flatten_data):
delete_list = []
7 years ago
for i in segments:
new_data = all_max_flatten_data[i-50:i+250]
min_value = 100
for val in new_data:
if val < min_value:
min_value = val
if all_max_flatten_data[i] > min_value:
delete_list.append(i)
7 years ago
for item in delete_list:
segments.remove(item)
return segments
7 years ago
def save(self, model_filename):
with open(model_filename, 'wb') as file:
pickle.dump((self.confidence), file)
7 years ago
def load(self, model_filename):
try:
with open(model_filename, 'rb') as file:
self.confidence = pickle.load(file)
7 years ago
except:
pass