将经过训练的 HDF5 模型加载到 Rust 中以进行预测

     2023-03-11     122

关键词:

【中文标题】将经过训练的 HDF5 模型加载到 Rust 中以进行预测【英文标题】:Loading a trained HDF5 model into Rust to make predictions 【发布时间】:2021-09-12 21:46:03 【问题描述】:

我使用 MNIST 数据集训练了一个模型来识别数字。该模型已使用 TensorFlow 和 Keras 在 Python 中进行了训练,并将输出保存到我​​命名为“sample_mnist.h5”的 HDF5 文件中。

我想将经过训练的模型从 HDF5 文件加载到 Rust 中以进行预测。

在 Python 中,我可以从 HDF5 生成模型并使用代码进行预测:

model = keras.models.load_model("./sample_mnist.h5")
model.precict(test_input)  # assumes test_input is the correct input type for the model

这个 Python sn-p 的 Rust 等价物是什么?

【问题讨论】:

【参考方案1】:

首先,您需要将模型保存为 .pb 格式,而不是 .hdf5,以便将其移植到 Rust,因为这种格式保存 一切关于在 Python 之外重建模型所需的执行图。 TensorFlow Rust repo 上有一个来自用户justnoxx 的开放pull request,它展示了如何为一个简单的模型执行此操作。要点是在 Python 中给出了一些模型......

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense

classifier = Sequential()
classifier.add(Dense(5, activation='relu', name="test_in", input_dim=5)) # Named input
classifier.add(Dense(5, activation='relu'))
classifier.add(Dense(1, activation='sigmoid', name="test_out")) # Named output

classifier.compile(optimizer ='adam', loss='binary_crossentropy', metrics=['accuracy'])

classifier.fit([[0.1, 0.2, 0.3, 0.4, 0.5]], [[1]], batch_size=1, epochs=1);

classifier.save('examples/keras_single_input_saved_model', save_format='tf')

以及我们命名的输入“test_in”和输出“test_out”以及它们的预期大小,我们可以在 Rust 中应用保存的模型...

use tensorflow::Graph, SavedModelBundle, SessionOptions, SessionRunArgs, Tensor;

fn main() 

    // In this file test_in_input is being used while in the python script,
    // that generates the saved model from Keras model it has a name "test_in".
    // For multiple inputs _input is not being appended to signature input parameter name.
    let signature_input_parameter_name = "test_in_input";
    let signature_output_parameter_name = "test_out";

    // Initialize save_dir, input tensor, and an empty graph
    let save_dir =
        "examples/keras_single_input_saved_model";
    let tensor: Tensor<f32> = Tensor::new(&[1, 5])
        .with_values(&[0.1, 0.2, 0.3, 0.4, 0.5])
        .expect("Can't create tensor");
    let mut graph = Graph::new();

    // Load saved model bundle (session state + meta_graph data)
    let bundle = 
        SavedModelBundle::load(&SessionOptions::new(), &["serve"], &mut graph, save_dir)
        .expect("Can't load saved model");

    // Get the session from the loaded model bundle
    let session = &bundle.session;

    // Get signature metadata from the model bundle
    let signature = bundle
        .meta_graph_def()
        .get_signature("serving_default")
        .unwrap();

    // Get input/output info
    let input_info = signature.get_input(signature_input_parameter_name).unwrap();
    let output_info = signature
        .get_output(signature_output_parameter_name)
        .unwrap();

    // Get input/output ops from graph
    let input_op = graph
        .operation_by_name_required(&input_info.name().name)
        .unwrap();
    let output_op = graph
        .operation_by_name_required(&output_info.name().name)
        .unwrap();
    
    // Manages inputs and outputs for the execution of the graph
    let mut args = SessionRunArgs::new();
    args.add_feed(&input_op, 0, &tensor); // Add any inputs

    let out = args.request_fetch(&output_op, 0); // Request outputs

    // Run model
    session.run(&mut args) // Pass to session to run
        .expect("Error occurred during calculations");

    // Fetch outputs after graph execution
    let out_res: f32 = args.fetch(out).unwrap()[0];

    println!("Results: :?", out_res);

【讨论】:

这能回答你的问题吗?

如何将经过 gpu 训练的模型加载到 cpu 中?

】如何将经过gpu训练的模型加载到cpu中?【英文标题】:howtoloadthegputrainedmodelintothecpu?【发布时间】:2019-08-2523:14:39【问题描述】:我正在使用PyTorch。我将在带有CPU的多个GPU上使用已经训练好的模型。怎么做这个任务?我在Anacon... 查看详情

为啥我无法保存经过训练的 RandomForestRegressor 模型?

】为啥我无法保存经过训练的RandomForestRegressor模型?【英文标题】:Whycan\'tIsavemytrainedRandomForestRegressormodel?为什么我无法保存经过训练的RandomForestRegressor模型?【发布时间】:2015-11-2101:54:19【问题描述】:我有一个训练有素的Rand... 查看详情

加载经过训练的 tensorflow protobuf 模型后,Android 应用程序崩溃

】加载经过训练的tensorflowprotobuf模型后,Android应用程序崩溃【英文标题】:Androidappcrashesafterloadingtrainedtensorflowprotobufmodel【发布时间】:2016-06-0815:12:46【问题描述】:我正在尝试加载我在tensorflowandroid应用上训练自己的模型。我... 查看详情

将经过训练的 AWS SageMaker MXNet 模型部署/转换到 iOS 设备

】将经过训练的AWSSageMakerMXNet模型部署/转换到iOS设备【英文标题】:Deploy/converttrainedAWSSageMakerMXNetModeltoiOSdevices【发布时间】:2019-12-1318:18:13【问题描述】:我使用SageMaker对象检测算法训练了一个MXnetSSDresnet-50模型,并希望在iOS设... 查看详情

将本地训练的 TensorFlow 模型导入 Google Colab

】将本地训练的TensorFlow模型导入GoogleColab【英文标题】:ImportingLocallyTrainedTensorFlowModeltoGoogleColab【发布时间】:2022-01-0813:47:47【问题描述】:我正在GoogleMagenta(MusicVAE)上训练我自己的模型,我正在使用自己的音乐文件并在我的计... 查看详情

将 Keras 模型 HDF5 文件存储到 SQL 数据库

...网络模型。对于历史可追溯性,我想在数据库中保留每个训练模型(架构+权重+优化器状态)的副本。KeraswillexportanHDF5file包含有关模型的所有信息。有没有办法将此文件转换为可以存储在SQL 查看详情

C# - Emgu Cv - 人脸识别 - 将保存到 Access 数据库的人脸训练集作为二进制文件加载到 EigenObjectRecognizer 中以进行人脸识别

】C#-EmguCv-人脸识别-将保存到Access数据库的人脸训练集作为二进制文件加载到EigenObjectRecognizer中以进行人脸识别【英文标题】:C#-EmguCv-FaceRecognition-LoadingtrainingsetsofFacessavedtoAccessdatabaseasabinaryintoEigenObjectRecognizerforFacerecognition【发... 查看详情

在 pytorch 中为聊天机器人加载经过训练的模型保存

】在pytorch中为聊天机器人加载经过训练的模型保存【英文标题】:Loadthe,trainedmodelsave,inpytorchforchatbots【发布时间】:2021-07-1114:16:25【问题描述】:我运行了本教程的代码(link),学习了一段时间后模型就完成了,我和训练好的模... 查看详情

运行经过训练的机器学习模型时出错

】运行经过训练的机器学习模型时出错【英文标题】:GettingerroronrunningthetrainedMachineLearningmodel【发布时间】:2019-05-1601:56:44【问题描述】:我有一个包含“studentDetails”和“studentId”列的数据集。我在这个数据集上训练了我的模... 查看详情

在 android studio 中使用 chaquopy 加载模型 hdf5

...dio【发布时间】:2022-01-1420:10:01【问题描述】:我的朋友训练了1个模型hdf5,我想用chaquopy在androidstudio中加载该模型,但尽管尝试了很多方法,但还是失败了。我的代码是这样的,包括pickle和keras:importnumpyasnpim 查看详情

如何在 H2o 中保存/加载经过训练的模型?

】如何在H2o中保存/加载经过训练的模型?【英文标题】:howtosave/loadatrainedmodelinH2o?【发布时间】:2015-10-0922:05:47【问题描述】:用户教程说NavigatetoData>ViewAllChoosetofilterbythemodelkeyHitSaveModelInputforpath:/data/h2o-training/...HitSubmit问题... 查看详情

torch.load()使用方式

...e()保存的对象。api:参数:默认加载方式,使用cpu加载cpu训练得出的模型或者用gpu调用gpu训练的模型:将全部Tensor全部加载到cpu上:使用函数将所有张量加载到CPU(适用在GPU训练的模型在CPU上加载):将所有张量加载到第一块GPU... 查看详情

高效地为具有内存限制的神经网络训练创建 HDF5 图像数据集

】高效地为具有内存限制的神经网络训练创建HDF5图像数据集【英文标题】:EfficientlyCreateHDF5ImageDatasetforNeuralNetworkTrainingwithMemoryLimitations【发布时间】:2019-07-2915:02:49【问题描述】:我有大型图像数据集来训练CNN。由于我无法将... 查看详情

从 Keras 中经过训练的自动编码器模型中获取解码器

】从Keras中经过训练的自动编码器模型中获取解码器【英文标题】:GetdecoderfromtrainedautoencodermodelinKeras【发布时间】:2019-08-2219:22:48【问题描述】:我正在训练深度自动编码器将人脸映射到128维潜在空间,然后将它们解码回其原... 查看详情

如何将训练有素的 Tensorflow 模型转换为 Keras?

】如何将训练有素的Tensorflow模型转换为Keras?【英文标题】:HowcanIconvertatrainedTensorflowmodeltoKeras?【发布时间】:2017-11-1123:02:24【问题描述】:我有一个训练有素的Tensorflow模型和权重向量,它们已分别导出到protobuf和权重文件。如... 查看详情

如何将张量流模型转换为 keras 模型? .pb 文件到 .hdf5?

】如何将张量流模型转换为keras模型?.pb文件到.hdf5?【英文标题】:Howtoconverttensorflowmodeltokerasmodel?.pbfileto.hdf5?【发布时间】:2020-01-1823:50:27【问题描述】:我在谷歌上搜索了几个小时,但没有看到任何要转换的代码/包。对此的... 查看详情

将 hdf5 文件加载到 python xarrays

】将hdf5文件加载到pythonxarrays【英文标题】:Loadinghdf5filesintopythonxarrays【发布时间】:2019-07-0421:02:14【问题描述】:python模块xarray极大地支持加载/映射netCDF文件,甚至懒惰地使用dask。我必须使用的数据源是数以千计的hdf5文件,... 查看详情

如何保存经过训练的模型(估计器)并将其加载回来以使用 Tensorflow 中的数据对其进行测试?

】如何保存经过训练的模型(估计器)并将其加载回来以使用Tensorflow中的数据对其进行测试?【英文标题】:Howtosaveatrainedmodel(Estimator)andLoaditbacktotestitwithdatainTensorflow?【发布时间】:2017-04-0721:25:30【问题描述】:我的模型有这... 查看详情