You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

tfjs-react-native导出模型转Keras/Saved Model失败,如何用于TensorFlow联邦学习?

问题:将tfjs-react-native保存的模型转为Keras/TF SavedModel用于联邦学习

我尝试用tensorflowjs_converter把tfjs-react-native保存的模型转成Keras或TF SavedModel格式,目标是把React Native端的模型权重用于TensorFlow联邦学习的全局模型训练,但遇到了问题:

  1. 先通过Python将Base64编码的权重转成二进制文件:
# Read the Base64 encoded file
with open("model_weights", "r") as file:
    base64_string = file.read()

# Decode the Base64 string
decoded_bytes = base64.b64decode(base64_string)

# Write the decoded bytes to a .bin file
with open("output.bin", "wb") as bin_file:
    bin_file.write(decoded_bytes)
  1. 执行转换命令:
tensorflowjs_converter --input_format=tfjs_layers_model --output_format=keras rn_model/model_data.json rn_model_conv

其中model_data.json是通过tfjs-react-native的asyncStorageIO保存的文件,执行后报错:

KeyError: 'Field "weightsManifest" is missing from the JSON content.'


解决方法

核心原因

tfjs-react-native的asyncStorageIO是为React Native本地存储优化的轻量保存方式,生成的model_data.json并非标准的tfjs_layers_model格式——标准格式要求JSON必须包含weightsManifest字段,用于描述权重文件的路径、权重元数据等信息,而asyncStorageIO保存的文件缺少这个关键结构。

方案一:从React Native端导出标准tfjs_layers_model格式(推荐)

不要直接从AsyncStorage导出零散文件,而是在React Native代码中用tfjs的标准保存方式导出模型,确保生成符合tfjs规范的文件结构:

import * as tf from '@tensorflow/tfjs-react-native';
import { FileSystem } from 'expo'; // 或使用React Native原生文件系统API

// 假设你的模型实例为model
const exportStandardModel = async () => {
  // 指定保存路径并创建目录
  const modelDir = `${FileSystem.documentDirectory}tfjs_model/`;
  await FileSystem.makeDirectoryAsync(modelDir, { intermediates: true });
  
  // 保存为标准tfjs_layers_model格式
  await model.save(`file://${modelDir}model.json`, { 
    weightsPathPrefix: `${modelDir}weights` 
  });

  // 之后将modelDir下的model.json和权重.bin文件导出到电脑即可
};

导出后,直接用这些标准文件执行转换命令,无需手动处理Base64。

方案二:手动补全model_data.json的weightsManifest字段(应急方案)

如果无法重新从React Native导出模型,需要手动修改model_data.json,添加weightsManifest字段并关联你的output.bin文件:

  1. 在model_data.json的根节点添加以下结构:
"weightsManifest": [
  {
    "paths": ["output.bin"],
    "weights": [
      // 需补全每一层权重的元数据,格式示例:
      {"name": "dense/kernel", "shape": [784, 128], "dtype": "float32"},
      {"name": "dense/bias", "shape": [128], "dtype": "float32"}
      // 元数据需与你的模型权重完全对应,可通过tfjs加载原模型后打印权重信息获取
    ]
  }
]
  1. 确保output.bin和修改后的model_data.json在同一目录下,重新执行转换命令。

验证转换结果

转换完成后,在Python中加载模型确认可用:

import tensorflow as tf

# 加载Keras模型
model = tf.keras.models.load_model('rn_model_conv')
model.summary()

# 或加载SavedModel(如果转换时指定output_format=tf_saved_model)
model = tf.saved_model.load('rn_model_saved')

内容的提问来源于stack exchange,提问作者daniellaios

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 17:25:19