【问题标题】:Python Keras LSTM input output shape issuePython Keras LSTM输入输出形状问题
【发布时间】:2017-06-25 13:10:45
【问题描述】:

我在 tensorflow 上运行 keras,试图实现一个多维 LSTM 网络来预测一个线性连续目标变量,每个示例的单个值(return_sequences = False)。 我的序列长度为 10,特征数(暗淡)为 11。 这是我运行的:

import pprint, pickle
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers import LSTM

# Input sequence
wholeSequence = [[0,0,0,0,0,0,0,0,0,2,1],
                 [0,0,0,0,0,0,0,0,2,1,0],
                 [0,0,0,0,0,0,0,2,1,0,0],
                 [0,0,0,0,0,0,2,1,0,0,0],
                 [0,0,0,0,0,2,1,0,0,0,0],
                 [0,0,0,0,2,1,0,0,0,0,0],
                 [0,0,0,2,1,0,0,0,0,0,0],
                 [0,0,2,1,0,0,0,0,0,0,0],
                 [0,2,1,0,0,0,0,0,0,0,0],
                 [2,1,0,0,0,0,0,0,0,0,0]]

# Preprocess Data:
wholeSequence = np.array(wholeSequence, dtype=float) # Convert to NP array.
data = wholeSequence
target = np.array([20])

# Reshape training data for Keras LSTM model
data = data.reshape(1, 10, 11)
target = target.reshape(1, 1, 1)

# Build Model
model = Sequential()
model.add(LSTM(11, input_shape=(10, 11), unroll=True, return_sequences=False))
model.add(Dense(11))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(data, target, nb_epoch=1, batch_size=1, verbose=2)

并得到错误 ValueError: Error when checks target: expected activation_1 to have 2 dimensions, but got array with shape (1, 1, 1) 不确定激活层应该得到什么(形状明智) 任何帮助表示赞赏 谢谢

【问题讨论】:

    标签: python-3.x tensorflow keras shape activation-function


    【解决方案1】:

    如果您只想拥有一个线性输出神经元,您可以简单地使用具有一个隐藏单元的密集层并在那里提供激活。然后你的输出可以是一个没有重塑的向量 - 我调整了你给定的示例代码以使其工作:

    wholeSequence = np.array(wholeSequence, dtype=float) # Convert to NP array.
    data = wholeSequence
    target = np.array([20])
    
    # Reshape training data for Keras LSTM model
    data = data.reshape(1, 10, 11)
    
    # Build Model
    model = Sequential()
    model.add(LSTM(11, input_shape=(10, 11), unroll=True, return_sequences=False))
    model.add(Dense(1, activation='linear'))
    model.compile(loss='mean_squared_error', optimizer='adam')
    model.fit(data, target, nb_epoch=1, batch_size=1, verbose=2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多