如何在Keras-Python中输入2D数组?

时间:2018-11-01 11:00:36

标签: python numpy machine-learning keras numpy-ndarray

我对机器学习和keras非常陌生,并且一直试图输入数据;我有如下数据:

[[[0.01363717 0.        ]
  [0.01577874 0.        ]
  [0.01463021 0.        ]]

 [[0.01577874 0.        ]
  [0.01463021 0.        ]
  [0.01006721 0.        ]]

 [[0.01463021 0.        ]
  [0.01006721 0.        ]
  [0.00762504 0.        ]]...]

数据的形状为:(1607,3,2)。 如何通过:

 [[0.01363717 0.        ]
  [0.01577874 0.        ]
  [0.01463021 0.        ]]

作为512个CuDNNLSTM单元层的输入?

这是我的整个网络:

def create_model():
    model = Sequential()

    model.add(CuDNNLSTM(512, input_shape=(3,2), return_sequences=True, name='inputlstm1'))
    model.add(Dropout(0.2))

    model.add(CuDNNLSTM(512, return_sequences=True,name='lstm2'))
    model.add(Dropout(0.2))

    model.add(CuDNNLSTM(512, return_sequences=True,name='lstm3'))
    model.add(Dropout(0.2))

    model.add(Dense(32, activation='relu', name='dense1'))
    model.add(Dropout(0.2))

    model.add(Dense(1, activation='softmax', name='denseoutput2'))


    # Compile model
    model.compile(
        loss='mse',
        optimizer='adam',
        metrics=['accuracy'],
    )
    return model 

及其合适之处:

model=create_model()
history=model.fit(xtrain, ytrain,batch_size=1, epochs=5, validation_data=(xtest, ytest), verbose=1)

2 个答案:

答案 0 :(得分:1)

构建keras层包括指定传递的数组的形状,这里要训练的数组形状为(3,2),带有1607个样本,

input_shape = (3,2)
X = LSTM(124, activation = 'sigmoid', name='layer1', dropout = 0.4) (temp)

如果要使用堆叠式LSTM,可以使用此

input_shape = (3,2)
    X = LSTM(124, activation = 'sigmoid', name='layer1', dropout = 0.4,return_sequences=True) (temp)
    X = LSTM(64, activation = 'sigmoid', name='layer2', dropout = 0.4) (X)

修改

def create_model():
    model = keras.models.Sequential()

    model.add(keras.layers.CuDNNLSTM(512, input_shape=(3,2), return_sequences=True, name='inputlstm1'))
    model.add(keras.layers.Dropout(0.2))

    model.add(keras.layers.CuDNNLSTM(512, return_sequences=True,name='lstm2'))
    model.add(keras.layers.Dropout(0.2))

    # The last layer of Stacked LSTM need not to return the input sequences
    model.add(keras.layers.CuDNNLSTM(512,name='lstm3'))
    model.add(keras.layers.Dropout(0.2))

    model.add(keras.layers.Dense(32, activation='relu', name='dense1'))
    model.add(keras.layers.Dropout(0.2))

    model.add(keras.layers.Dense(1, activation='softmax', name='denseoutput2'))


    # Compile model
    model.compile(
        loss='mse',
        optimizer='adam',
        metrics=['accuracy'],
    )
    return model 

答案 1 :(得分:0)

您可以设置 mvn clean install -f ,Keras会照顾好它。只需将整个数组放入模型输入即可。