2015-11-02 89 views
0

对于任务,我必须使用属于某些数据的功能的不同组合来评估分类系统。通过特征我的意思是测量,例如身高,体重,年龄,收入。因此,举个例子,我想看看分类器在给定高度和重量的情况下的表现如何,然后根据身高和年龄表示。我不仅希望能够测试哪两种功能最好地协同工作,而且还希望将3个功能最好地结合在一起,并且希望能够将其推广到n功能。使用Python的功能组合NumPy

我一直在尝试使用numpy的mgrid,创建n维数组,将它们展平,然后创建使用每个数组中相同元素创建新数组的数组。棘手的所以这里解释一下是一些代码和伪代码:

import numpy as np 

def test_feature_combos(data, combinations): 
    dimensions = combinations.shape[0] 
    grid = np.empty(dimensions) 
    for i in xrange(dimensions): 
     grid[i] = combinations[i].flatten() 
    #The above code throws an error "setting an array element with a sequence" error which I understand, but this shows my approach. 

    **Pseudo code begin** 
    For each element of each element of this new array, 
    create a new array like so: 
    [[1,1,2,2],[1,2,1,2]] ---> [[1,1],[1,2],[2,1],[2,2]] 
    Call this new array combo_indices 
    Then choose the columns (features) from the data in a loop using: 
    new_data = data[:, combo_indices[j]] 

combinations = np.mgrid[1:5,1:5] 
test_feature_combos(data, combinations) 

我承认,这种做法意味着很多是由于重复不必要的组合,但我甚至无法实现这个乞丐所以不能挑肥拣瘦。

请有人建议我如何能a)实现我的方法或b)以更加优雅的方式实现这一目标。

在此先感谢,并告知我是否需要澄清,这很难解释。

+0

你能否提供一些样本'数据'和'组合'供人们玩耍? – jkalden

回答

1

为了产生从一组尺寸的无需更换绘制Ñ可以使用itertools.combinationsķ元素的所有组合,例如:

idx = np.vstack(itertools.combinations(range(n), k)) # an (n, k) array of indices 

对于特殊情况,其中k = 2时它往往更快地使用nxn矩阵的上三角的索引,例如:

idx = np.vstack(np.triu_indices(n, 1)).T 
+0

令人惊叹,谢谢! – quantum285