【问题标题】:BOW not considered all elementsBOW 未考虑所有元素
【发布时间】:2022-01-18 03:59:41
【问题描述】:

我正在研究应用 BOW 方法为表示的和弦生成向量的可能性。但是,当我使用这种方法时,我可以生成向量,但并不是所有的和弦都被考虑在内。

这里是详细的代码:

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
# DF
    music   chords
0   1.wav   N, A7, Am7, Am7b5/G, A7, N
1   2.wav   N, Em, C, D, Em, C, D, N
2   3.wav   N, E, A, E, B, A, D6, E, N
#BOW
bow = CountVectorizer(max_features=1000, ngram_range=(1,1))
train_bow = bow.fit_transform(df['chords'])
pd.DataFrame(bow.transform(df['chords']).toarray(), columns=sorted(bow.vocabulary_.keys()))

#Result
    a7  am7 am7b5   d6  em
0   2   1   1      0     0
1   0   0   0      0     2
2   0   0   0      1     0

例如,请参阅不计算 C、D 和 A 等和弦。有谁明白我可能错了什么?

【问题讨论】:

  • 可能 CountVectorizer 的默认标记器不是最适合您的字符串的。也许您应该编写一个自定义并通过 tokenizer 参数传递它

标签: python scikit-learn nlp


【解决方案1】:

我不知道 sklearn 的默认分词器是如何工作的,但它不适合您的输入。

tokenizer = lambda x: x.replace(" ", "").split(",")
bow = CountVectorizer(max_features=1000, tokenizer = tokenizer, ngram_range=(1,1))
train_bow = bow.fit_transform(df['chords'])
pd.DataFrame(bow.transform(df['chords']).toarray(), columns=sorted(bow.vocabulary_.keys()))

打印输出:

>>> bow.vocabulary_.keys()
dict_keys(['n', 'a7', 'am7', 'am7b5/g', 'em', 'c', 'd', 'e', 'a', 'b', 'd6'])

【讨论】:

  • 一个小问题:为什么N会出现两次?
  • 有些空格没有去掉,我检查一下
  • 现在应该可以工作了
【解决方案2】:

我编写了一种方法来手动创建词汇表,另一种方法用于标记。

输出如下:

>>>
   b  d  am7  c  em  n  a  e  a7  am7b5/g  d6
0  0  0    1  0   0  2  0  0   2        1   0
1  0  2    0  2   2  2  0  0   0        0   0
2  1  0    0  0   0  2  2  3   0        0   1

代码如下:

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer

def voc(chord):
    items = []
    for item in chord:
        items += item.split(', ')
        items = [el.lower() for el in items]
    vocabulary = list(set(items))
    return vocabulary

def tokenizer(item):
    items = []
    items = item.split(', ')
    items = [el.lower() for el in items]
    return items

df = pd.read_excel("df.xlsx") #I created a df for test purpose, replace with yours


chord = list(df['chords'].values)

vocabulary = voc(chord)
#BOW
bow = CountVectorizer(vocabulary = vocabulary, tokenizer = tokenizer, max_features=1000, ngram_range=(1,1))
train_bow = bow.fit_transform(df['chords'])
bow = pd.DataFrame(bow.transform(df['chords']).toarray(),columns=bow.vocabulary_.keys())

如果您需要,请告诉我!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多