首页 > 解决方案 > 我正在尝试减少数据集的列数

问题描述

我试图用 shape(20000,8000) 减少向量 X 的列数,但是减少了数据集的行数,使其成为新的数据集 X_5000 ,它的形状是 (5000 , 8000) 。请让我知道我在哪里犯了错误。当前我有 - X - 形状向量 (20000,8000) 必需 - X_5000 - 形状向量 (5000 , 8000) 我正在使用决策树模型并使用 feature_importance 来减少数量。的特征。

clf = DecisionTreeClassifier()

clf.fit(X, y)

class_prob_sorted = (-clf.feature_importances_).argsort()              

top_5000_index= class_prob_sorted[:5000]    


X_5000=X.tocsr()[top_5000_index]

实际上我得到了 - print(X_5000.shape) - (5000 , 8000)

预期 - print(X_5000.shape) - (20000 , 5000)

标签: pythondata-sciencesize-reduction

解决方案


对不起,如果我误解了你的问题,但我仍然很困惑。您正在将模型拟合到初始 X,使用最重要的特征clf.feature_importances_(这是一维数组,因此出现错误消息),然后尝试将 X 减少到仅这些特征?如果是这样:

clf.fit(X, y)

#map indices of columns to most important features - argsort loses order
important = clf.important_features_
important_dict = dict( zip( [i for i in range( len( important ))], important ))

#sort the dict in reverse order to get list of indices of the most important columns
top_5000_index = sorted( important_dict, key=important_dict.get, reverse=True )[0:5000]

#add the rows to a new X 
reduced_X = []
reduced_y = []
for i in top_5000_index:
    reduced_X.append( X[:,i] )
    reduced_y.append( y[i] ) #if you need the labels for later

reduced_X = np.array( reduced_X )
reduced_y = np.array( reduced_y )

那么唯一的问题仍然是为什么有 5000 个特征?也许您应该设置一个重要性阈值并抓住高于此阈值的特征。

至于X.tocsr(),它似乎不适合这个问题,因为我从我非常简短的阅读中得到的印象是它用于减少稀疏矩阵。如果我第二次误读你的问题,我再次道歉。


推荐阅读