Sliding Window Algorithm Implementation Using Python3

Mon, May 21, 2018 2-minute read

The sliding window approach is a handy way to scan through a series of points and spot the ones that don’t belong. In this article we’ll work through an implementation in Python3, running it over a set of 5000 sample (x, y) points.

To keep things tidy, we start by defining a small class that simply holds a single point.

class Nokta:
	def __init__(self,x,y): #nokta sınıfı tanımladım
		self.x = x
self.y = y

With the container in place, we can load the data. We read the CSV file line by line, split each line on the comma (,), and turn those x and y values into a new Nokta object that gets appended to a list.

file = open("s5000.txt","r") #dışarıdan 5000 nokta için dosyayı açtım
threshold = 80             #threshold değerini seçtim
noktalar=[]                  #noktalar adında boş liste oluşturdum
for a in range (5000) :      #5000 satırı okumak için for döngüsü
    tmp = file.readline()
    x,y = tmp.split(",")    #her bir satırı virgül ile ayırıp x ve y değişkenine atadım
    x_int = int(x)
    y_int = int(y)
    tmp = Nokta(x_int,y_int)    #nokta nesnesi oluşturdum
noktalar.append(tmp) #bu nesneyi noktalar listesine ekledim

Now comes the actual detection. Using the Euclidean hypot equation to measure distance, we pick out the anomalies and collect them into a dictionary.

Once the sweep is complete, we write that dictionary out to a new .csv file and print how many anomalies turned up along the way.

All the code is accessible on GitHub.