python - How to concatenate two models in keras?
问题描述
I wanted to use this model but we cannot use merge anymore.
image_model = Sequential([
Dense(embedding_size, input_shape=(2048,), activation='relu'),
RepeatVector(max_len)
])
caption_model = Sequential([
Embedding(vocab_size, embedding_size, input_length=max_len),
LSTM(256, return_sequences=True),
TimeDistributed(Dense(300))
])
final_model = Sequential([
Merge([image_model, caption_model], mode='concat', concat_axis=1),
Bidirectional(LSTM(256, return_sequences=False)),
Dense(vocab_size),
Activation('softmax')
])
i rewrote this in following way,excluding final_model:
image_in = Input(shape=(2048,))
caption_in = Input(shape=(max_len, vocab_size))
merged = concatenate([image_model(image_in), caption_model(caption_in)],axis=0)
latent = Bidirectional(LSTM(256, return_sequences=False))(merged)
out = Dense(vocab_size, activation='softmax')(latent)
final_model = Model([image_in, caption_in], out)
final_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])
final_model.summary()
This also gave me:
ValueError: "input_length" is 40, but received input has shape (None, 40, 8256).
Can anyone help to fix it? source:https://github.com/yashk2810/Image-Captioning/blob/master/Image%20Captioning%20InceptionV3.ipynb
解决方案
you should define the caption_in as 2D: Input(shape=(max_len,))
. in your case, the concatenation must be operated on the last axis: axis=-1
. the rest seems ok
embedding_size=300
max_len=40
vocab_size=8256
image_model = Sequential([
Dense(embedding_size, input_shape=(2048,), activation='relu'),
RepeatVector(max_len)
])
caption_model = Sequential([
Embedding(vocab_size, embedding_size, input_length=max_len),
LSTM(256, return_sequences=True),
TimeDistributed(Dense(300))
])
image_in = Input(shape=(2048,))
caption_in = Input(shape=(max_len,))
merged = concatenate([image_model(image_in), caption_model(caption_in)],axis=-1)
latent = Bidirectional(LSTM(256, return_sequences=False))(merged)
out = Dense(vocab_size, activation='softmax')(latent)
final_model = Model([image_in, caption_in], out)
final_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])
final_model.summary()
推荐阅读
- php - laravel 中奇怪的 API 路由错误,一条路线正常工作,另一条路线显示 404 用于同一目的地
- powerbi - 如何将 Power BI 报表发布到网站
- node.js - 我应该在哪个文件夹中安装我的 socket.io 应用程序?
- swift - NSTableView / Cocoa - 具有表宽部分行的多列表
- powershell - 无法安装 Chocolatey Windows 10(新对象错误)PowerShell
- kubernetes - 将 Kubernetes pod 缩放偏移一秒
- elasticsearch - Elasticsearch 7.5.3 RequestError(400, 'parse_exception', 'numeric value expected') 执行地理多边形查询
- arrays - Python 嵌套 For 循环增强可能吗?
- hpc - 混淆 HPC 和普通计算机之间的差异
- c# - CSVHelper 不同编码的文件