更新:我发现了问题
gram = notesNumbers[i:(i+1)];
当我打印gram
时,它将打印为只有1个值的数组。例如,它将打印[55]
。稍后在我的代码中引用gram,但是它使用整个数组而不是其中的一个值。要使其正常运行,我必须做gram[0]
,但是更简单的方法是将上面的代码重写为:
gram = notesNumbers[i]
现在,当我打印gram
时,它的值是ex)55
在我的代码中
我了解人们也遇到过类似的问题,但是就我而言,我该如何解决!
我正在尝试根据马尔可夫链进行一些预测。
我有一个非常简单的程序。我已使用库Mido来获取音乐笔记。我已经对其进行了解析,并将所有注释放在名为notesNumbers
notesNumbers
数组输出如下所示
[55,62,67,74,55,62,67,74,55,62,67,74,55,62,67,74,55,62,67,74,55,62,67, 74,55,62,67,74,55,48,52,55,59,67,71,67,71,67,71,59,67,71]
然后,我创建了一个名为ngrams
的新的空字典,我为markovchain设置了一个起点,该起点由变量currentGram
标注为88
我接下来要做的是创建markov过渡“矩阵”。我使用字典创建带有数字的键,然后为该值创建一个数组,该数组包含在给定notesNumber
如果我打印ngrams
,应该会看到类似以下内容(示例):
{'88':['45','55','67','45','45','33','77','90'],'32':['44','76 ','77'}
但是,当尝试通过迭代添加到字典中时,出现错误TypeError: unhashable type: 'list' python
在包含
的行中出现错误if not gram in ngrams:
代码如下:
from midiutil.MidiFile import MIDIFile
import random
import mido
from mido import MidiFile
from mido import MidiTrack
#ignore midi stuff
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
notesNumbers = []
#notesNumbers = notesNumbers2
ngrams= {}
#Parsing message to get the notes to be played
for msg in MidiFile('song.mid'):
if (not msg.is_meta):
if (msg.type == 'note_on'):
notesNumbers.append(msg.note)
#print(notesNumbers)
#starting number I picked
currentGram = 88
#print notesNumbers
#myOtherString = "".join(str(elm) for elm in notesNumbers)
#print notesNumbers2
#currentGram = random.choice(myOtherString)
ngrams= {}
#print currentGram
print(len(notesNumbers))
#creating markov transition matrix without directly doing probabilty
#Creating a dictionary, getting each number and the frequency of the following number
for i in range(len(notesNumbers)):
print("about to iterate")
gram = notesNumbers[i:(i+1)];
print(gram)
print("finish iterate")
lessthan = len(notesNumbers) - 1
if not gram in ngrams:
ngrams[gram] = []
else:
if (i < lessthan):
nextgram = notesNumbers[i+1]
ngrams[gram].append(nextgram)
print(ngrams)
result = []
result.append(currentGram)
#getting next state
for i in range(len(notesNumbers)):
possibilites = ngrams[currentGram]
#print possibilites
nextChoice = random.choice(possibilites)
#print nextChoice
result.append(nextChoice)
currentGram = nextChoice
print("Restult")
print result