TensorFlow.NET icon indicating copy to clipboard operation
TensorFlow.NET copied to clipboard

[BUG Report]:读取报错,.h5的模型

Open xdaker opened this issue 5 months ago • 2 comments

Description

读取.h5的模型报错:Tensorflow.Exceptions.NotOkStatusException: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for E:\aa\007005.h5\variables\variables at Tensorflow.Checkpoint.CheckpointReader..ctor(String filename) at Tensorflow.Checkpoint.TrackableSaver.restore(String save_path, CheckpointOptions options) at Tensorflow.Loader._restore_checkpoint() at Tensorflow.Loader..ctor(SavedObjectGraph object_graph_proto, SavedModel saved_model_proto, String export_dir, CheckpointOptions ckpt_options, LoadOptions save_options, IDictionary2 filters) at Tensorflow.Loader.<>c__DisplayClass45_1.<load_partial>b__3(NameScope x) at Tensorflow.Binding.tf_with[T](T py, Action1 action) at Tensorflow.Loader.load_partial(String export_dir, IDictionary2 filters, Object tags, LoadOptions options) at Tensorflow.Keras.Saving.SavedModel.KerasLoadModelUtils.load(String path, Boolean compile, LoadOptions options) at Tensorflow.Keras.Saving.SavedModel.KerasLoadModelUtils.load_model(String filepath, IDictionary2 custom_objects, Boolean compile, LoadOptions options) at Tensorflow.Keras.Models.ModelsApi.load_model(String filepath, Boolean compile, LoadOptions options)
保存模型的方法:
// 保存模型 Model?.save(MLNetModelPath); 读取模型方法: tf.keras.models.load_model(MLNetModelPath);;//在这里报错

是哪里有问题?还有我发现007005.h5文件夹下面有variables文件夹,但是并没有variables\variables文件夹,两个文件夹重复,是不是代码问题? 版本:TensorFlow.Keras 0.15.0

Reproduction Steps

No response

Known Workarounds

No response

Configuration and Other Information

No response

xdaker avatar Aug 21 '25 07:08 xdaker

///

/// 设置默认卷积神经网络 /// /// 输入步长 /// 特征数量 /// public Result SetDefaultLayers(int features,int outTimesteps) { return Misc.CatchException(() => { Model = new Sequential(new SequentialArgs()); Model.add(keras.Input(shape: new Shape(Parameter.InTimesteps, features)));

    Model.add(new Tensorflow.Keras.Layers.LSTM(new LSTMArgs()
    {
        Units = Parameter.InTimesteps * features * 10,
        RecurrentActivation = tf.keras.activations.Sigmoid,
        Activation = tf.keras.activations.Tanh,
        Name = "layer2",
        //InputShape = new Shape(10, 10),
        //ReturnState = false,
        //ReturnSequences = true,
    }));
    Model.add(new Dropout(new DropoutArgs()
    {
        Rate = 0.1f,
        Seed = DateTime.Now.Millisecond,
        Name = "layer3",
    }));

    Model.add(new Dense(new DenseArgs()
    {
        Units = outTimesteps,
        Activation = tf.keras.activations.Relu, // 显式声明线性激活
        Name = "layer4",
    }));

    return new Result(true);
});

}

xdaker avatar Aug 21 '25 12:08 xdaker

问题解决了,MLNetModelPath值是绝对路径,需要换成相对路径。但是读h5文件还原的模型,在预测上和刚训练出来的模型预测值不一样。不建议用Model?.save。推荐使用 Model.save_weights保存权重,后面在读权重,注意 Model.save_weights(文件名),参数填的是文件名称,不是文件路径

xdaker avatar Aug 21 '25 13:08 xdaker