首页 > 解决方案 > 在 Colab 和本地运行相同的代码会产生不同的结果。不涉及随机化或神经网络训练

问题描述

我的代码在本地终端和 Google Colab 上产生不同的结果。但是,如果我在 Colab 上运行相同的代码但使用终端命令(即!python test.py),它会产生与本地相同的结果。与 Stack Overflow 上的另一篇文章不同,这段代码没有随机化器或神经网络训练的东西,只是普通的旧函数。

项目的简短描述:我正在尝试为音乐生成编写深度学习代码。我将音符(从萨克斯独奏)更改为固定长度的列表,并将同一小节的音符放在更大的列表中。我最终得到了一个列表(分数)列表(度量,不同长度)列表(注释,固定长度)。要将其转换为张量,我必须使所有列表的长度相同,因此我决定在每个较短列表的末尾填充 [0, 0, 0, 0]。

在本地和 Colab 上使用终端命令,它会成功输出hihello填充零。但是在使用本机运行按钮的 Colab 上,它只打印hello和输出未填充的列表。

代码如下:

(data_transform.py)

from music21 import *

def mxl2list(mxlfile): #padded

    print('hi')
    parsed = converter.parse(mxlfile)
    myPiece = []

    measures = parsed[1] #measures[0] is an instrument, not a measure
    measures.pop(0)
    measures[-1].pop(-1)


    for m in measures: #for each measure
        myMeasure = []
        
        #Each note/rest has the following values, in order:
        #Pitch (integer, midi pitch constants, get with n.pitch.midi, 128 for rest)
        #Offset (float)
        #Duration (float, 0.0 for grace notes, get or set with n.quarterLength)
        #Tie (0 for no tie, 1 for tie start, 2 for tie stop, 3 for tie continue)

        for note in m:
            myNote = [0,0,0,0]

            try:
                if note.isRest or note.isNote:
                    pass
            except AttributeError:
                continue

            if note.isRest:
                myNote[0] = 128
            else:
                myNote[0] = note.pitch.midi
            
            myNote[1] = note.offset

            myNote[2] = note.quarterLength

            try:
                isTie = note.tie.type
                if isTie == "start":
                    myNote[3] = 1
                elif isTie == "stop":
                    myNote[3] = 2
                elif isTie == "continue":
                    myNote[3] = 3
            except AttributeError:
                myNote[3] = 0
            
            myMeasure.append(myNote)
        
        myPiece.append(myMeasure)

    #pad shorter length lists with zeros
    zeroList = [0, 0, 0, 0]
    listLen = []
    for measures in myPiece:
        listLen.append(len(measures))
    maxLen = max(listLen)
    for measures in myPiece:
        lenDiff = maxLen - len(measures)
        for i in range(lenDiff):
            measures.append(zeroList)

    return myPiece

(测试.py)

from data_transform import *

print('hello')
scoreList = mxl2list('musicxml/gs2.mxl')
print(scoreList)

标签: pythonlistgoogle-colaboratorymusic21

解决方案


推荐阅读