首次使用pickle.Dump / pickle.load



我正在使用一个函数,在它结束时,它在pickle文件中转储数据,我稍后调用我的函数,它工作得很好。而不是调用函数,我想使用我创建的数据。我试过用泡菜。加载,但似乎不工作。

函数:

def get_notes():
""" Get all the notes and chords from the midi files in the directory """
notes = []
for file in midi_files:
midi = converter.parse(file)
print("Parsing %s" % file)
notes_to_parse = None
try:  # file has instrument parts
s2 = instrument.partitionByInstrument(midi)
notes_to_parse = s2.parts[0].recurse()
except:  # file has notes in a flat structure
notes_to_parse = midi.flat.notes
for element in notes_to_parse:
if isinstance(element, note.Note):
notes.append(str(element.pitch))
elif isinstance(element, chord.Chord):
notes.append('.'.join(str(n) for n in element.normalOrder))
with open('/content/gdrive/MyDrive/notes', 'wb') as filepath:
pickle.dump(notes, filepath)
return notes

第二个函数通常是这样的:

def train_network():
""" Train a Neural Network to generate music """
notes = get_notes()
# get amount of pitch names
n_vocab = len(set(notes))
network_input, network_output = prepare_sequences(notes, n_vocab)
model = create_network(network_input, n_vocab)
train(model, network_input, network_output)

但是我不想每次训练时都重新解析文件,我需要这样的东西:

def train_network():
""" Train a Neural Network to generate music """
notes = pikle.load('/content/gdrive/MyDrive/notes')
# get amount of pitch names
n_vocab = len(set(notes))
network_input, network_output = prepare_sequences(notes, n_vocab)
model = create_network(network_input, n_vocab)
train(model, network_input, network_output)

正如@MarkTolonen所提到的,pickle.load不接受文件路径,而是从打开的文件中获取对象。试试这个:

with open('/content/gdrive/MyDrive/notes', mode) as f:
notes = pickle.load(f)

你可以在这里和这里找到更多。

最新更新