如何为我的 NN 模型正确调整数据?

How Do I Correctly Shape my Data for my NN Model?

我正在尝试在 Keras 中创建一个基本的神经网络模型,它将学习将正数相加,但在调整训练数据以适应模型时遇到了问题:

我已经为第一个 Dense 层的 "input_shape" 属性尝试了很多配置,但似乎没有任何效果。

# training data
training = np.array([[2,3],[4,5],[3,8],[2,9],[11,4],[13,5],[2,9]], dtype=float)
answers  = np.array([5, 9, 11, 11, 15, 18, 11],  dtype=float)
# create our model now:
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=16, input_shape=(2,)),
    tf.keras.layers.Dense(units=16, activation=tf.nn.relu),
    tf.keras.layers.Dense(units=1)
])
# set up the compile parameters: 
model.compile(loss='mean_squared_error',
              optimizer=tf.keras.optimizers.Adam(.1))
#fit the model:
model.fit(training, answers, epochs=550, verbose=False)

print(model.predict([[7,9]]))

我希望这 运行 没有错误并产生结果“16”,但我收到以下错误:

"Traceback (most recent call last):
  File "c2f", line 27, in <module>
    print(model.predict([[7,9]]))
  File "C:\Users\Aalok\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1096, in predict
    x, check_steps=True, steps_name='steps', steps=steps)
  File "C:\Users\Aalok\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 2382, in _standardize_user_data
    exception_prefix='input')
  File "C:\Users\Aalok\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training_utils.py", line 362, in standardize_input_data
    ' but got array with shape ' + str(data_shape))

ValueError: Error when checking input: expected dense_input to have shape (2,) but got array with shape (1,)

收到错误。根据堆栈跟踪,错误出现在这一行,

print(model.predict([[7,9]]))

现在,Keras Sequential 模型需要 NumPy 数组形式的输入 (ndarray)。在上面的行中,模型将数组解释为多个输入的列表(这不是你的情况)。

根据 official docsmodel.fit() 中的参数 x 是,

Numpy array of training data (if the model has a single input), or list of Numpy arrays (if the model has multiple inputs). If input layers in the model are named, you can also pass a dictionary mapping input names to Numpy arrays. x can be None (default) if feeding from framework-native tensors (e.g. TensorFlow data tensors).

我们需要创建一个 NumPy 数组,使用 numpy.array()

print(model.predict(np.array([[7,9]])))

错误已解决。我有 运行 代码,它工作得很好。