获取前10名和后10名功能

时间:2018-10-27 10:22:04

标签: python-3.x numpy matplotlib scikit-learn jupyter-notebook

我是python的新手,试图学习如何从使用以下代码创建的列表中提取前10名和后10名:

clftest = logres1.fit(X_train,y_train)

#getting the feature's coefficient
feature_importance = clftest.coef_[0]

#creating an array to identify the highest and lowest value
sorter = np.argsort(feature_importance)

#using the shape of sorter, arrange it from lowest to highest
position = np.arange(sorter.shape[0])


featfig = plt.figure(figsize=(100,100))
featax = featfig.add_subplot(1, 1, 1)
featax.barh(position, feature_importance[sorter], align="center")
featax.set_yticks(position)
featax.set_yticklabels(np.array(X.columns)[sorter], fontsize=8)

plt.show()

如您所见,我的图形中涉及很多功能...

此外,我想知道这是否有一个简写形式,或者这已经是最短的代码行了。

Result of the code above

2 个答案:

答案 0 :(得分:1)

尝试一下:

clftest = logres1.fit(X_train,y_train)

#getting the feature's coefficient
feature_importance = clftest.coef_[0]

#creating an array to identify the highest and lowest value
sorter = np.argsort(feature_importance)

#add 2 rows in you code
n = 10 # this is number of features top
sorter = np.append(sorter[:n],sorter[-n:]) #this is fixed code

#using the shape of sorter, arrange it from lowest to highest
position = np.arange(sorter.shape[0])


featfig = plt.figure(figsize=(100,100))
featax = featfig.add_subplot(1, 1, 1)
featax.barh(position, feature_importance[sorter], align="center")
featax.set_yticks(position)
featax.set_yticklabels(np.array(X.columns)[sorter], fontsize=8)

plt.show()

答案 1 :(得分:1)

假设您具有具有特征权重的以下数组

coef =  array([  1.88300851e+00,   9.85092999e-02,  -5.65726689e-02,
                -6.15194157e-06,  -1.47064483e-01,  -3.80980229e-01,
                -5.74536851e-01,  -2.95280519e-01,  -2.40004639e-01,
                -3.51240376e-02,  -9.66881225e-03,   1.24471692e+00,
                 4.37321571e-02,  -9.20868564e-02,  -1.44701472e-02,
                -9.55498577e-03,  -4.33660677e-02,  -3.42427309e-02,
                -4.17388237e-02,   3.75241446e-03,   1.11771818e+00,
                -3.16367948e-01,  -9.05980063e-02,  -2.56441451e-02,
                -2.61484045e-01,  -1.22299461e+00,  -1.57351240e+00,
                -6.03878651e-01,  -7.25284179e-01,  -1.29895629e-01])

您可以按降序获得要素权重排序数组的索引:

sorter = np.argsort(-coef)
sorter
array([ 0, 11, 20,  1, 12, 19,  3, 15, 10, 14, 23, 17,  9, 18, 16,  2, 22,
       13, 29,  4,  8, 24,  7, 21,  5,  6, 27, 28, 25, 26])

然后您将获得以下十大功能:

top_ten_arg = sorter[:10]
coef[top_ten_arg]
array([  1.88300851e+00,   1.24471692e+00,   1.11771818e+00,
         9.85092999e-02,   4.37321571e-02,   3.75241446e-03,
        -6.15194157e-06,  -9.55498577e-03,  -9.66881225e-03,
        -1.44701472e-02])

并类似地获得最低的10个功能:

lowest_ten_arg = sorter[-10:]
coef[lowest_ten_arg]
array([-0.24000464, -0.26148405, -0.29528052, -0.31636795, -0.38098023,
       -0.57453685, -0.60387865, -0.72528418, -1.22299461, -1.5735124 ])

请注意,这仅使您获得要素权重,就像在排序器上一样,只需使用top_ten_arg上的lowest_ten_argX.columns即可获得要素名称