2016-11-08 51 views
1

我正在尝试创建一个决策树分类器函数,该函数将构建决策树集合并根据来自所有树的多数投票预测进行最终预测。我的方法是建立一个矩阵,将每个决策树的预测结果放在一个单独的列中,然后对每一行(对应于每个数据点),找到模态值以对该数据点进行最终预测。迭代通过numpy数组的行来查找模式

到目前为止,我的作用是:

def majority_classify(x_train, y_train, x_test, y_test, num_samples): 

n = x_train.shape[0] 
c=len(np.unique(y_train)) 

votes=np.zeros((n, c)) 
predictions_train=np.empty((n, num_samples+1)) 
predictions_test=np.empty((n, num_samples)) 


for i in range(0, num_samples): 
    # Randomly a sample points from the train set of size 'n' 
    indices = np.random.choice(np.arange(0, n), size=n) 

    x_train_sample = x_train[indices, :] 
    y_train_sample = y_train[indices] 

    dt_major = tree.DecisionTreeClassifier(max_depth = 2) 
    model_major = dt_major.fit(x_train, y_train) 

    predictions_train[:,i]=model_major.predict(x_train) 




for r in predictions_train: 
    predict_train = mode(r)[0][0] 

但是,我在同是确定如何通过每一行迭代,并找到模式什么麻烦。有什么建议么?

谢谢!

+0

[文档](https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html)是好的地方开始。你应该在你的问题中包含一个**最小的**输入例子和期望的结果。 – wwii

+1

我想遍历每行作为一个单元,而不是遍历每行内的项目。我不认为我在该文档中看到如何做到这一点。 – yogz123

+0

https://docs.scipy.org/doc/numpy/user/quickstart.html#indexing-slicing-and-iterating – wwii

回答

1
  • 使用np.uniquereturn_counts参数。
  • 使用counts数组上的argmax可以从唯一数组中获取值。
  • 一个自定义功能使用np.apply_along_axismode

def mode(a): 
    u, c = np.unique(a, return_counts=True) 
    return u[c.argmax()] 

a = np.array([ 
     [1, 2, 3], 
     [2, 3, 4], 
     [3, 4, 5], 
     [2, 5, 6], 
     [4, 1, 7], 
     [5, 4, 8], 
     [6, 6, 3] 
    ]) 

np.apply_along_axis(mode, 0, a) 

array([2, 4, 3]) 
0

退房scipy.stats.mode

import numpy as np 
from scipy.stats import mode 

>>> a = np.array([[1,1,0],[1,2,2],[2,0,0]]) 
>>> mode(a, axis=1)[0] 
array([[1], 
     [2], 
     [0]])