网站版权信息的正确写法,网络推广平台代理,临清住房建设网站,网站建设流程 报读文库零基础吃透#xff1a;SavedModel与RaggedTensor的结合使用
核心背景#xff08;先理清#xff09;
SavedModel 是 TensorFlow 官方的模型序列化格式#xff0c;能完整保存模型的「权重计算图签名」#xff0c;支持跨平台部署#xff08;如TensorFlow Serving、TFLiteSavedModel与RaggedTensor的结合使用核心背景先理清SavedModel是 TensorFlow 官方的模型序列化格式能完整保存模型的「权重计算图签名」支持跨平台部署如TensorFlow Serving、TFLite、离线复用RaggedTensor 与 SavedModel 兼容的核心规则TF 2.3通过「具体函数Concrete Function」原生支持 RaggedTensor无需额外处理TF 2.3 前需将 RaggedTensor 拆解为「values元素值 row_splits行分割点」两个张量再保存/加载。下面结合你提供的两个核心示例Keras模型、自定义tf.Module模型逐行解析代码逻辑、原理和关键注意事项。前置准备确保代码可运行importtensorflowastfimporttempfile# 用于创建临时目录存储SavedModel示例1保存/加载支持RaggedTensor的Keras模型步骤1先重建之前的Keras模型衔接上下文# 1. 定义数据复用之前的句子分类任务sentencestf.constant([What makes you think she is a witch?,She turned me into a newt.,A newt?,Well, I got better.])is_questiontf.constant([True,False,True,False])# 2. 预处理字符串→RaggedTensor单词哈希编码hash_buckets1000wordstf.strings.split(sentences, )hashed_wordstf.strings.to_hash_bucket_fast(words,hash_buckets)# RaggedTensor# 3. 构建适配RaggedTensor的Keras模型修正后版本避免LSTM报错keras_modeltf.keras.Sequential([tf.keras.layers.Input(shape[None],dtypetf.int64,raggedTrue),# 声明Ragged输入tf.keras.layers.Embedding(hash_buckets,16),tf.keras.layers.LSTM(32,use_biasFalse),tf.keras.layers.Dense(32),tf.keras.layers.Activation(tf.nn.relu),tf.keras.layers.Dense(1)])keras_model.compile(lossbinary_crossentropy,optimizerrmsprop)keras_model.fit(hashed_words.to_tensor(default_value0),is_question,epochs1)# 补0后训练步骤2保存Keras模型支持RaggedTensor输入# 创建临时目录避免手动管理路径keras_module_pathtempfile.mkdtemp()# 保存模型自动将Keras模型转换为SavedModel格式包含RaggedTensor的处理逻辑tf.saved_model.save(keras_model,keras_module_path)print(fKeras模型已保存到{keras_module_path})步骤3加载SavedModel并调用传入RaggedTensor# 加载保存的模型imported_modeltf.saved_model.load(keras_module_path)# 直接传入RaggedTensorhashed_words模型透明处理resultimported_model(hashed_words)print(\n加载后模型的预测结果)print(result)运行结果关键解读WARNING:absl:Function _wrapped_model contains input name(s) args_0 with unsupported characters which will be renamed to args_0_1 in the SavedModel. INFO:tensorflow:Assets written to: /tmp/xxx/assets tf.Tensor: shape(4, 1), dtypefloat32, numpy array([[0.05265009], [0.000567 ], [0.03915224], [0.0021234 ]], dtypefloat32)警告含义非错误SavedModel对输入名称的字符有规范自动将不兼容的名称如args_0重命名为args_0_1不影响模型功能核心兼容逻辑Keras模型的Input层声明了raggedTrue保存为SavedModel时TF会自动生成适配RaggedTensor的具体函数Concrete Function加载后可直接传入RaggedTensor结果一致性加载后模型的预测结果与原Keras模型完全一致说明RaggedTensor的处理逻辑被完整保存。示例2保存/加载支持RaggedTensor的自定义tf.Module模型自定义tf.Module是TF原生的模型封装方式比Keras更灵活但需手动构建具体函数指定RaggedTensor的输入签名否则SavedModel无法正确处理RaggedTensor。步骤1定义自定义tf.Module含RaggedTensor运算classCustomModule(tf.Module):def__init__(self,variable_value):super(CustomModule,self).__init__()# 定义可训练变量会被SavedModel保存self.vtf.Variable(variable_value,dtypetf.float32)# 用tf.function装饰编译为计算图支持RaggedTensortf.functiondefgrow(self,x):# 核心逻辑RaggedTensor的每个元素 × 变量vreturnx*self.v# 实例化模块变量v100.0moduleCustomModule(100.0)步骤2预构建具体函数关键适配RaggedTensor# 必须先构建具体函数指定输入为RaggedTensorSpec二维、float32、可变长度# 作用让SavedModel记录RaggedTensor的输入签名避免加载后调用报错concrete_funcmodule.grow.get_concrete_function(tf.RaggedTensorSpec(shape[None,None],dtypetf.float32))print(预构建的具体函数,concrete_func)步骤3保存自定义模块# 创建临时目录custom_module_pathtempfile.mkdtemp()# 保存模块包含变量v、grow函数的计算图、RaggedTensor的输入签名tf.saved_model.save(module,custom_module_path)print(f\n自定义模型已保存到{custom_module_path})步骤4加载并调用传入RaggedTensor# 加载保存的模块imported_moduletf.saved_model.load(custom_module_path)# 传入RaggedTensor调用grow函数ragged_inputtf.ragged.constant([[1.0,4.0,3.0],[2.0]],dtypetf.float32)resultimported_module.grow(ragged_input)print(\n自定义模型调用结果)print(result)运行结果关键解读INFO:tensorflow:Assets written to: /tmp/yyy/assets tf.RaggedTensor [[100.0, 400.0, 300.0], [200.0]]为什么必须预构建具体函数自定义tf.Module的tf.function函数默认是“动态跟踪”的未指定输入签名时SavedModel无法确定输入类型密集张量/RaggedTensor用get_concrete_functiontf.RaggedTensorSpec预构建后SavedModel会固化RaggedTensor的处理逻辑加载后可直接调用。运算逻辑验证RaggedTensor的每个元素 × 变量v100.0结果保留RaggedTensor结构[1.0,4.0,3.0] × 100 → [100.0,400.0,300.0][2.0] × 100 → [200.0]。关键注意事项避坑核心1. 版本要求重中之重TF 2.3具体函数原生支持RaggedTensor无需额外处理TF 2.3 前SavedModel的签名不支持RaggedTensor需手动拆解RaggedTensor为两个张量# 低版本兼容拆解RaggedTensorrttf.ragged.constant([[1.0,2.0],[3.0]])rt_valuesrt.values# 所有元素值[1.0,2.0,3.0]rt_row_splitsrt.row_splits# 行分割点[0,2,3]# 保存/加载时传递valuesrow_splits加载后用tf.RaggedTensor.from_row_splits重构2. 具体函数Concrete Function的必要性Keras模型TF自动为raggedTrue的Input层生成具体函数无需手动构建自定义tf.Module必须用get_concrete_function(tf.RaggedTensorSpec)预构建否则加载后调用RaggedTensor会报错。3. tf.RaggedTensorSpec的作用定义RaggedTensor的输入签名形状、 dtype让SavedModel明确输入约束示例中shape[None, None]表示二维RaggedTensor两个维度长度均可变若需固定某一维如固定批次大小为32可写shape[32, None]。4. SavedModel的核心组成了解即可保存后的SavedModel目录包含assets/静态资源如词汇表variables/模型权重如CustomModule的变量vsaved_model.pb计算图签名包含RaggedTensor的处理逻辑。核心总结SavedModel RaggedTensor模型类型保存关键步骤加载后调用方式Keras模型Input层设置raggedTrue直接tf.saved_model.save直接传入RaggedTensor自定义tf.Module用get_concrete_function(tf.RaggedTensorSpec)预构建具体函数再保存传入符合RaggedTensorSpec的RaggedTensor核心原则SavedModel对RaggedTensor的支持依赖「具体函数Concrete Function」需确保保存前生成适配RaggedTensor的具体函数TF 2.3是兼容的最低版本低版本需拆解RaggedTensor为分量张量Keras模型的兼容性更“傻瓜化”自动处理自定义tf.Module需手动指定输入签名。这套方案是生产环境中部署“处理可变长度数据文本、序列”模型的标准流程既保留RaggedTensor无冗余的优势又能利用SavedModel实现模型的序列化和部署。