2015-05-08 79 views
0

我有一個問題/想法,我不知道該怎麼做。定義數據點周圍的橢圓

我有X的散點圖與Ÿ

scatter plot example

我可以繪製一個矩形,然後在內部挑選的所有點。

理想我想定義一個橢圓形,因爲它更好地捕捉形狀並排除其外部的所有點。

這是怎麼回事?它甚至有可能嗎?我使用matplotlib繪製了該圖。

我用線性迴歸(LR)來適應點,但那不是真的我在找什麼。 我想定義一個橢圓來覆蓋儘可能多的點,然後排除它之外的點。我怎樣才能定義一個方程/代碼來挑選裏面的?

+0

什麼是您點的形狀方程?我不明白你是如何使用線性迴歸來繪製矩形的? – RafaelC

+0

可以在這裏查看可拖動的矩形演示:http://matplotlib.org/1.4.0/users/event_handling.html#draggable-rectangle-exercise – reptilicus

+0

嗯,我不知道它有多難實現,但有些「數據挖掘」算法將涵蓋您的需求。看看'k-means'算法或'GMM'(高斯模型)。 – RafaelC

回答

0

如果您具有圖中所示的數據結構,您可以使用函數和列表理解來完成此操作。

如果你有這樣的列表中的數據:

# Made up data 
lst = [ 
    # First element is X, second is Y. 
    (0,0), 
    (92,20), 
    (10,0), 
    (13,40), 
    (27,31), 
    (.5,.5), 
] 

def shape_bounds(x): 
    """ 
    Function that returns lower and upper bounds for y based on x 

    Using a circle as an example here. 
    """ 
    r = 4 
    # A circle is x**2 + y**2 = r**2, r = radius 
    if -r <= x <= r: 
     y = sqrt(r**2-x**2) 
     return -y, y 
    else: 
     return 1, -1 # Remember, returns lower, upper. 
     # This will fail any lower < x < upper test.   

def in_shape(elt): 
    """ 
    Unpacks a pair and tests if y is inside the shape bounds given by x 
    """ 
    x, y = elt 
    lower_bound, upper_bound = shape_bounds(x) 
    if lower_bound < y < upper_bound: 
     return True 
    else: 
     return False 

# Demo walkthrough 
for elt in lst: 
    x, y = elt 
    print x, y 
    lower_bound, upper_bound = shape_bounds(x) 
    if lower_bound < y < upper_bound: 
     print "X: {0}, Y: {1} is in the circle".format(x, y) 

# New list of only points inside the shape 
new_lst = [x for x in lst if in_shape(x)] 

至於橢圓,請嘗試更改基於this