首页 > 编程问答 >ValueError: ('预期 `model` 参数是一个 `Model` 实例,得到 ', <keras.engine.sequential.Sequential 对象位

ValueError: ('预期 `model` 参数是一个 `Model` 实例,得到 ', <keras.engine.sequential.Sequential 对象位

时间:2024-07-22 14:15:13浏览次数:11  
标签:python tensorflow quantization-aware-training

我想做 量化感知训练

这是我的模型架构。

Model: "sequential_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
masking_4 (Masking)          (None, 389, 64)           0         
_________________________________________________________________
my_layer_5_4 (my_layer_5)       (None, 389, 512)          12288     
_________________________________________________________________
time_distributed_4 (TimeDist (None, 389, 39)           20007     
=================================================================

我遵循 tfmot.quantization.keras.QuantizeConfig , 我希望他们都使用量化。 这是我的代码

import tensorflow_model_optimization as tfmot
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantize_configs
NoOpQuantizeConfig = default_8bit_quantize_configs.NoOpQuantizeConfig

class NoOpQuantizeConfig(tfmot.quantization.keras.QuantizeConfig):
    """QuantizeConfig which does not quantize any part of the layer."""
    def get_weights_and_quantizers(self, layer):
        return []
    def get_activations_and_quantizers(self, layer):
        return []
    def set_quantize_weights(self, layer, quantize_weights):
        pass
    def set_quantize_activations(self, layer, quantize_activations):
        pass
    def get_output_quantizers(self, layer):
        return []
    def get_config(self):
        return {}
  
def apply_quantization(layer):
    if isinstance(layer, (tf.keras.layers.TimeDistributed, tf.keras.layers.Masking,tf.keras.layers.my_layer_5_4  )):
        return tfmot.quantization.keras.quantize_annotate_layer(layer, quantize_config=NoOpQuantizeConfig())
    else:
        return tfmot.quantization.keras.quantize_annotate_layer(layer)

if __name__ == '__main__':
    model = load_model('./model.h5',custom_objects = {'my_layer_5': my_layer_5})
    model.summary()

    annotated_model = tf.keras.models.clone_model(
        model,
        clone_function=apply_quantization,
    )

    with tf.keras.utils.custom_object_scope({"NoOpQuantizeConfig": NoOpQuantizeConfig}):
        q_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
    
    q_aware_model.summary()

当我运行它时,但显示错误

ValueError: ('Expected `model` argument to be a `Model` instance, got ', <keras.engine.sequential.Sequential object at 0x7f234263dfd0>)```


出现 ValueError: ('Expected 'model' argument to be a 'Model' instance, got ', <keras.engine.sequential.Sequential object at 0x7f234263dfd0>) 错误,是因为你试图将 tfmot.quantization.keras.quantize_apply 应用于一个 Sequential 模型,而这个函数需要的是一个函数式 API 模型。

以下是解决此问题的步骤:

  1. 将 Sequential 模型转换为函数式 API 模型

你可以通过创建一个新的 Input 层并将你的 Sequential 模型的输入和输出连接到该层来做到这一点。例如:

```python input_tensor = tf.keras.Input(shape=(389, 64)) # 根据你的模型输入形状进行调整 output_tensor = model(input_tensor) # 将 Sequential 模型应用于输入张量

functional_model = tf.keras.Model(inputs=input_tensor, outputs=output_tensor) ```

  1. 使用函数式 API 模型进行量化感知训练

现在,你可以使用 functional_model 代替原始的 Sequential 模型来进行量化感知训练。

```python annotated_model = tf.keras.models.clone_model( functional_model, clone_function=apply_quantization, )

with tf.keras.utils.custom_object_scope({"NoOpQuantizeConfig": NoOpQuantizeConfig}): q_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model) ```

完整的代码:

import tensorflow_model_optimization as tfmot
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantize_configs
NoOpQuantizeConfig = default_8bit_quantize_configs.NoOpQuantizeConfig

# ... (你的 NoOpQuantizeConfig 和 apply_quantization 函数) ...

if __name__ == '__main__':
    model = load_model('./model.h5',custom_objects = {'my_layer_5': my_layer_5})
    model.summary()

    # 将 Sequential 模型转换为函数式 API 模型
    input_tensor = tf.keras.Input(shape=(389, 64))
    output_tensor = model(input_tensor)
    functional_model = tf.keras.Model(inputs=input_tensor, outputs=output_tensor)

    annotated_model = tf.keras.models.clone_model(
        functional_model,
        clone_function=apply_quantization,
    )

    with tf.keras.utils.custom_object_scope({"NoOpQuantizeConfig": NoOpQuantizeConfig}):
        q_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)

    q_aware_model.summary()

通过进行这些更改,你就可以解决 ValueError 并成功地对你的模型进行量化感知训练。

标签:python,tensorflow,quantization-aware-training
From: 78777178

相关文章

  • 当 python 脚本通过 jenkins + Github 在 Windows 本地计算机上运行时,chrome 浏览器不
    我的Python代码是(windowsMachine)fromseleniumimportwebdriverprint("newLine")print("2Line")print("3Line")holdChrome=webdriver.ChromeOptions()holdChrome.add_experimental_option("detach",True)#Restricta......
  • python_基础_数据类型
    基础数据类型不需要声明,只有被赋值后才会创建变量。变量本身没有类型,“类型”指的是所存值的类型。类型判断type(x)和isinstance(x,int)前者不会认为子类是一种他的父类类型后者会认为子类是父类类型>>>classA:...pass...>>>classB(A):...pass......
  • IPython 使用技巧
    IPython是一个强大的交互式Pythonshell,提供了许多方便的功能,使Python编程更加高效和愉快。本文将介绍一些IPython的实用技巧,帮助开发者充分利用其功能,提高编程效率。1.基本操作和快捷键1.1启动IPython可以通过在终端输入以下命令来启动IPython:ipython启动后,你......
  • 【python】类方法和静态方法的区别
    类方法和静态方法在Python中都可以用来定义与类相关的功能,但它们有不同的使用场景和优缺点。虽然类方法也可以用来实现验证逻辑,但静态方法在某些情况下更合适。让我们详细看看这两种方法的区别以及为什么在某些情况下静态方法可能更适合验证功能。类方法和静态方法的区别类......
  • Python自动化:一键提取千万个Excel指定数据
    一、传统方法的局限性打开每个Excel文件,逐个查找需要的数据。筛选出老板需要的数据列。复制并粘贴到新的工作表中。保存并关闭每个文件。这个过程不仅耗时,而且容易出错。每一次的筛选都可能遗漏数据,每一次的复制粘贴都可能引入错误。二、Python自动化的解决方案i......
  • Python:提交和跟踪许多子流程会导致“卡住”子流程
    我有一个第3方cli可执行文件,需要从python代码中调用。这些都是繁重的计算(CPU),我需要调用它大约50-100次。可执行文件本身在某种程度上是多线程的,但不是所有步骤,而且我有很多可用的核心。这意味着我希望同时运行多个子进程,但不是全部。因此,我需要提交其中一些,然后跟踪......
  • 无法在 Ubuntu 20.04 中安装 python3-venv,一些损坏的软件包
    这可能很长,但请耐心看完当我在关注这篇文章时尝试安装python3-venvsudoaptinstallbuild-essentiallibssl-devlibffi-devpython3-dev它抛出了以下错误:libffi-devpython3-devReadingpackagelists...DoneBuildingdependencytreeRead......
  • 正则表达式在python爬虫中常用的方法举例
    在爬虫中,正则表达式被广泛用于从网页中提取特定信息。以下是一些常用的正则表达式方法举例,以及它们在爬虫中的典型应用场景:1.提取URLimportreurl_pattern=r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'urls=re.findall(url_pattern,html_content)用于从网页中......
  • 使用 Python XlsxWriter 将 DatePicker 添加到 Excel 单元格中?
    我正在尝试使用PythonXlsxWriter生成的Excel创建输入表单。我想知道是否可以在Excel单元格中添加一个迷你日历(作为DatePicker)供用户输入日期?我偶然发现了Microsoft支持团队提供的本指南插入日期选择器:|||https://support.microsoft.com/en-us/office/......
  • [1037] Python operation of three keys shortcut (pynput)
    Theshortcutof win+shift+leftdoesnotworkwellin pyautogui,butitworkswellin pynput.MovingtheActiveWindowtoaDifferentMonitor: You’reright;PyAutoGUIdoesn’tdirectlysupportmovingwindowsacrossmonitorswiththeeleganceofaswan......