我是 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()

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

另外,我想知道这个是否有简写,或者这是否已经是最短的代码行了..

python-3.x - 获取前 10 名和后 10 名特征-LMLPHP

最佳答案

试试这个:

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()

关于python-3.x - 获取前 10 名和后 10 名特征,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53020910/

10-10 20:03