![](/img/trans.png)
[英]Printing out Features used in Feature Selection with XGBoost Feature Importance Scores
[英]Explainantion of a function used in class for feature selection
我遇到了一個 function 如下:
def indices_of_top_k(arr, k):
return np.sort(np.argpartition(np.array(arr), -k)[-k:])
我無法理解它的作用或每個組件的工作原理。 有人可以解釋一下它的作用嗎?
對於上下文,它在下面給出的 class 中用於特征選擇:
class TopFeatureSelector(BaseEstimator, TransformerMixin):
def __init__(self, feature_importances, k):
self.feature_importances = feature_importances
self.k = k
def fit(self, X, y=None):
self.feature_indices_ = indices_of_top_k(self.feature_importances, self.k)
return self
def transform(self, X):
return X[:, self.feature_indices_]
謝謝,
partition
比排序更難理解。 將其視為不完整的排序。
In [152]: x=np.random.randint(0,50,12)
In [153]: x
Out[153]: array([16, 16, 4, 33, 39, 43, 28, 47, 2, 23, 25, 11])
要獲得最大的 5 個元素,我們可以排序和切片:
In [154]: np.sort(x)[-5:]
Out[154]: array([28, 33, 39, 43, 47])
partition
獲得相同的值,但順序有點不同:
In [155]: np.partition(x,-5)[-5:]
Out[155]: array([28, 33, 39, 47, 43])
對應的指標:
In [156]: np.argpartition(x,-5)[-5:]
Out[156]: array([6, 3, 4, 7, 5])
對這些索引進行排序:
In [157]: np.sort(np.argpartition(x,-5)[-5:])
Out[157]: array([3, 4, 5, 6, 7])
使用 argsort 做同樣的事情,但據說argpartition
比argsort
快:
In [158]: np.sort(np.argsort(x)[-5:])
Out[158]: array([3, 4, 5, 6, 7])
從這里我們可以得到 5 個最大值,但是按照它們的原始順序,而不是 [154] 中的排序順序:
In [159]: x[_]
Out[159]: array([33, 39, 43, 28, 47])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.