簡體   English   中英

計算給定年份的漢明距離

[英]Calculating hamming distance in a given year

我有以下 dataframe:

Bacteria   Year      Feature_Vector
XYRT23     1968      [0 1 0 0 1 1 0 0 0 0 1 1]
XXQY12     1968      [0 1 0 0 0 1 1 0 0 0 1 1]
RTy11R     1968      [1 0 0 0 0 1 1 0 1 1 1 1]
XYRT23     1969      [0 1 0 0 1 1 0 0 0 0 1 1]
XXQY12     1969      [0 0 1 0 0 1 1 0 0 0 1 1]
RTy11R     1969      [1 0 0 0 0 1 1 1 1 1 1 1]

我想計算給定年份每一對的成對漢明距離,並將其保存到新的 dataframe 中。 示例:(注:漢明距離的數字是我自己編的,實際上並不需要 Pair 列)

Pair               Year       HammingDistance
XYRT23 - XXQY12    1968       0.24
XYRT23 - RTy11R    1968       0.33
XXQY12 - RTy11R    1968       0.29
XYRT23 - XXQY12    1969       0.22
XYRT23 - RTy11R    1969       0.34
XXQY12 - RTy11R    1969       0.28

我試過類似的東西:

import itertools
from sklearn.metrics.pairwise import pairwise_distances
my_list = df.groupby('Year')['Feature_Vector'].apply(list)

total_list = []
for lists in my_list:
    i = 0
    results = []
    for x in itertools.combinations(lists, 2):
        vec1, vec2 = np.array(x[0]), np.array(x[1])
        keepers = np.where(np.logical_not((np.vstack((vec1, vec2)) == 0).all(axis=0)))
        vecx = vec1[keepers].reshape(1, -1) 
        vecy = vec2[keepers].reshape(1, -1)
        try:
            score = pairwise_distances(vecx, vecy, metric = "hamming")
            print(score)
        except:
            score = 0
        results.append(score) 

function pairwise_distances可以接受一個矩陣,因此將一年中的特征作為一個矩陣提供可能更容易,返回一個成對的距離矩陣,只是我們需要的比較的子集。 例如,像您這樣的數據集:

df = pd.DataFrame({'Bacteria':['XYRT23','XXQY12','RTy11R']*2,
'Year':np.repeat(['1968','1969'],3),
'Feature_Vector':list(np.random.binomial(1,0.5,(6,12)))})

type(df['Feature_Vector'][0])
numpy.ndarray

定義成對的 function 接受特征列和行名稱:

def pwdist(features , names):
    dm = pairwise_distances(features.to_list(),metric="hamming")
    m,n = dm.shape
    dm[:] = np.where(np.arange(m)[:,None] >= np.arange(n),np.nan,dm)
    dm = pd.DataFrame(dm,index = names,columns = names)
    out = dm.stack().reset_index()
    out.columns = ['Bacteria1','Bacteria2','distance']
    return out

使用 groupby 並應用 function:

df.groupby('Year').apply(lambda x: pwdist(x.Feature_Vector,x.Bacteria.values))

給我們這樣的東西:

       Bacteria1 Bacteria2  distance
Year                                
1968 0    XYRT23    XXQY12  0.333333
     1    XYRT23    RTy11R  0.250000
     2    XXQY12    RTy11R  0.416667
1969 0    XYRT23    XXQY12  0.500000
     1    XYRT23    RTy11R  0.333333
     2    XXQY12    RTy11R  0.166667
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM