最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

tensorflow - NotImplementedError: StreamingModel.call() not implemented in custom Keras model - Is this a new compilation error?

programmeradmin3浏览0评论

1.Description I am implementing a custom Keras model (StreamingModel) with a custom layer (CircularBufferLayer). However, I am encountering a NotImplementedError when compiling the model. The error suggests that the call() method of StreamingModel is not implemented, even though I have defined it. Here is the error:

NotImplementedError: Exception encountered when calling StreamingModel.call().
Could not automatically infer the output shape / dtype of 'streaming_model' (of type StreamingModel).
Either the `StreamingModel.call()` method is incorrect, or you need to implement the `StreamingModelpute_output_spec() / compute_output_shape()` method.
Error encountered: Model StreamingModel does not have a `call()` method implemented.

2.Context I am building a streaming model for real-time data processing. The model uses a custom layer (CircularBufferLayer) to maintain a buffer of recent inputs. The StreamingModel is a custom Keras model that processes these inputs. The goal is to train the model on sequential data.

import tensorflow as tf
class CircularBufferLayer(tf.keras.layers.Layer):
    def __init__(self, num_features, buffer_size, stride, **kwargs):
        super().__init__(**kwargs)
        self.num_features = num_features
        self.buffer_size = buffer_size
        self.stride = stride
        self.gradient_scale = 0.1
        self.buffer = self.add_weight(name='buffer', shape=(1, buffer_size, num_features),
                                      initializer='zeros', trainable=False, dtype=tf.float32)
        self.call_count = self.add_weight(name='call_count', shape=(), initializer='zeros',
                                          dtype=tf.int32, trainable=False)
        self.total_call_count = self.add_weight(name='total_call_count', shape=(), initializer='zeros',
                                                dtype=tf.int32, trainable=False)

    def call(self, inputs):
        scaled_input = tf.multiply(inputs, self.gradient_scale)
        new_buffer = tf.concat([scaled_input, self.buffer[:, :-1]], axis=1)
        self.buffer.assign(new_buffer)
        return self.buffer
class StreamingModel(tf.keras.Model):
    def call(self, inputs):
        x, _ = super().call(inputs) 
        return x
buffer_layer = CircularBufferLayer(num_features=64, buffer_size=10, stride=1)
model = StreamingModel()
input_shape = (None, 10, 64)
inputs = tf.keras.Input(shape=input_shape[1:])  
outputs = model(inputs)
model = tf.keras.Model(inputs=inputs, outputs=outputs)

modelpile(
    optimizer='adam',  
    loss='mse',       
    metrics=['mae']   
)

3.Error log:

2025-03-19 16:09:45.545622: I tensorflow/core/util/port:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2025-03-19 16:09:46.283611: I tensorflow/core/util/port:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2025-03-19 16:09:48.149403: I tensorflow/core/platform/cpu_feature_guard:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 AVX_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
WARNING:tensorflow:From D:\project\DLComplier\.venv\Lib\site-packages\keras\src\backend\tensorflow\core.py:216: The name tf.placeholder is deprecated. Please use tfpat.v1.placeholder instead.

Traceback (most recent call last):
  File "D:\project\DLComplier\.venv\statiblity.py", line 37, in <module>
    outputs = model(inputs)
              ^^^^^^^^^^^^^
  File "D:\project\DLComplier\.venv\Lib\site-packages\keras\src\utils\traceback_utils.py", line 122, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "D:\project\DLComplier\.venv\statiblity.py", line 27, in call
    x, _ = super().call(inputs)  # Assume another branch is truncated
           ^^^^^^^^^^^^^^^^^^^^
NotImplementedError: Exception encountered when calling StreamingModel.call().

Could not automatically infer the output shape / dtype of 'streaming_model' (of type StreamingModel). Either the `StreamingModel.call()` method is incorrect, or you need to implement the `StreamingModelpute_output_spec() / compute_output_shape()` method. Error encountered:

Model StreamingModel does not have a `call()` method implemented.

Arguments received by StreamingModel.call():
  • args=('<KerasTensor shape=(None, 10, 64), dtype=float32, sparse=False, name=keras_tensor>',)
  • kwargs=<class 'inspect._empty'>

4.Environment Information TensorFlow Version: 2.18.0

Python Version: 3.12.6

Operating System: Windows 11

GPU/CPU: CPU 5.Question Is this a new compilation error in TensorFlow, or am I missing something in my implementation?

Why is TensorFlow unable to infer the output shape/dtype of StreamingModel?

Do I need to implement compute_output_spec() or compute_output_shape() for custom models? If so, how?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论