写给零基础 · 每个词都有解释 · 无需注册
完全不懂 AI?没关系。这里有 15 节课:每节课先讲人话、配漫画、遇到的每个生词都能点开看解释,最后动手跑一个实验。跟着顺序学就行。
怎么学
完全零基础就按数字顺序学。第 4、5 板块用到前面的知识,建议不要跳。每个单元 60-90 分钟:看讲解 → 看漫画 → 记要点 → 跑实验。
板块 01
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# 复制到任意 Python 环境跑(https://colab.research.google.com 免安装) import numpy as np np.random.seed(42) x = np.array([0.2, 0.9, -0.4]) # 一个"词"的嵌入(3 个数字) W = np.random.randn(3, 3) * 0.5 # 一张"权重表"(3×3 共9个数字) y = x @ W + 0 # 乘法加法,得到新的 3 个数字 print("词变成:", y.round(3))
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# 让模型自己找出 y = 3x + 2 里的 3 和 2 import numpy as np x = np.linspace(-1, 1, 50) y_true = 3 * x + 2 + np.random.normal(0, 0.1, 50) w, b, lr = 0.0, 0.0, 0.5 # 从"啥都不会"开始 for step in range(100): y_pred = w * x + b loss = np.mean((y_pred - y_true) ** 2) dw = 2 * np.mean((y_pred - y_true) * x) db = 2 * np.mean(y_pred - y_true) w -= lr * dw; b -= lr * db # 顺着箭头反方向改 if step % 20 == 0: print(f"第{step:3d}步 loss {loss:.4f} w {w:.3f} b {b:.3f}") print("找到答案: w=%.3f b=%.3f(真值是 3 和 2)" % (w, b))
开场白 · 分步讲解 · 漫画 · 术语 · 实验
import numpy as np
logits = np.array([2.1, 1.4, 0.6, 0.1, -1.2]) # 5 个候选词的分数
def softmax_with_t(z, T):
z = z / T
e = np.exp(z - z.max())
return e / e.sum()
for T in [0.2, 1.0, 3.0]:
p = softmax_with_t(logits, T)
print(f"温度 T={T}: " + " ".join(f"{v:.2f}" for v in p))
板块 02
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# pip install tiktoken
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
zh = "人工智能正在改变世界"
en = "AI is changing the world"
print("中文 token 数:", len(enc.encode(zh)))
print("英文 token 数:", len(enc.encode(en)))
开场白 · 分步讲解 · 漫画 · 术语 · 实验
import numpy as np
def attention(Q, K, V):
d = Q.shape[-1]
scores = Q @ K.T / np.sqrt(d) # Q 找 K 配对打分
w = np.exp(scores - scores.max(axis=-1, keepdims=True))
w = w / w.sum(axis=-1, keepdims=True) # softmax 归一
return w @ V, w # 按权重取内容
np.random.seed(0)
X = np.random.randn(4, 8) # 4 个词,各 8 个数字
Q = X @ np.random.randn(8, 8); K = X @ np.random.randn(8, 8); V = X @ np.random.randn(8, 8)
out, weights = attention(Q, K, V)
print("每个词对其他词的关注度(每行=一个词):")
print(weights.round(2))
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# 装 ollama 后跑(免费本地) # ollama pull qwen2.5:0.5b-instruct # 走完三阶段的成品 # ollama pull qwen2.5:0.5b # 只预训练过的"原始版" # 分别运行 ollama run <模型名>,输入:你好,介绍一下你自己 # 你会发现:instruct 版正常聊天;原始版只会"接话续写"
板块 03
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# 打开任意 AI 聊天工具(ChatGPT/DeepSeek/Kimi…)直接试: # 问法 A(模糊): # "总结这段文字。" # 问法 B(结构化): # "你是一位资深编辑。任务:把以下文字压缩成 3 条要点。 # 约束:每条不超过 20 字,按重要性排序,只输出列表。 # 文字:<粘贴你的内容>"
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# 需要任意 OpenAI 兼容 API(你的 KEY)
import openai
client = openai.OpenAI(base_url="你的BASE_URL", api_key="你的KEY")
tools = [{"type": "function", "function": {
"name": "get_weather",
"description": "查询城市天气",
"parameters": {"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]}}}]
resp = client.chat.completions.create(
model="gpt-4o-mini", tools=tools,
messages=[{"role": "user", "content": "深圳今天适合跑步吗?"}])
msg = resp.choices[0].message
if msg.tool_calls:
c = msg.tool_calls[0].function
print("AI 请求调用:", c.name, "参数:", c.arguments)
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# pip install chromadb sentence-transformers
import chromadb
from sentence_transformers import SentenceTransformer
emb = SentenceTransformer("BAAI/bge-small-zh-v1.5")
db = chromadb.Client().create_collection("kb")
docs = ["深圳康泰创新广场在南山科技园附近",
"深圳地铁 1 号线经过深大站",
"华为康泰创新广场楼下有肯德基"]
for i, d in enumerate(docs):
db.add(ids=[str(i)], documents=[d], embeddings=[emb.encode(d).tolist()])
q = "肯德基在哪?"
hits = db.query(query_embeddings=[emb.encode(q).tolist()], n_results=1)
print("检索到:", hits["documents"][0][0])
板块 04
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# pip install peft transformers from peft import LoraConfig, get_peft_model from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained( "Qwen/Qwen2.5-0.5B-Instruct") lora = LoraConfig(r=8, target_modules=["q_proj","k_proj","v_proj","o_proj"]) model = get_peft_model(model, lora) model.print_trainable_parameters() # 输出类似:trainable params: 1,572,864 / 501,432,960 → 只训练 0.31%
开场白 · 分步讲解 · 漫画 · 术语 · 实验
ollama run qwen2.5:14b 就能聊天。# 第 1 步:装 Ollama(官网 ollama.com 下载,或终端执行) # brew install ollama # 第 2 步:下载并运行一个 14B 模型(约 9GB,等几分钟) # ollama run qwen2.5:14b # 第 3 步:用 Python 调它(OpenAI 兼容接口) import openai client = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") r = client.chat.completions.create( model="qwen2.5:14b", messages=[{"role": "user", "content": "用三句话解释 RAG"}]) print(r.choices[0].message.content)
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# 打开任意 AI 工具,做一件事:
# 1. 收集你日常问它的 10 个问题+理想答案
# 2. 每个问题问 3 遍,看回答稳不稳定
# 3. 统计:几次答对?几次胡说?
# 4. 把"胡说的题"挑出来,改提示词:
# "不确定的信息,请明确说'我不确定'"
# 5. 再考一遍,对比正确率
板块 05
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# 需要任意 OpenAI 兼容 API。看懂结构即可,不用全跑 def run_agent(task, max_steps=5): messages = [{"role": "system", "content": "你是 Agent。循环执行:思考→调工具→看结果→再思考。" "完成时输出 Final Answer 并停止。"}] for step in range(max_steps): r = client.chat.completions.create( model="gpt-4o-mini", messages=messages, tools=tools) msg = r.choices[0].message print(f"[第{step}步]", msg.content or "(调用工具)") if msg.content and "Final Answer" in msg.content: return msg.content if msg.tool_calls: fn = msg.tool_calls[0].function result = my_tool(fn.name, fn.arguments) # 执行工具 messages += [msg, {"role": "tool", "tool_call_id": msg.tool_calls[0].id, "content": result}] return "达到步数上限,任务未完成"
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# pip install langgraph from typing import TypedDict from langgraph.graph import StateGraph, END class State(TypedDict): messages: list def agent_node(state): return {"messages": [call_llm(state["messages"])]} # LLM 站 def route(state): last = state["messages"][-1] return "finish" if "答案" in last else "agent" # 条件边 g = StateGraph(State) g.add_node("agent", agent_node) g.set_entry_point("agent") g.add_conditional_edges("agent", route, {"agent": "agent", "finish": END}) app = g.compile() print(app.invoke({"messages": ["用一句话介绍 Agent"]}))
开场白 · 分步讲解 · 漫画 · 术语 · 实验
# pip install "mcp[cli]" from mcp.server.fastmcp import FastMCP mcp = FastMCP("demo") @mcp.tool() def add(a: int, b: int) -> int: """两数相加""" return a + b if __name__ == "__main__": mcp.run() # 启动服务器(stdio 模式) # 之后:任何支持 MCP 的 AI 客户端连接这个 server, # 模型就能自己调用 add —— 写一次,处处用
小抄
学完 15 课还记不住?把这一页存着。以后看到 AI 新闻里的生词,回来查。