简体   繁体   English

Tensorflow中多输入模型的优化

[英]Optimization of multiple inputs model in Tensorflow

I am working with medical data and trying to build a TF model with 2 inputs.我正在处理医疗数据并尝试构建具有 2 个输入的 TF 模型。
-The first input is a numpy array containing data about several Patient. - 第一个输入是一个 numpy 数组,其中包含有关多个患者的数据。 Some tests are made on each Patient regularly (eg check the weigth of the Patient).定期对每个患者进行一些测试(例如检查患者的体重)。 They will appear several times in my array.它们会在我的数组中出现多次。
-The second one is an image of the Patient lungs. - 第二张是患者肺部的图像。

Suppose I have 2 patients named Bob and Jean.假设我有两个名为 Bob 和 Jean 的患者。 Bob has been tested 3 times and Jean has been tested 2 times. Bob 已经测试了 3 次,Jean 已经测试了 2 次。 I will have 3 rows in the array for Bob and 2 rows for Jean.我将在数组中为 Bob 分配 3 行,为 Jean 分配 2 行。 But for each patient, I have only one picture.但是对于每个病人,我只有一张照片。 So in my DataGenerator, I will have to use this picture 3 times, for each row.因此,在我的 DataGenerator 中,对于每一行,我必须使用这张图片 3 次。
My first input would look like this:我的第一个输入看起来像这样:

['Name', 'Age', 'Weight']  
['Bob', 54, 80]  
['Bob', 55, 81]  
['Bob', 52, 79]  
['Jean', 40, 90]   
['Jean', 41, 88]  

And the second one like this:第二个是这样的:

Bob_img = 'Array representing the image of Bob lungs' 
Jean_img = 'Array representing the image of Jean lungs' 

[Picture_array]
[Bob_img]
[Bob_img]
[Bob_img]
[Jean_img]
[Jean_img]

I want to build a CNN to treat the image and then concatenate the output of the CNN with the numpy array.我想构建一个 CNN 来处理图像,然后将 CNN 的输出与 numpy 数组连接起来。 There is a repetition of images in my second input.我的第二个输入中有重复的图像。 It uses a lot of RAM and execute the same calculation on the CNN several times.它使用大量 RAM 并在 CNN 上多次执行相同的计算。 So I would like to know if there is any way to optimize it?所以我想知道有没有什么方法可以优化它?

The model is more complex than in the following code but you should have the idea with it.该模型比以下代码更复杂,但您应该对此有所了解。

image_input = K.Input(shape=(512, 512, 60,), name="img_input")
x = tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu')(image_input)
x = tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu')(x)
x = tf.keras.layers.MaxPool2D(pool_size=(2,2),strides=(2,2))(x)
cnn_output = tf.keras.layers.Flatten()(x)
    
numpy_input = K.Input(shape=(10,), name="numpy_input")
x = tf.keras.layers.concatenate([cnn_output, numpy_input], axis=1)
x = tf.keras.layers.Dense(32, activation='relu')(x)
x = tf.keras.layers.Dense(1, activation='relu')(x)

    
output= tf.keras.layers.Dense(1)(x)
    
model = K.Model(inputs=[image_input, numpy_input], outputs=output)

Plotting the model:绘制模型:

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

Link to Model模型链接

Finally found the answer: it is possible to implement the training from scratch.终于找到了答案:可以从头开始实施训练。 The solution is then to forward pass the CNN, then to contenate the CNN forward pass with tabular input and apply the forward pass of the second part of the NN.然后解决方案是前向传递 CNN,然后将 CNN 前向传递与表格输入连接起来,并应用 NN 的第二部分的前向传递。 Finally, I just need to apply the back propagation.最后,我只需要应用反向传播。 I put the link of the guide to write the training from scratch here .我把从头开始编写培训的指南链接放在这里 And my code if it can be useful:我的代码是否有用:

epochs = 1
for epoch in range(epochs):
    print("\nStart of epoch %d" % (epoch,))
    j=0

    # Iterate over the batches of the dataset.
    for [X1, X2], Y in generator:

        # Open a GradientTape to record the operations run
        # during the forward pass, which enables auto-differentiation.
        with tf.GradientTape() as tape:
            # Forward pass for CNN
            out_imgs = CNN(X2)
            # Replicate the forward pass in the same order than the numpy array
            patients = X1.loc[:, 'Patient'].unique()
            X_imgs = np.empty([X1.shape[0], out_imgs.shape[1]])
            for i in range(len(patients)):
                X_imgs[np.where(X1['Patient']==patients[i])] = out_imgs.numpy()[i]
            # Concatenate the forward pass with the numpy array
            inp_mlp = [tf.keras.layers.concatenate([0.1*X_imgs, np.asarray(X1[temp_SELECTED_COLUMNS])], axis=1)]
            # Forward pass of the second part of the layer
            for layer in model.layers[-3:]:
                inp_mlp.append(layer(inp_mlp[-1]))
            # Calculate loss
            loss = model.compiled_loss(tf.constant(Y), inp_mlp[-1], regularization_losses=model.losses)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 tensorflow model 的多个输入(数据集列表) - Multiple inputs(list of dataset) for tensorflow model 具有多个输入的 Keras 序列模型,Tensorflow 1.9.0 - Keras sequential model with multiple inputs, Tensorflow 1.9.0 TensorFlow model 多输入单 output - TensorFlow model with multiple inputs and single output Tensorflow model 具有多个输入 - Tensorflow model with multuple inputs 如何使用AWS Sagemaker托管的自定义Tensorflow模型的多个输入 - How to use multiple inputs for custom Tensorflow model hosted by AWS Sagemaker 如何在 Tensorflow 2.2 中使用多个输入训练 Keras model? - How to train Keras model with multiple inputs in Tensorflow 2.2? 将具有多个输入的 Tensorflow model 转换为 OpenVino IR 格式 - Convert Tensorflow model with multiple inputs to OpenVino IR format tensorflow.keras model 具有多个不同形状的输入(错误) - tensorflow.keras model with multiple inputs with different shapes (Error) (已解决)Tensorflow 联合 | tff.learning.from_keras_model() 与 model 与 DenseFeature 层和多个输入 - (SOLVED) Tensorflow Federated | tff.learning.from_keras_model() with a model with DenseFeature layer and multiple inputs 具有多个输入和目标的 Tensorflow 数据集 - Tensorflow dataset with multiple inputs and target
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM