Created
February 25, 2016 21:09
-
-
Save stormxuwz/2afa161277709e1c6ad5 to your computer and use it in GitHub Desktop.
time series segmentation
This file contains 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 numpy as np | |
def slidingWindow(x,max_error): | |
n=len(x) | |
leftNode=0 | |
segmentList=[] | |
print n | |
while leftNode<n-1: | |
print leftNode | |
newSeg = False | |
for rightNode in range(leftNode+3,n): | |
testSeg=x[leftNode:rightNode] | |
testLine = createLine(testSeg,"regression") | |
segError = calculate_error(testSeg, testLine) | |
if segError>max_error: | |
segmentList.append([testLine,range(leftNode,rightNode)]) | |
leftNode=rightNode | |
newSeg = True | |
break | |
if newSeg is False: | |
segmentList.append([testLine,range(leftNode,rightNode)]) | |
leftNode = n-1 | |
return segmentList | |
def calculate_error(x,y): | |
return np.max(np.abs(x-y)) | |
def createLine(x,method="simple"): | |
n=len(x) | |
if method=="simple": | |
# Using two node as line | |
line = np.linspace(x[0],x[-1],n) | |
pass | |
elif method == "regression": | |
# Using other node | |
slope, intercept, r_value, p_value, std_err = ss.linregress(range(n),x) | |
line = intercept+slope*np.arange(n) | |
elif method == "poly": | |
line=np.poly1d(np.polyfit(range(n),x,2))(range(n)) | |
return(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment