【问题标题】:How to add a second input argument (the first is an image) to a CNN model built with Keras?如何向使用 Keras 构建的 CNN 模型添加第二个输入参数(第一个是图像)?
【发布时间】:2018-11-20 20:17:59
【问题描述】:

假设我有一个从 Instagram 下载的 图像(转换为 numpy 数组)列表,以及它们对应的和用户关注者 .假设我有一个 CNN 模型(在 Tensorflow 上使用 Keras),我在这些图像(200x200x3 numpy 数组)上进行训练,它试图预测一张图片将获得的赞数

如果我想为这个模型提供每个图像对应的关注者作为第二个输入

这是我目前的代码:

IMAGESIZE = (200, 200)

def create_model():
    # create model and add layers
    model = Sequential()

    model.add(Conv2D(10, 5, 5, activation='relu',
                     input_shape=(IMAGESIZE[0], IMAGESIZE[1], 3)))

    model.add(Conv2D(10, 5, 5, activation='relu'))
    model.add(MaxPool2D((5, 5)))
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(50))
    model.add(Activation('relu'))
    model.add(Dense(1))

    print(model.summary())

    model.compile(loss='mse',
                  optimizer='rmsprop', metrics=["accuracy"])
    return model

# Read the likes
likes = getlikes(src='../data/pickledump')
likesraw = np.array(likes)
likes = (likesraw - np.mean(likesraw))/np.std(likesraw)  # normalize

# Read the images and resize them
images = []
for imgfile in glob.glob('../data/download/*.jpeg'):
    img = cv2.imread(imgfile)
    resized = cv2.resize(img, IMAGESIZE)
    images.append(resized)
    break
images = np.array(images)

# Read the followers
followers= getfollowers(src='../data/pickledump')
followersraw= np.array(followers)
followers= (followersraw- np.mean(followersraw))/np.std(followersraw)  # normalize

classifier = KerasClassifier(build_fn=create_model, epochs=20)
print("Accuracy (Cross Validation=10): ",
      np.mean(cross_val_score(classifier, images, likes, cv=2)))

【问题讨论】:

    标签: python tensorflow machine-learning keras conv-neural-network


    【解决方案1】:

    一种方法是使用双分支模型,其中一个分支处理图像,另一个分支处理其他非图像输入(例如帖子文本或关注者和关注者的数量等)。然后您可以合并这两个分支的结果,并可能在之后添加一些其他层来充当最终的分类器/回归器。要在 Keras 中构建这样的模型,您需要改用 functional API。只是为了演示,这里是一个例子:

    inp_img = Input(shape=image_shape)
    inp_others = Input(shape=others_shape)
    
    # branch 1: process input image
    x = Conv2D(...)(inp_img)
    x = Conv2D(...)(x)
    x = MaxPool2D(...)(x)
    out_b1 = Flatten()(x)
    
    # branch 2: process other input
    out_b2 = Dense(...)(inp_other)
    
    
    # merge the results by concatenation
    merged = concatenate([out_b1, out_b2])
    
    # pass merged tensor to some other layers
    x = Dense(...)(merged)
    output = Dense(...)(x)
    
    # build the model and compile it
    model = Model([inp_img, inp_other], output)
    model.compile(...)
    
    # fit on training data
    model.fit([img_array, other_array], label_array, ...)
    

    请注意,我们在上面使用了concatenation 层,但是您可以使用其他merge layers。并确保您阅读了functional API guide,这是一本必读指南。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      相关资源
      最近更新 更多