首页 > 解决方案 > 来自bigram的矩阵?

问题描述

我有一个和弦列表

['F', 'Em7', 'A7', 'Dm', 'Dm7', 'A#', 'C7', 'C', 'G7', 'A7sus4', 'Gm6', 'Fsus4', etc]

我想把它变成一个转换矩阵。到目前为止我所拥有的:

import pandas as pd
from nltk.util import ngrams

bigram = pd.Series(ngrams(data.split(),2)) ### creating the bigrams of ordered pairs like:
### 0      (F, Em7) 
### 1     (Em7, A7) 
### 2      (A7, Dm)

probabilities = bigram.value_counts(normalize=True) ### getting probability of each ordered pair
letters = pd.Series(data.split()).unique() ### getting each chord 

我希望矩阵像:

          F        Em7      A7          ....
 F     p(FF)    p(FEm7)    p(FA7)       ....
 Em7   p(Em7F)  p(Em7Em7)  p(Em7A7)     ....
 A7    p(A7F)    p(A7Em7)  p(A7A7)      ....
  .
  .
  .

我的概率列表中p(FF)的概率在哪里。(F, F)我怎样才能做到这一点?谢谢!!

标签: pythonpandasnltkprobability

解决方案


创建一个新pd.Series的索引,使用来自列表MultiLevel的有序对创建索引,然后使用with将系列重塑为一个旋转的数据农场,可选的值。:bigramsprobSeries.unstackfill_value=0round

prob = bigram.value_counts(normalize=True)

mat = (
    pd.Series(
        prob, index=[prob.index.str[0], prob.index.str[1]])
    .unstack(fill_value=0).round(3)
)

结果:

print(mat)

           A#     A7  A7sus4      C     C7     Dm    Dm7    Em7  Fsus4     G7    Gm6
A#      0.000  0.000   0.000  0.000  0.091  0.000  0.000  0.000  0.000  0.000  0.000
A7      0.000  0.000   0.000  0.000  0.000  0.091  0.000  0.000  0.000  0.000  0.000
A7sus4  0.000  0.000   0.000  0.000  0.000  0.000  0.000  0.000  0.000  0.000  0.091
C       0.000  0.000   0.000  0.000  0.000  0.000  0.000  0.000  0.000  0.091  0.000
C7      0.000  0.000   0.000  0.091  0.000  0.000  0.000  0.000  0.000  0.000  0.000
Dm      0.000  0.000   0.000  0.000  0.000  0.000  0.091  0.000  0.000  0.000  0.000
Dm7     0.091  0.000   0.000  0.000  0.000  0.000  0.000  0.000  0.000  0.000  0.000
Em7     0.000  0.091   0.000  0.000  0.000  0.000  0.000  0.000  0.000  0.000  0.000
F       0.000  0.000   0.000  0.000  0.000  0.000  0.000  0.091  0.000  0.000  0.000
G7      0.000  0.000   0.091  0.000  0.000  0.000  0.000  0.000  0.000  0.000  0.000
Gm6     0.000  0.000   0.000  0.000  0.000  0.000  0.000  0.000  0.091  0.000  0.000

推荐阅读