Keras Neural Network Training Set Data Error: Expected Varying Shape

Keras Neural Network Training Set Data Error: Expected Varying Shape

最近,我试图在该领域之前进行的工作的基础上创建一个股票市场预测程序,通过 Python 中的 Keras 模块创建的神经网络被输入调整后的股票价格来自 Quandl 的信息,利用上述信息来训练自己。我已经借助以下教程的帮助完成了这个程序;但是,我修改了提供的程序,用 Keras 顺序模型替换了 'sklearn' 线性模块的使用。教程如下:

https://www.youtube.com/watch?v=EYnC4ACIt2g&t=1551s

我另外从 Keras 模块的官方文档中导出了 Keras Sequential 模型信息:

https://keras.io

我已经在 Google Colaboratory 程序中完成了上述内容,以 Jupyter Notebook 的形式为 Python 提供了一个解释器和在线 IDE。我使用了以下代码:

import tensorflow as tf
import keras
import numpy as np
import quandl
from sklearn.model_selection import train_test_split

df = quandl.get("WIKI/FB")
df = df[['Adj. Close']]
forecast_out = 1
df['Prediction'] = df[['Adj. Close']].shift(-(forecast_out))

X = np.array(df.drop(['Prediction'], 1))
X = X[:-forecast_out]

y = np.array(df['Prediction'])
y = y[:-forecast_out]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

model = keras.models.Sequential()
model.add(keras.layers.Dense(units = 64, activation = 'relu'))
model.add(keras.layers.Dense(units = 10, activation = 'softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5, batch_size=32)

但是,Colaboratory 编译器提供了以下错误消息:

WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:4432: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.

WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:3576: The name tf.log is deprecated. Please use tf.math.log instead.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-70cb958ae676> in <module>()
      7               metrics=['accuracy'])
      8 
----> 9 model.fit(x_train, y_train, epochs=5, batch_size=32)

2 frames
/usr/local/lib/python3.6/dist-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    139                             ': expected ' + names[i] + ' to have shape ' +
    140                             str(shape) + ' but got array with shape ' +
--> 141                             str(data_shape))
    142     return data
    143 

ValueError: Error when checking target: expected dense_16 to have shape (10,) but got array with shape (1,)

这个错误是否有有效的解释,是否可以解决?如果是这样,什么是必然的?是否有必要改变训练数据或神经网络?感谢您的协助。

在神经网络中,你的最后一层(输出层)应该匹配目标的形状(y)。如我所见,您正在尝试预测股票价格(连续目标),因此形状应为 (1,)。你最终的致密层应该是:

model.add(keras.layers.Dense(units = 1, activation = 'linear')

最重要的是,你没有分类,所以你的损失不应该是 categorical_crossentropy。应该是mean_absolute_error,或者类似的

最后,最好在第一层明确声明 input_shape。这使事情变得更容易(我们也可以提供帮助)。