Keras misinterprets training data shape

后端 未结 1 724
囚心锁ツ
囚心锁ツ 2020-11-28 16:53

My training data has the form (?,15) where ? is a variable length.

When creating my model I specify this:

inp = Input(shape=(None,15))
conv = Conv1D(         


        
相关标签:
1条回答
  • 2020-11-28 16:57

    (Edited, according to OP's comment on this question, where they posted this link: https://github.com/fchollet/keras/issues/1920)


    Your X is not a single numpy array, it's an array of arrays. (Otherwise its shape would be X.shape=(35730,513,15).

    It must be a single numpy array for the fit method. Since you have a variable length, you cannot have a single numpy array containing all your data, you will have to divide it in smaller arrays, each array containing data with the same length.

    For that, you should maybe create a dictionary by shape, and loop the dictionary manually (there may be other better ways to do this...):

    #code in python 3.5
    xByShapes = {}
    yByShapes = {}
    for itemX,itemY in zip(X,Y):
        if itemX.shape in xByShapes:
            xByShapes[itemX.shape].append(itemX)
            yByShapes[itemX.shape].append(itemY)
        else:
            xByShapes[itemX.shape] = [itemX] #initially a list, because we're going to append items
            yByShapes[itemX.shape] = [itemY]
    

    At the end, you loop this dictionary for training:

    for shape in xByShapes:
        model.fit(
                  np.asarray(xByShapes[shape]), 
                  np.asarray(yByShapes[shape]),...
                  )
    

    Masking

    Alternatively, you can pad your data so all samples have the same length, using zeros or some dummy value.

    Then before anything in your model you can add a Masking layer that will ignore these padded segments. (Warning: some types of layer don't support masking)

    0 讨论(0)
提交回复
热议问题