使用未经训练的 Keras 模型预测数据

Predicting Data using an Untrained Keras Model

本质上,我想通过 Keras 模型传播数据,而无需先训练 Keras 模型。我尝试同时使用 predict() 并将原始张量输入模型。

数据是一个二维 Numpy float64 数组,形状为 (3, 3),完全用零填充。

模型本身概述如下:

inputs = keras.Input(shape=(3,), batch_size=1)
FFNNlayer1 = keras.layers.Dense(100, activation='relu')(inputs)
FFNNlayer2 = keras.layers.Dense(100, activation='relu')(FFNNlayer1)
numericalOutput = keras.layers.Dense(3, activation='sigmoid')(FFNNlayer2)
categoricalOutput = keras.layers.Dense(9, activation='softmax')(FFNNlayer2)
outputs = keras.layers.concatenate([numericalOutput, categoricalOutput])
hyperparameters = keras.Model(inputs=inputs, outputs=outputs, name="hyperparameters")
hyperparameters.summary()

该模型在其输出层需要两个不同的激活函数,因此我使用函数 API。

我第一次尝试使用 hyperparameter.predict(data[0]),但一直出现以下错误:

WARNING:tensorflow:Model was constructed with shape (1, 3) for input KerasTensor(type_spec=TensorSpec(shape=(1, 3), dtype=tf.float32, name='input_15'), name='input_15', description="created by layer 'input_15'"), but it was called on an input with incompatible shape (None,).
Traceback (most recent call last):

  File "<ipython-input-144-4c4a629eaefa>", line 1, in <module>
    mainNet.hyperparameters.predict([dataset_info[0]])

  File "C:\Users\hudso\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None

  File "C:\Users\hudso\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\func_graph.py", line 1129, in autograph_handler
    raise e.ag_error_metadata.to_exception(e)

ValueError: in user code:

    File "C:\Users\hudso\anaconda3\lib\site-packages\keras\engine\training.py", line 1621, in predict_function  *
        return step_function(self, iterator)
    File "C:\Users\hudso\anaconda3\lib\site-packages\keras\engine\training.py", line 1611, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\hudso\anaconda3\lib\site-packages\keras\engine\training.py", line 1604, in run_step  **
        outputs = model.predict_step(data)
    File "C:\Users\hudso\anaconda3\lib\site-packages\keras\engine\training.py", line 1572, in predict_step
        return self(x, training=False)
    File "C:\Users\hudso\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "C:\Users\hudso\anaconda3\lib\site-packages\keras\engine\input_spec.py", line 227, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" '

    ValueError: Exception encountered when calling layer "hyperparameters" (type Functional).
    
    Input 0 of layer "dense_20" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)
    
    Call arguments received:
      • inputs=('tf.Tensor(shape=(None,), dtype=float32)',)
      • training=False
      • mask=None

我摆弄了一下数组维度,但模型继续给出相同的错误。然后我尝试使用以下代码将原始张量输入模型:

tensorflow_dataset_info =  tf.data.Dataset.from_tensor_slices([dataset_info[0]]).batch(1)
aaaaa = enumerate(tensorflow_dataset_info)
predictions = mainNet.hyperparameters(aaaaa)

此代码继续出现以下错误:

Traceback (most recent call last):

  File "<ipython-input-143-df51fe8fd203>", line 1, in <module>
    hyperparameters = mainNet.hyperparameters(enumerate(tensorflow_dataset_info))

  File "C:\Users\hudso\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None

  File "C:\Users\hudso\anaconda3\lib\site-packages\keras\engine\input_spec.py", line 196, in assert_input_compatibility
    raise TypeError(f'Inputs to a layer should be tensors. Got: {x}')

TypeError: Inputs to a layer should be tensors. Got: <enumerate object at 0x000001F60081EA40>

我上网查了一段时间,也搜索了 tf.data 文档,但我仍然不确定如何解决这个问题。同样,我尝试了此代码的多种变体,但我仍然遇到大部分相同的错误。

如果 data.shape = (3, 3),当您将 data[0] 传递给 model.predict() 时,您实际上发送了一个形状为 (3, ) 的矢量,但您的模型期望形状为 [=15] =] 表示 1 个尺寸为 3 的示例。

尝试切片您的数据:

model.predict(data[:1])

这样你的张量就会有形状 (1, 3)。