【问题标题】:Changing one model automatically Changes another in keras自动更改一个模型 在 keras 中更改另一个
【发布时间】:2021-02-04 12:42:23
【问题描述】:

(这是我的第一个问题!) 我在谷歌 colab 工作。我在 keras 中微调了 Resnet50 模型并保存了权重。 现在,稍后在测试期间,我像这样加载模型权重:

res50 = keras.applications.ResNet50(weights= None, include_top=False, input_shape=(image_size, image_size, 3))

# Create the model
model = Sequential()

model.add(res50)

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

model.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'也被编译了。此外,我注意到“模型”的权重也更新了,而不仅仅是“新模型”。基本上对任何一个进行任何更改都会更改另一个。为什么会这样?这是加载重量的正确方法吗? 我对编程有非常基本的了解。请帮忙。

【问题讨论】:

    标签: machine-learning keras deep-learning neural-network google-colaboratory


    【解决方案1】:

    这里的问题是你给new_model分配了一个指向model的指针,所以基本上new_model和model引用的是同一个变量。

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

    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 model
    new_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)
    

    【讨论】:

    • 谢谢。我能问一下,为什么这是一个指针?如果我们简单地写成:''' x =2, y=x, y=y+1。 ''' x 仍然是 2,对吧?
    • 这个答案可能会帮助你解决这个问题:stackoverflow.com/a/986145/11050000
    • 基本上,您的 keras 模型是一个可变对象,因此它的赋值会产生对原始对象(在您的情况下为模型)的引用
    猜你喜欢
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    相关资源
    最近更新 更多