0
我有一個0s和1s的稀疏矩陣,它是訓練數據= numpy二維數組。基於它們的頻率的排名特徵
我想只保留頂部K個特徵來描述我的數據。
我想根據它們的頻率來計算頂級K特徵,即它們在矩陣中的訓練樣本中出現的頻率。
但是,我沒有這些功能的確切名稱。他們只是列。
我該如何計算他們的頻率,最重要的是,我該如何選擇矩陣中的頂級K特徵並刪除其他特徵?
我有一個0s和1s的稀疏矩陣,它是訓練數據= numpy二維數組。基於它們的頻率的排名特徵
我想只保留頂部K個特徵來描述我的數據。
我想根據它們的頻率來計算頂級K特徵,即它們在矩陣中的訓練樣本中出現的頻率。
但是,我沒有這些功能的確切名稱。他們只是列。
我該如何計算他們的頻率,最重要的是,我該如何選擇矩陣中的頂級K特徵並刪除其他特徵?
SciPy的稀疏矩陣可以 - 到他們討厭的傾向返回matrix
不array
對象 - 在許多方面就像arrays
使用,所以要提取特徵頻率並找到頂級的,比方說,4:
>>> features_present_in_sample = [[1,5], [0,3,7], [1,2], [0,4,6], [2,6]]
>>> features_per_sample=[len(s) for s in features_present_in_sample]
>>> features_flat = np.r_[tuple(features_present_in_sample)]
>>> boundaries = np.r_[0, np.add.accumulate(features_per_sample)]
>>> nsaamples = len(features_present_in_sample)
>>> nfeatures = np.max(features_flat) + 1
>>> data = sparse.csr_matrix((np.ones_like(features_flat), features_flat, boundaries), (nsaamples, nfeatures))
>>>
>>> data
<5x8 sparse matrix of type '<class 'numpy.int64'>'
with 12 stored elements in Compressed Sparse Row format>
>>> data.todense()
matrix([[0, 1, 0, 0, 0, 1, 0, 0],
[1, 0, 0, 1, 0, 0, 0, 1],
[0, 1, 1, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0]])
>>> frequencies = data.mean(axis=0)
>>> frequencies
matrix([[ 0.4, 0.4, 0.4, 0.2, 0.2, 0.2, 0.4, 0.2]])
>>> top4 = np.argpartition(-frequencies.A.ravel(), 4)[:4]
>>> top4
array([6, 0, 2, 1])
刪除他人:
>>> one_hot_top4 = np.zeros((nfeatures, 4), dtype=int)
>>> one_hot_top4[top4, np.arange(4)] = 1
>>> data @ one_hot_top4
array([[0, 0, 0, 1],
[0, 1, 0, 0],
[0, 0, 1, 1],
[1, 1, 0, 0],
[1, 0, 1, 0]], dtype=int64)
或(更好):
>>> one_hot_top4_sparse = sparse.csc_matrix((np.ones((4,), dtype=int), top4, np.arange(4+1)), (nfeatures, 4))
>>> data @ one_hot_top4_sparse
<5x4 sparse matrix of type '<class 'numpy.int64'>'
with 8 stored elements in Compressed Sparse Row format>
>>> (data @ one_hot_top4_sparse).todense()
matrix([[0, 0, 0, 1],
[0, 1, 0, 0],
[0, 0, 1, 1],
[1, 1, 0, 0],
[1, 0, 1, 0]], dtype=int64)
每個數據樣本中必須包含每個特徵。這就是你如何將它提供給scikit。你的意思是什麼特徵的頻率。 –