GPT(Generative Pre-trained Transformer,生成式预训练 Transformer)是由 OpenAI 开发的基于 Transformer 解码器(Decoder) 的 自回归(Autoregressive)语言模型。
它能够通过 大量无监督数据预训练,然后 微调(Fine-tuning) 以适应特定任务,如 文本生成、对话系统、代码生成等。
✅ 基于 Transformer 结构:使用 多层自注意力(Self-Attention) 机制建模文本序列。
✅ 单向(左到右)训练:不同于 BERT 的 双向编码,GPT 仅使用 前向信息 进行预测。
✅ 自回归(Autoregressive)生成:通过 逐步预测下一个词 来生成文本。
✅ 大规模预训练 + 任务微调:先在 海量数据上预训练,再微调以适应具体应用。
GPT 采用 Transformer 解码器,其核心包括:
GPT 主要版本
版本 | 参数量 | 主要特点 |
---|---|---|
GPT-1 (2018) | 1.17 亿 | 仅用于 NLP 任务 |
GPT-2 (2019) | 15 亿 - 175 亿 | 更强大的文本生成能力 |
GPT-3 (2020) | 1,750 亿 | 可用于翻译、对话、代码生成等 |
GPT-4 (2023) | 兆级参数 | 多模态能力(支持图像+文本) |
GPT 采用两阶段训练:
预训练(Pre-training)
The cat sat on the
目标:预测 "mat"
。微调(Fine-tuning)
✅ 使用 Hugging Face 运行 GPT
from transformers import GPT2LMHeadModel, GPT2Tokenizer
# 加载 GPT-2 预训练模型和分词器
model = GPT2LMHeadModel.from_pretrained("gpt2")
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
# 输入文本
input_text = "Artificial Intelligence is transforming the world" # 输入文本
inputs = tokenizer(input_text, return_tensors="pt") # 输入文本转换为模型输入
# 生成文本
output = model.generate(**inputs, max_length=50) # 生成长度为50的文本
print(tokenizer.decode(output[0], skip_special_tokens=True)) # 输出文本
输出示例:
Artificial Intelligence is transforming the world.
The world is changing.
The world is changing.
The world is changing.
The world is changing.
The world is changing.
The world is changing.
✅ GPT 进行问答
from transformers import pipeline
# 加载 GPT-2 进行问答任务
qa_pipeline = pipeline("text-generation", model="gpt2")
# 生成回答
response = qa_pipeline("What is the capital of France?", max_length=30)
print(response[0]["generated_text"])
输出:
What is the capital of France? How has Greece been governed? In short, what is its future? We will see what the French leadership stands for
模型 | 架构 | 训练方式 | 主要用途 |
---|---|---|---|
GPT | Transformer Decoder | 单向学习(左到右) | 主要用于 文本生成(如 ChatGPT) |
BERT | Transformer Encoder | 双向学习(MLM + NSP) | 适用于 NLP 任务(分类、问答、NER) |
✅ ChatGPT(聊天机器人)
✅ 代码生成(如 GitHub Copilot)
✅ 自动文本摘要
✅ 机器翻译
✅ 创意写作(小说、诗歌)
✅ 问答系统
GPT 已成为 AI 发展的重要推动力,特别是在 ChatGPT、自动写作和代码生成等应用中大放异彩!