LSTM神经网络输入/输出维度错误

我对TensorFlow和LSTM架构还比较陌生。我在处理数据集的输入和输出(x_train, x_test, y_train, y_test)时遇到了问题。

我的输入的原始形状如下:

  • x_train: (366,4)
  • x_test: (104,4)
  • y_train: (366,)
  • y_test: (104,)

y_train和y_test是一系列股票价格。x_train和x_test是我用来预测股票价格的四个特征。

# 分割训练和测试数据
train_start_date = '2010-01-08'
train_end_date = '2017-01-06'
test_start_date = '2017-01-13'
test_end_date = '2019-01-04'
train = df.ix[train_start_date : train_end_date]
test = df.ix[test_start_date:test_end_date]
X_test = sentimentScorer(test)
X_train = sentimentScorer(train)
Y_test = test['prices'] 
Y_train = train['prices']
# 转换为LSTM输入的3D数组
X_test = X_test.reshape(1, 104, 4)
X_train = X_train.reshape(1, 366, 4)
model = Sequential()
model.add(LSTM(128, input_shape=(366,4), activation='relu', return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(128, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
opt = tf.keras.optimizers.Adam(lr=0.001, decay=1e-6)
# 编译模型
model.compile(    
    loss='sparse_categorical_crossentropy',    
    optimizer=opt,    
    metrics=['accuracy'],
)
model.fit(X_train,          
          Y_train,          
          epochs=3,          
          validation_data=(X_test, Y_test))

这是生成的错误:

> --------------------------------------------------------------------------- ValueError                                Traceback (most recent call> last) <ipython-input-101-fd4099583529> in <module>>      65           Y_train,>      66           epochs=3,> ---> 67           validation_data=(X_test, Y_test))> > c:\users\talal\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\keras\engine\training.py> in fit(self, x, y, batch_size, epochs, verbose, callbacks,> validation_split, validation_data, shuffle, class_weight,> sample_weight, initial_epoch, steps_per_epoch, validation_steps,> **kwargs)    1507         steps_name='steps_per_epoch',    1508         steps=steps_per_epoch,> -> 1509         validation_split=validation_split)    1510     1511     # Prepare validation data.> > c:\users\talal\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\keras\engine\training.py> in _standardize_user_data(self, x, y, sample_weight, class_weight,> batch_size, check_steps, steps_name, steps, validation_split)>     991       x, y = next_element>     992     x, y, sample_weights = self._standardize_weights(x, y, sample_weight,> --> 993                                                      class_weight, batch_size)>     994     return x, y, sample_weights>     995 > > c:\users\talal\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\keras\engine\training.py> in _standardize_weights(self, x, y, sample_weight, class_weight,> batch_size)    1110         feed_input_shapes,    1111        > check_batch_axis=False,  # Don't enforce the batch size.> -> 1112         exception_prefix='input')    1113     1114     if y is not None:> > c:\users\talal\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\keras\engine\training_utils.py> in standardize_input_data(data, names, shapes, check_batch_axis,> exception_prefix)>     314                            ': expected ' + names[i] + ' to have ' +>     315                            str(len(shape)) + ' dimensions, but got array '> --> 316                            'with shape ' + str(data_shape))>     317         if not check_batch_axis:>     318           data_shape = data_shape[1:]> > ValueError: Error when checking input: expected lstm_18_input to have> 3 dimensions, but got array with shape (366, 4)

回答:

你的代码基本上是正确的。

你的y_testy_train应该是一个元素的数组或形状为(1,1)的数组,这没有关系。

不过你的输入形状是错误的,第一个LSTM应该这样设置:

model.add(LSTM(128, input_shape=(None,4), activation='relu', return_sequences=True))

注意None,因为你的测试和训练序列长度不同,你不能指定它(Keras接受第一个维度未指定)。错误是由于长度分别为366和104引起的。如果你想在RNN中使用批处理,你应该使用keras.preprocessing.sequence.pad_sequences进行零填充。

不需要在批处理中指定input_shape,网络的其他部分应该没问题。

如果你在进行回归,而不是分类,可能是这种情况,你应该执行@Ankish Bansal提到的最后两个步骤,例如将损失函数改为mean squared error,并将最后一层的输出值改为1而不是10。

Related Posts

如何使用Google Protobuf解析、编辑和生成object_detection/pipeline.config文件

我在一个常见的集成学习范式中训练多个模型,目前我在处理…

我的GridSearchCV不起作用,我不知道为什么

大家好,我在使用GridSearchCV时遇到了问题,…

Keras: 两个同时进行的层,其中一个对前一层的输出进行卷积

我想实现这样的模型连接: 输入图像1 -> 卷积层1 …

如何将行数据转换为列数据而不使用独热编码

我有一个如下所示的数据集。 MonthDate Day…

使用 ML Kit 与 NNAPI

我正在尝试在运行 Android 9 的设备上使用新的…

Vowpal Wabbit 可能的哈希冲突

我在VW中生成了一个模型,并且在相同的数据上生成了两个…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注