如何绕过张量流中的部分神经网络来获得某些(但不是全部)特征

2024-04-27 12:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的TensorFlow模型中,我有一些数据,在它进入几个完全连接的层之前,我把它们输入一堆CNN。我已经用Keras的Sequential模型实现了这一点。但是,我现在有一些数据不应该进入CNN,而是直接输入到第一个完全连接的层,因为该数据包含一些值和标签,这些值和标签是输入数据的一部分,但是该数据不应该进行卷积,因为它不是图像数据。你知道吗

这样的事情在tensorflow.keras中可能发生吗?或者我应该用tensorflow.nn来做吗?据我所知,Keras的“{a1}”是指输入端一端进入另一端,中间没有特殊的布线。你知道吗

要做到这一点,我必须对最后一个CNN层的数据和绕过CNN的数据使用tensorflow.concat,然后再将其送入第一个完全连接的层,对吗?你知道吗


Tags: 数据模型图像tensorflowa1nn标签事情
2条回答

通过稍加改造和功能API,您可以:

#create the CNN - it can also be a sequential
cnn_input = Input(image_shape)
cnn_output = Conv2D(...)(cnn_input)
cnn_output = Conv2D(...)(cnn_output)
cnn_output = MaxPooling2D()(cnn_output)
....

cnn_model = Model(cnn_input, cnn_output)

#create the FC model - can also be a sequential
fc_input = Input(fc_input_shape)
fc_output = Dense(...)(fc_input)
fc_output = Dense(...)(fc_output)

fc_model = Model(fc_input, fc_output)

创意空间很大,这只是其中一种方式。你知道吗

#create the full model
full_input = Input(image_shape)
full_output = cnn_model(full_input)
full_output = fc_model(full_output)

full_model = Model(full_input, full_output)

你可以任意使用这三种型号中的任何一种。它们共享层和权重,因此在内部它们是相同的。你知道吗

保存和加载完整的模型可能很奇怪。我可能会分别保存另外两个,然后在加载时再次创建完整模型。你知道吗

另请注意,如果保存共享同一层的两个模型,则加载后它们可能不再共享这些层。(另一个只保存/加载fc_modelcnn_model,同时从代码中再次创建full_model的原因)

下面是一个简单的示例,其中的操作是将来自不同子网的激活相加:

import keras
import numpy as np
import tensorflow as tf
from keras.layers import Input, Dense, Activation

tf.reset_default_graph()

# this represents your cnn model 
def nn_model(input_x):
    feature_maker = Dense(10, activation='relu')(input_x)
    feature_maker = Dense(20, activation='relu')(feature_maker)
    feature_maker = Dense(1, activation='linear')(feature_maker)
    return feature_maker

# a list of input layers, of course the input shapes can be different
input_layers = [Input(shape=(3, )) for _ in range(2)]
coupled_feature = [nn_model(input_x) for input_x in input_layers]

# assume you take the sum of the outputs 
coupled_feature = keras.layers.Add()(coupled_feature)
prediction = Dense(1, activation='relu')(coupled_feature)

model = keras.models.Model(inputs=input_layers, outputs=prediction)
model.compile(loss='mse', optimizer='adam')

# example training set
x_1 = np.linspace(1, 90, 270).reshape(90, 3)
x_2 = np.linspace(1, 90, 270).reshape(90, 3)
y = np.random.rand(90)

inputs_x = [x_1, x_2]

model.fit(inputs_x, y, batch_size=32, epochs=10)

你可以绘制模型来获得更多的直觉

from keras.utils.vis_utils import plot_model

plot_model(model, show_shapes=True)

上面代码的模型如下所示

model

相关问题 更多 >