【问题标题】:Format of adding hidden layers in Keras.在 Keras 中添加隐藏层的格式。
【发布时间】:2019-05-19 04:22:38
【问题描述】:

我写了一个神经网络代码,我想给它添加隐藏层。我可以访问这一小部分代码:

trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)

trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)

trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

有没有办法在有这么多可用信息的情况下添加隐藏层?此外,此代码在 Python3 中运行良好。

这将是一个很大的帮助。谢谢。

【问题讨论】:

标签: python-3.x tensorflow keras time-series recurrent-neural-network


【解决方案1】:

上述代码是核心 ML 部分的完整实现。

您在这里创建了模型,
model = Sequential()

这是输入层,
model.add(LSTM(4, input_shape=(1, look_back)))

这是输出层
model.add(Dense(1))

模型编译
model.compile(loss='mean_squared_error', optimizer='adam')

模型训练
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)

在输入和输出层之间添加的任何层都称为隐藏层,您可以轻松添加,最终代码如下所示,

trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)

trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(4)) # New hidden layer with 4 params
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)

trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

【讨论】:

    【解决方案2】:

    您可以尝试使用以下格式结构添加隐藏层。但是,该示例不适用于您的问题:

    from tensorflow.keras.layers import Dense
    from tensorflow.keras import Model, Input
    
    input_layer = Input(shape=(3,), name='input') # 3 dimensional input
    hidden_layer1 = Dense(units=20, activation="sigmoid", name="hidden_layer1")(input_layer)
    hidden_layer2 = Dense(units=20, activation="sigmoid", name="hidden_layer2")(hidden_layer1)
    output_layer = Dense(units=1, activation="sigmoid", name="output_layer")(hidden_layer2)
      
    # Create the model
    model = Model(input_layer, output_layer)
    

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 2019-01-27
      • 2018-01-25
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2018-05-27
      相关资源
      最近更新 更多