且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何组合(合并)不同的回归模型

更新时间:2023-12-02 14:39:10

您可以使用 Functional API 来实现这一点.我添加了一个简单的示例,您可以根据您的用例将此示例调整为更复杂的模型.

You can use Functional API to achieve this. I have added a simple example you can adapt this example to more complicated models according to your usecase.

代码:

import tensorflow as tf
import numpy as np

# Here I have generated to different data and labels containing different number of features.
x1 = tf.constant(np.random.randint(50, size =(1000,13)), dtype = tf.float32)
y1 = tf.constant(np.random.randint(2, size =(1000,)), dtype = tf.int32)

x2 = tf.constant(np.random.randint(50, size =(1000,6)), dtype = tf.float32)
y2 = tf.constant(np.random.randint(2, size =(1000,)), dtype = tf.int32)

# Creation of model
def create_model3():
    input1 = tf.keras.Input(shape=(13,), name = 'I1')
    input2 = tf.keras.Input(shape=(6,), name = 'I2')
    
    hidden1 = tf.keras.layers.Dense(units = 4, activation='relu')(input1)
    hidden2 = tf.keras.layers.Dense(units = 4, activation='relu')(input2)
    hidden3 = tf.keras.layers.Dense(units = 3, activation='relu')(hidden1)
    hidden4 = tf.keras.layers.Dense(units = 3, activation='relu')(hidden2)
    output1 = tf.keras.layers.Dense(units = 2, activation='softmax', name ='O1')(hidden3)
    output2 = tf.keras.layers.Dense(units = 2, activation='softmax', name = 'O2')(hidden4)
    
    model = tf.keras.models.Model(inputs = [input1,input2], outputs = [output1,output2])
    
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    return model
model = create_model3()

tf.keras.utils.plot_model(model, 'my_first_model.png', show_shapes=True)

模型架构:

你可以像这样使用 model.fit() 训练这个模型:

You can train this model using model.fit() like this:

history = model.fit(
    x = {'I1':x1, 'I2':x2}, 
    y = {'O1':y1, 'O2': y2},
    batch_size = 32,
    epochs = 10,
    verbose = 1,
    callbacks = None,
#     validation_data = [(val_data,new_val_data),(val_labels, new_val_labels)]
)

注意:为了训练工作,所有输入数据中的样本数量应该相同.即 x1 包含 1000 行,所以 x2 也应该包含 1000 行.

Note: For training to work the number of samples in all your input data should be the same. ie x1 contains 1000 rows so x2 should also contain 1000 rows.

您可以像这样使用此模型进行预测:

You can predict using this model like this:

model.predict(x = {'I1':x1, 'I2':x2})