使用先前获得的权重(.h5)加载模型

时间:2019-12-12 22:40:22

标签: python tensorflow keras

我正在尝试加载经过训练的神经网络模型,该模型另存为@page "/" @using System.Collections.Generic <h3>Display Customers</h3> <table class="table"> <thead> <tr> <th>CustomerID</th> <th>Customer Name</th> </tr> </thead> <tbody> @foreach (var acustomer in thecustomers) { <tr> <td>acustomer.CustomerID</td> <td>acustomer.CustomerName</td> </tr> } </tbody> </table> @code { List<Customer2> thecustomers = new List<Customer2>(); protected override void OnInitialized() { thecustomers.Add(new Customer2 { CustomerID = "123", CustomerName = "Any Company" }); thecustomers.Add(new Customer2 { CustomerID = "456", CustomerName = "Some Company" }); } public class Customer2 { public string CustomerID { get; set; } public string CustomerName { get; set; } } } 文件。

我定义了.h5save_model函数来保存和加载模型。

load_wght

然后,我的代码使用了def save_model(model,fName): ff = h5py.File(fName,'w') ww = model.get_weights() for i in range(len(ww)): ff.create_dataset('ww'+str(i),data=ww[i]) ff.close() def load_wght(fName): ff = h5py.File(fName,'r') ww = [] for i in range(len(ff.keys())): ww.append(ff['ww'+str(i)][:]) return ww

model

但是我遇到了错误

model = tf.keras.Sequential()

model.set_weights(load_wght("./models/my_model.h5"))

如何使用KeyError: "Unable to open object (object 'ww0' doesn't exist)" 检索保存的模型?

我认为我们在加载模型时不能使用model.set_weights(load_wght("./models/my_model.h5"))

我知道我们可以使用model = tf.keras.Sequential()和 使用model.save("model.h5")加载模型。

但是,由于我使用的是贝叶斯NN,因此需要使用用户定义的model = tf.keras.models.load_model('model.h5')save_model

0 个答案:

没有答案