gpt4 book ai didi

machine-learning - keras 结合预训练模型

转载 作者:行者123 更新时间:2023-11-30 08:28:55 25 4
gpt4 key购买 nike

我训练了一个模型,并希望使用功能 API 将其与另一个 keras 模型结合起来(后端是 TensorFlow 版本 1.4)

我的第一个模型如下所示:

import tensorflow.contrib.keras.api.keras as keras

model = keras.models.Sequential()
input = Input(shape=(200,))
dnn = Dense(400, activation="relu")(input)
dnn = Dense(400, activation="relu")(dnn)
output = Dense(5, activation="softmax")(dnn)
model = keras.models.Model(inputs=input, outputs=output)

训练完这个模型后,我使用 keras model.save() 方法保存它。我还可以毫无问题地加载模型并重新训练它。

现在我想使用该模型的输出作为第二个模型的附加输入:

# load first model
old_model = keras.models.load_model(path_to_old_model)

input_1 = Input(shape=(200,))
input_2 = Input(shape=(200,))
output_old_model = old_model(input_2)

merge_layer = concatenate([input_1, output_old_model])
dnn_layer = Dense(200, activation="relu")(merge_layer)
dnn_layer = Dense(200, activation="relu")(dnn_layer)
output = Dense(10, activation="sigmoid")(dnn_layer)
new_model = keras.models.Model(inputs=[input_1, input_2], outputs=output)
new_model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
new_model.fit(inputs=[x1,x2], labels=labels, epochs=50, batch_size=32)

当我尝试此操作时,我收到以下错误消息:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value dense_1/kernel
[[Node: dense_1/kernel/read = Identity[T=DT_FLOAT, _class=["loc:@dense_1/kernel"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](dense_1/kernel)]]
[[Node: model_1_1/dense_3/BiasAdd/_79 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_68_model_1_1/dense_3/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

最佳答案

我将按照以下步骤执行此操作:

  1. 定义用于构建具有相同架构的干净模型的函数:

    def build_base():
    input = Input(shape=(200,))
    dnn = Dense(400, activation="relu")(input)
    dnn = Dense(400, activation="relu")(dnn)
    output = Dense(5, activation="softmax")(dnn)
    model = keras.models.Model(inputs=input, outputs=output)
    return input, output, model
  2. 构建同一模型的两个副本:

    input_1, output_1, model_1 = build_base()
    input_2, output_2, model_2 = build_base()
  3. 在两个模型中设置权重:

    model_1.set_weights(old_model.get_weights())
    model_2.set_weights(old_model.get_weights())
  4. 现在做剩下的事情:

    merge_layer = concatenate([input_1, output_2])
    dnn_layer = Dense(200, activation="relu")(merge_layer)
    dnn_layer = Dense(200, activation="relu")(dnn_layer)
    output = Dense(10, activation="sigmoid")(dnn_layer)
    new_model = keras.models.Model(inputs=[input_1, input_2], outputs=output)

关于machine-learning - keras 结合预训练模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48308306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com