python - 来自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)
我怎样才能做到这一点?谢谢!!
解决方案
创建一个新pd.Series
的索引,使用来自列表MultiLevel
的有序对创建索引,然后使用with将系列重塑为一个旋转的数据农场,可选的值。:bigrams
prob
Series.unstack
fill_value=0
round
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
推荐阅读
- c++ - 如何理解 AddSprite 函数中的 Sprite 坐标?
- javascript - Javascript 将值输入文本框而不是 Python 中的 sendKeys()
- angular - Angular Test:从父组件访问子组件的元素
- sql - SQLite3中特定表的最后插入的rowid
- python-3.x - 始终在 Ubuntu 中使用 Python virtualenv
- java - 重新启动 EXAM 工具会引发 Eclipse 错误
- reactjs - 如何从状态/道具中获取复选框值?
- node.js - 如何链接 2 个 docker 容器,一个与后端代码,另一个与 react 都在 node.js 上
- mysql - 如何使用 Count 一列并由每个 id 分隔
- java - 在 SPARK 中的两个集群之间同步 HBase 表