多模态与 AIGC:用 TensorFlow 构建图文 / 语音 / 视频生成模型
🎯 本章目标
- 了解主流 AIGC 多模态模型架构(图像、语音、视频)
- 构建文本生成模型(GPT-like)
- 构建图文生成模型(图像 Caption / Text-to-Image)
- 构建文本转语音模型(TTS Tacotron2 / FastSpeech2)
- 构建视频生成模型思路(AutoRegressive + Diffusion)
- 实战:用 TensorFlow 构建一个图像 Caption 模型,并导出部署
一、AIGC 多模态发展全景
| 类型 | 输入 | 输出 | 常用模型 |
|---|---|---|---|
| 文本生成 | 文本 | 文本 | GPT, BERT, LLaMA |
| 图文生成 | 图像/文本 | 文本/图像 | BLIP, Flamingo, CLIP, DALL·E |
| 语音生成 | 文本 | 音频 | Tacotron2, FastSpeech, VITS |
| 视频生成 | 文本 | 视频 | VideoDiffusion, AnimateDiff |
| 多模态对齐 | 图 + 文 | 向量 | CLIP, BLIP2 |
二、构建文本生成模型(GPT结构)
我们以一个 Mini GPT Decoder 结构构建为例(AutoRegressive 单向模型):
class MiniGPT(tf.keras.Model):
def __init__(self, vocab_size, max_len, d_model=256, num_heads=8, num_layers=4):
super().__init__()
self.embedding = tf.keras.layers.Embedding(vocab_size, d_model)
self.pos_enc = positional_encoding(max_len, d_model)
self.dec_layers = [DecoderLayer(d_model, num_heads, d_model*4) for _ in range(num_layers)]
self.final = tf.keras.layers.Dense(vocab_size)
def call(self, x, mask):
seq_len = tf.shape(x)[1]
x = self.embedding(x) + self.pos_enc[:, :seq_len, :]
for dec in self.dec_layers:
x = dec(x, mask)
return self.final(x)
- 自回归预测下一 token(训练阶段使用
teacher forcing) - 推理阶段需逐 token 生成(可使用 greedy / sampling / beam search)
三、图文生成模型示例(图像 Caption)
✅ 架构:
图像(CNN) → Encoder (resnet50)
文本 → Decoder(Transformer)
训练目标:给定图像特征,生成描述性文本
✅ 示例代码:
# 图像编码器
def build_cnn_encoder():
base_model = tf.keras.applications.ResNet50(include_top=False, weights='imagenet')
base_model.trainable = False
model = tf.keras.Model(inputs=base_model.input, outputs=base_model.layers[-1].output)
return model
# 文本解码器
class ImageCaptionDecoder(tf.keras.Model):
def __init__(self, vocab_size, d_model):
super().__init__()
self.embedding = tf.keras.layers.Embedding(vocab_size, d_model)
self.attn = MultiHeadAttention(d_model, 8)
self.ffn = tf.keras.Sequential([
tf.keras.layers.Dense(d_model, activation='relu'),
tf.keras.layers.Dense(vocab_size)
])
def call(self, img_feat, caption_input):
x = self.embedding(caption_input)
context = self.attn(x, img_feat, img_feat, mask=None)
x = self.ffn(context + x)
return x
训练时目标是:输入图像 + 前缀文本,预测下一个 token。
四、语音生成模型:Tacotron2 简化版结构
文本输入(词向量) →
Encoder →
Attention →
Decoder(生成梅尔频谱) →
Vocoder(Griffin-Lim / WaveGlow) →
音频输出
✅ 可用预训练模型:
-
TensorFlowTTS:支持 Tacotron2, FastSpeech2, MB-MelGAN - 示例生成:
from tensorflow_tts.inference import AutoProcessor, TFAutoModel
processor = AutoProcessor.from_pretrained("tensorspeech/tts-tacotron2-ljspeech-en")
tacotron2 = TFAutoModel.from_pretrained("tensorspeech/tts-tacotron2-ljspeech-en")
mel_outputs, _, _ = tacotron2.inference(input_ids=tf.constant([[1, 23, 45, 3]]))
可配合 vocoder(如 MB-MelGAN)转为 wave 文件。
五、视频生成模型(探索)
目前主流方向:
| 类型 | 架构 | 特点 |
|---|---|---|
| Diffusion | 文本 + 时序 noise 去除器 | 视频版 Stable Diffusion |
| AutoRegressive | 每帧逐帧生成 + 光流补帧 | 有清晰度问题 |
| GAN + 3D Conv | 像素级建模 | 难以训练,效果一般 |
TensorFlow 社区尚未完善视频生成流水线,建议结合:
六、实战:用 TensorFlow 构建图像 Caption 模型并部署
✅ 输入:
- 图像文件(.jpg/.png)
- 输出:自然语言描述
✅ 推理流程:
img_feat = cnn_encoder(preprocess(img_input)) # shape: [1, 49, 2048]
caption_input = tf.constant([[tokenizer.bos_id]])
for _ in range(max_len):
logits = decoder(img_feat, caption_input)
next_token = tf.argmax(logits[:, -1, :], axis=-1)
caption_input = tf.concat([caption_input, tf.expand_dims(next_token, 1)], axis=-1)
if next_token == tokenizer.eos_id:
break
✅ 导出部署:
@tf.function(input_signature=[tf.TensorSpec(shape=[None, None, 3], dtype=tf.float32)])
def caption_model(img_tensor):
feat = cnn_encoder(img_tensor)
caption = decoder(feat, tf.constant([[tokenizer.bos_id]]))
return caption
tf.saved_model.save(model, "caption_model")
可以用:
- TensorFlow Serving 部署
- 转换为
TF.js网页 caption 模型
✅ 本章小结
| 任务 | 推荐结构 | 可用框架 |
|---|---|---|
| 文本生成 | GPT/BERT Decoder | HuggingFace + Keras |
| 图文生成 | CNN + Transformer | 自建或用 BLIP/BERTVision |
| 语音合成 | Tacotron2 / FastSpeech | TensorFlowTTS |
| 视频生成 | Diffusion 或 Flow-GAN | DiffusionLib, keras-cv |
文章来源于互联网:多模态与 AIGC:用 TensorFlow 构建图文 / 语音 / 视频生成模型
毕业季,论文写作是每位毕业生的“必经之路”。从选题到成稿,从格式规范到降重优化,每一步都充满了挑战。但别担心,AI写作工具来帮忙!以下为您推荐几款强大的AI写作工具,助您轻松完成论文写作。 一、ailisipaper:学术写作的智能伙伴 ailisipaper…
5bei.cn大模型教程网










