在Keras中自动更改一个模型会影响另一个模型

(这是我第一次提问!)我在Google Colab上工作。我对一个Resnet50模型进行了微调,并保存了权重。后来在测试过程中,我这样加载了模型权重:

res50 = keras.applications.ResNet50(weights= None, include_top=False, input_shape=(image_size, image_size, 3))# Create the modelmodel = Sequential()model.add(res50)model.add(Flatten())model.add(Dense(100, activation='relu'))model.add(Dropout(0.5))#0.75model.add(Dense(1, activation='sigmoid'))#softmax #to Sigmoidmodel.summary()new_model = model    new_model.load_weights('/content/drive/My Drive/model_weights.hdf5')model.compile(    optimizer=keras.optimizers.Adam(1e-4),#1e-6    loss="binary_crossentropy",    metrics=["accuracy"],)

请注意,在最后一块代码中,我编译的是’model’而不是’new_model’。然而,我发现’new_model’也被编译了。此外,我还注意到’model’的权重也被更新了,不仅仅是’new_model’。基本上,对其中一个进行任何更改都会影响另一个。这是为什么会发生这种情况?这是加载权重的正确方式吗?我对编程的理解非常基础。请帮助我。


回答:

问题在于你将new_model赋值为model的指针,因此new_modelmodel实际上引用的是同一个变量。

你可以通过创建一个辅助函数来解决这个问题,该函数生成具有所需结构的新模型:

def make_model(base_model):    model = Sequential()    model.add(base_model)    model.add(Flatten())    model.add(Dense(100, activation='relu'))    model.add(Dropout(0.5))#0.75    model.add(Dense(1, activation='sigmoid'))#softmax #to Sigmoid    return model

最后:

res50 = keras.applications.ResNet50(weights= None, include_top=False, input_shape=(image_size, image_size, 3))# Create the modelnew_model = make_model(base_model=res50)new_model.summary()  new_model.load_weights('/content/drive/My Drive/model_weights.hdf5')new_model.compile(    optimizer=keras.optimizers.Adam(1e-4),#1e-6    loss="binary_crossentropy",    metrics=["accuracy"],)

这样,如果将来你需要创建额外的模型并加载另一个模型的权重,你只需要这样做:

new_future_model = make_model(new_base_model)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注