python - 我正在尝试减少数据集的列数
问题描述
我试图用 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)
解决方案
对不起,如果我误解了你的问题,但我仍然很困惑。您正在将模型拟合到初始 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()
,它似乎不适合这个问题,因为我从我非常简短的阅读中得到的印象是它用于减少稀疏矩阵。如果我第二次误读你的问题,我再次道歉。
推荐阅读
- sql - 在 Spark SQL 中使用 XPATH 处理 XML
- python - Python封闭范围:在调用点还是在定义?
- git - 如何在 azure devops 中创建分支策略(或类似策略),这会在自定义条件下强制额外的审阅者
- php - 如何以多页重力形式将字段添加到特定页面?
- sql-server - 将并行阈值从 5 增加到 20 会导致糟糕的查询性能
- regex - 正则表达式模式允许忽略大小写的字母
- java - 在 ooxml-schemas-1.4.jar 和 poishadow-all.jar 中使用 Apache poi 重复错误时
- ffmpeg - 同时修剪视频和提取缩略图
- excel - 用值分隔单元格并将相关列移动到新行
- vue.js - VueJS 多次切换以打开/隐藏元素