如何将第二个输入参数(第一个是图像)添加到用Keras构建的CNN模型中?

2024-09-28 21:32:42 发布

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

假设我有一个从Instagram下载的图像列表(转换成numpy数组),以及相应的喜欢的和用户追随者。假设我有一个CNN模型(使用Tensorflow上的Keras),我对这些图像(200x200x3numpy数组)进行训练,它试图预测一张图像将得到的像数。你知道吗

如果我想把每个图像对应的追随者作为第二个输入给这个模型怎么办?你知道吗

这是我目前的代码:

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)))

Tags: the图像addreaddatamodelcreatenp
1条回答
网友
1楼 · 发布于 2024-09-28 21:32:42

一种方法是使用双分支模型,其中一个分支处理图像,另一个分支处理其他非图像输入(例如帖子文本或关注者和关注者的数量等)。然后您可以合并这两个分支的结果,并可能在之后添加一些其他层,以充当最终分类器/回归器的角色。要在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,这是必读指南。你知道吗

相关问题 更多 >