婴儿版训练GPT

import numpy as np

==============================

1. 固定词典(你建立的字典)

==============================

vocab = {"我":0, "喜":1, "欢":2, "中":3, "国":4, "美":5, "食":6, "END":7}

idx2word = {v:k for k,v in vocab.items()}

vocab_size = len(vocab)

d_model = 8 # 向量维度

lr = 0.1 # 学习率(训练步长)

==============================

2. 初始化所有矩阵!【随机,但会被训练】

==============================

np.random.seed(42) # 固定初始随机值,方便看效果

embedding = np.random.randn(vocab_size, d_model) # 嵌入矩阵

Wq = np.random.randn(d_model, d_model) # 注意力Q

Wk = np.random.randn(d_model, d_model) # 注意力K

Wv = np.random.randn(d_model, d_model) # 注意力V

output_layer = np.random.randn(d_model, vocab_size) # 输出层

==============================

3. 定义 softmax(稳定版)

==============================

def softmax(x):

exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True))

return exp_x / np.sum(exp_x, axis=-1, keepdims=True)

==============================

4. 【核心】前向传播(模型预测)

==============================

def forward(input_ids):

字 → 向量

x = embeddinginput_ids

自注意力

Q = x @ Wq

K = x @ Wk

V = x @ Wv

scores = Q @ K.T / np.sqrt(d_model)

attn_weights = softmax(scores)

attn_out = attn_weights @ V

取最后一个token → 预测下一个字

last_vec = attn_out-1

logits = last_vec @ output_layer

probs = softmax(logits)

return x, Q, K, V, scores, attn_weights, attn_out, last_vec, logits, probs

==============================

5. 【核心】训练!反向传播(调参)

让模型从错误中学习

==============================

def train(input_ids, target_id):

global embedding, Wq, Wk, Wv, output_layer

1. 前向预测

x, Q, K, V, scores, attn_weights, attn_out, last_vec, logits, probs = forward(input_ids)

2. 计算误差(预测值 - 真实值)

loss = -np.log(probstarget_id + 1e-10) # 损失越小越准

3. 反向更新所有矩阵(学习过程)

grad_logits = probs.copy()

grad_logitstarget_id -= 1

更新输出层

grad_output_layer = np.outer(last_vec, grad_logits)

output_layer -= lr * grad_output_layer

更新注意力 & 嵌入层(简化版,让模型能学到)

grad_last = grad_logits @ output_layer.T

embeddinginput_ids\[-1] -= lr * grad_last

return loss, probs

==============================

6. 开始训练!

输入:我喜欢中国 → 目标:输出 美(ID=5)

==============================

input_text = "我喜欢中国"

input_ids = vocab\[c for c in input_text]

target_id = 5 # 正确答案:美

print("===== 开始训练(越训练,越准)=====\n")

for step in range(200): # 训练200次

loss, probs = train(input_ids, target_id)

pred_id = np.argmax(probs)

pred_word = idx2wordpred_id

true_word = idx2wordtarget_id

每10步打印一次

if step % 10 == 0:

print(f"训练步数 {step:3d} | 损失:{loss:.4f} | 预测:{pred_word} | 正确:{true_word}")

==============================

训练完成,最终测试

==============================

print("\n===== 训练完成!最终预测 =====")

_, _, _, _, _, _, _, _, _, probs = forward(input_ids)

pred_id = np.argmax(probs)

pred_word = idx2wordpred_id

print(f"输入:{input_text}")

print(f"模型预测下一个字:【 {pred_word} 】")

print("? 训练成功!模型学会了!")

相关推荐
2401_8734794010 分钟前
IP属地为什么有时显示外省?用IP查询工具核查动态分配、运营商出口与GeoIP库
python·tcp/ip·ip
OKkankan2 小时前
LangChain 能力详解!:输出解析、RAG、向量数据库与 Retriever 检索器
数据结构·python·langchain·ai应用
龙腾AI白云2 小时前
孪生不止在工厂:能源、医疗与农业
人工智能·机器学习·scikit-learn·知识图谱
YFJ_mily3 小时前
9.24早鸟通道即将关闭|IMRA2026智能制造机器人自动化IEEE会议|往届EI稳定检索,设有学生专属投稿权益
人工智能·机器学习·机器人·自动化·智能制造·rdlink研发家·马鞍山会议
山哥ol3 小时前
【Geany 环境配置与中文乱码解决参考】
python
renhongxia13 小时前
数字孪生不止在工厂:能源、医疗与农业
人工智能·深度学习·算法·机器学习·数字孪生
会飞锦鲤3 小时前
基于 Mask R-CNN 的药片缺陷检测系统
人工智能·pytorch·python·神经网络·resnet-50
默 语3 小时前
Java新手入门:从零开始安装JDK并配置环境变量
java·开发语言·python·mysql·group by·1024程序员节·数据去重
清水白石0084 小时前
Python 异步编程深度解析:Cancellation 到底是异常还是控制信号?从 asyncio 取消机制到企业级事务设计最佳实践
开发语言·python
Patrick在香港4 小时前
Python 审计香港开放数据目录:两个端点差 10 倍,只有 9.3% 的资源标了「最后修改时间」
开发语言·数据库·python·数据分析·api·数据治理·开放数据