{
  "id": "python-numpy-setup",
  "module": "math-ml",
  "level": 1,
  "minutes": 25,
  "audiences": [
    "beginner",
    "developer",
    "researcher"
  ],
  "software": [
    "uv"
  ],
  "text": {
    "en": {
      "title": "First Step into AI Coding: Python, NumPy and Your Dev Environment (venv, Git, Jupyter)",
      "description": "The programming basics you need before learning AI: core Python syntax and data structures, vectorised computing and broadcasting with NumPy, virtual environments, Git and Jupyter/Colab — plus a tiny linear regression written in pure NumPy. Based on the official Python and NumPy docs and the NumPy paper.",
      "updated": "2026-10-23",
      "takeaways": [
        "AI code uses a small slice of Python: lists, dicts, functions, classes, loops and imports. Get fluent with those first.",
        "NumPy is built around the ndarray, a multi-dimensional array of one data type. Replacing per-element loops with whole-array operations (vectorisation) makes code shorter and usually much faster.",
        "Broadcasting compares shapes from the last dimension backwards; two dimensions are compatible when they are equal or one of them is 1. Understand this and most model code becomes readable.",
        "Use one virtual environment per project (python -m venv or uv) and keep your code in Git.",
        "Experiment in Jupyter or Colab, then move reusable code into .py files."
      ],
      "faq": [
        {
          "q": "Do I have to learn Python to learn AI?",
          "a": "Not to use AI products. But as soon as you call model APIs, build RAG or fine-tune, the major frameworks (PyTorch, Hugging Face, scikit-learn) and almost every official example are in Python, so it is the easiest path."
        },
        {
          "q": "How do NumPy and PyTorch relate?",
          "a": "Both are multi-dimensional array libraries with very similar syntax. NumPy runs mainly on the CPU; PyTorch tensors can also live on a GPU and support automatic differentiation. Learn NumPy first and the move to PyTorch is almost seamless."
        },
        {
          "q": "venv, conda or uv?",
          "a": "venv ships with Python and is the simplest; uv is a faster package and project manager; conda suits scientific stacks that need non-Python dependencies. Pick one and stick to it — what matters is a separate environment per project."
        },
        {
          "q": "What if my computer is weak?",
          "a": "Use Google Colab: Python notebooks run in the browser, and there is a free GPU runtime with usage limits."
        }
      ],
      "sources": [
        {
          "title": "The Python Tutorial (official)",
          "url": "https://docs.python.org/3/tutorial/index.html"
        },
        {
          "title": "Python docs: Data Structures",
          "url": "https://docs.python.org/3/tutorial/datastructures.html"
        },
        {
          "title": "Python docs: venv — creation of virtual environments",
          "url": "https://docs.python.org/3/library/venv.html"
        },
        {
          "title": "NumPy: the absolute basics for beginners",
          "url": "https://numpy.org/doc/stable/user/absolute_beginners.html"
        },
        {
          "title": "NumPy quickstart",
          "url": "https://numpy.org/doc/stable/user/quickstart.html"
        },
        {
          "title": "NumPy docs: Broadcasting",
          "url": "https://numpy.org/doc/stable/user/basics.broadcasting.html"
        },
        {
          "title": "Harris et al. (2020), Array Programming with NumPy (Nature)",
          "url": "https://arxiv.org/abs/2006.10256"
        },
        {
          "title": "Stanford CS231n, Python Numpy Tutorial",
          "url": "https://cs231n.github.io/python-numpy-tutorial/"
        },
        {
          "title": "MIT, The Missing Semester of Your CS Education",
          "url": "https://missing.csail.mit.edu/"
        },
        {
          "title": "Pro Git (official Git book)",
          "url": "https://git-scm.com/book/en/v2"
        },
        {
          "title": "Project Jupyter documentation",
          "url": "https://docs.jupyter.org/en/latest/"
        },
        {
          "title": "uv documentation",
          "url": "https://docs.astral.sh/uv/"
        },
        {
          "title": "Google Colab FAQ",
          "url": "https://research.google.com/colaboratory/faq.html"
        }
      ],
      "url": "https://aimap.page/en/learn/math-ml/python-numpy-setup/",
      "markdown": "## The short answer\n\nThe coding foundation for AI is three things: **writing Python, computing with arrays in NumPy, and a clean, reproducible dev environment**. In [this unit](/learn/unit/u10-python) of the Maths & Code stage that takes about 12 hours, and everything after — [PyTorch](/learn/pytorch-autograd), model APIs, RAG — builds on it.\n\n## Step 1: just enough Python\n\nThe [official Python Tutorial](https://docs.python.org/3/tutorial/index.html) is the authoritative starting point. These are the pieces you meet most often in AI code:\n\n| Syntax | What it looks like in AI code |\n|---|---|\n| list | a batch of samples, a sequence of tokens: `batch = [x1, x2, x3]` |\n| dict | configs and API request bodies: `{\"model\": \"...\", \"messages\": [...]}` |\n| functions with defaults | `def train(lr=1e-3, epochs=10): ...` |\n| classes | model definitions: `class MyNet(nn.Module): ...` |\n| list comprehensions | `lengths = [len(t) for t in texts]` |\n| imports | `import numpy as np` |\n\nA good route: read chapters 3–9 of the tutorial (control flow, [data structures](https://docs.python.org/3/tutorial/datastructures.html), modules, classes), then do the [Kaggle Learn Python course](https://www.kaggle.com/learn/python) and practise right in the browser.\n\n## Step 2: NumPy and vectorisation\n\nNumPy is the foundation of numerical Python. Its core object, the **ndarray**, is a multi-dimensional array of a single type; every array has a `shape` and a `dtype` ([NumPy basics](https://numpy.org/doc/stable/user/absolute_beginners.html)). The NumPy paper describes it as the foundation of the whole scientific Python ecosystem, with other array libraries — deep-learning tensors included — offering NumPy-like interfaces ([Harris et al., 2020](https://arxiv.org/abs/2006.10256)).\n\n**Vectorisation** means you don't loop over elements in Python; you give one instruction for the whole array.\n\n```python\nimport numpy as np\n\nx = np.random.rand(1_000_000)\n\n# Loop: every element goes through the Python interpreter\ny_loop = [v * 2 + 1 for v in x]\n\n# Vectorised: one statement, executed in NumPy's compiled code\ny_vec = x * 2 + 1\n```\n\nBoth give the same numbers, but the vectorised version hands the loop to NumPy's compiled internals and skips per-element interpreter overhead. Compare them yourself with `%timeit` in Jupyter.\n\n### Broadcasting\n\nHow do you add arrays of different shapes? NumPy's rule: **compare dimensions starting from the last (rightmost) one and move left; two dimensions are compatible when they are equal or one of them is 1**. Otherwise you get an error ([official docs](https://numpy.org/doc/stable/user/basics.broadcasting.html)).\n\n```python\nimages = np.random.rand(32, 28, 28)   # 32 images of 28×28\nmean = images.mean(axis=0)            # shape (28, 28)\ncentered = images - mean              # (32,28,28) vs (28,28): aligned from the right, compatible\n```\n\nModel code is full of this: subtracting a mean from a batch, adding a bias vector, a row-wise softmax.\n\n### A tiny example: linear regression in pure NumPy\n\nPut it together and fit a line ([linear regression](/learn/algorithms/linear-regression)) with [gradient descent](/learn/algorithms/sgd). The idea is explained in [How Machines Learn](/learn/ml-basics).\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng(0)\nX = rng.random((200, 1))\ny = 3 * X[:, 0] + 2 + 0.1 * rng.standard_normal(200)\n\nw, b, lr = 0.0, 0.0, 0.5\nfor step in range(500):\n    pred = X[:, 0] * w + b          # vectorised prediction\n    err = pred - y\n    grad_w = 2 * (err * X[:, 0]).mean()\n    grad_b = 2 * err.mean()\n    w -= lr * grad_w\n    b -= lr * grad_b\n\nprint(round(w, 2), round(b, 2))     # close to 3 and 2\n```\n\nThe only loop is over training steps; the work on all 200 samples inside each step is vectorised. In the next lesson, [PyTorch and Autograd](/learn/pytorch-autograd), the framework computes `grad_w` and `grad_b` for you.\n\n## Step 3: your dev environment\n\n### Virtual environments\n\nProjects often need conflicting library versions. Python's built-in `venv` creates a separate directory per project; packages installed there are isolated by default from the base environment and from other virtual environments ([venv docs](https://docs.python.org/3/library/venv.html)):\n\n```bash\npython -m venv .venv\nsource .venv/bin/activate        # Windows: .venv\\Scripts\\activate\npip install numpy jupyter\n```\n\n[uv](https://docs.astral.sh/uv/) is an alternative that handles environments, installs and version locking in one faster tool.\n\n### Git\n\nPut code, experiment configs and small datasets in Git. The first three chapters of [Pro Git](https://git-scm.com/book/en/v2) cover what you need: `init`, `add`, `commit`, `branch`, `push`. MIT's [Missing Semester](https://missing.csail.mit.edu/) teaches the shell, scripting, Git and debugging tools together and is a great catch-up course.\n\n### Jupyter and Colab\n\nA [Jupyter](https://docs.jupyter.org/en/latest/) notebook keeps code, output and notes on one page — ideal for exploring data and running experiments. Without a suitable computer, use Google Colab in the browser ([FAQ](https://research.google.com/colaboratory/faq.html)). A good habit: prototype in a notebook, then move stable functions into `.py` files so you can reuse them and diff them in Git.\n\n## Common mistakes\n\n- **\"I'll finish learning Python before touching AI.\"** No need. Know the table above and learn the rest while building.\n- **Triple for-loops in NumPy.** They can almost always be rewritten as matrix operations or broadcasting — and that rewrite is the best practice you can get.\n- **One global environment for everything.** You will hit version conflicts sooner or later, and nobody can reproduce your results.\n- **Sprinkling `reshape` until the error goes away.** `print(a.shape)` first, align shapes from the right by the broadcasting rule, and know what each dimension means.\n\n## Try it yourself\n\n1. Finish every exercise in [Kaggle Learn Python](https://www.kaggle.com/learn/python).\n2. Do the first 50 problems of [numpy-100](https://github.com/rougier/numpy-100).\n3. Unit project: **without loops**, use only NumPy to normalise a batch of images, do a matrix multiplication and a row-wise softmax, then compare speed with a loop version using `%timeit`.\n4. Put the project in a fresh virtual environment and a Git repo with a `requirements.txt` (or a uv lockfile) so anyone can reproduce it.\n\nFor a compact review, read Stanford CS231n's [Python Numpy Tutorial](https://cs231n.github.io/python-numpy-tutorial/), one page covering the Python and NumPy a deep-learning course needs."
    },
    "zh-hans": {
      "title": "AI 入门第一步：Python、NumPy 与开发环境（虚拟环境、Git、Jupyter）",
      "description": "学 AI 之前要准备的编程基本功：Python 的核心语法和数据结构，用 NumPy 做向量化计算和广播，用虚拟环境隔离依赖，用 Git 管理代码，用 Jupyter/Colab 做实验。附一个只用 NumPy 写的线性回归小例子。依据 Python、NumPy 官方文档与 NumPy 论文。",
      "updated": "2026-10-23",
      "takeaways": [
        "AI 代码里最常用的 Python 只占语言的一小部分：列表、字典、函数、类、循环和模块导入，先把这些练熟。",
        "NumPy 的核心是 ndarray：一块同类型的多维数组。把“对每个元素循环”改写成“对整个数组运算”（向量化），代码更短、通常也快得多。",
        "广播（broadcasting）从最后一维往前比较形状，两维相等或其中一个是 1 就能运算；搞懂它，就能读懂大部分模型代码。",
        "每个项目一个虚拟环境（python -m venv 或 uv），依赖互不干扰；代码交给 Git 管理。",
        "做实验用 Jupyter 或 Colab，写成可复用的工具再移到 .py 文件里。"
      ],
      "faq": [
        {
          "q": "学 AI 一定要学 Python 吗？",
          "a": "如果只是用 AI 产品，不需要。但只要你想调用模型 API、做 RAG 或微调，主流框架（PyTorch、Hugging Face、scikit-learn）和几乎所有官方示例都是 Python，学它最省事。"
        },
        {
          "q": "NumPy 和 PyTorch 是什么关系？",
          "a": "两者都是多维数组库，写法很像。NumPy 主要跑在 CPU 上；PyTorch 的张量（tensor）还能放到 GPU 上，并能自动求导。先学 NumPy 再学 PyTorch，过渡几乎无缝。"
        },
        {
          "q": "venv、conda、uv 选哪个？",
          "a": "venv 是 Python 自带的，最简单；uv 是更快的包和项目管理工具，本站软件库也有收录；conda 适合需要非 Python 依赖的科学计算环境。新手选一个坚持用即可，关键是每个项目分开。"
        },
        {
          "q": "没有好电脑怎么办？",
          "a": "用 Google Colab，在浏览器里就能运行 Python 和 Notebook，还能使用免费的 GPU 运行环境（有使用限额）。"
        }
      ],
      "sources": [
        {
          "title": "Python 官方教程（The Python Tutorial）",
          "url": "https://docs.python.org/3/tutorial/index.html"
        },
        {
          "title": "Python 官方文档：数据结构",
          "url": "https://docs.python.org/3/tutorial/datastructures.html"
        },
        {
          "title": "Python 官方文档：venv 虚拟环境",
          "url": "https://docs.python.org/3/library/venv.html"
        },
        {
          "title": "NumPy 官方：NumPy: the absolute basics for beginners",
          "url": "https://numpy.org/doc/stable/user/absolute_beginners.html"
        },
        {
          "title": "NumPy 官方：Quickstart",
          "url": "https://numpy.org/doc/stable/user/quickstart.html"
        },
        {
          "title": "NumPy 官方：Broadcasting",
          "url": "https://numpy.org/doc/stable/user/basics.broadcasting.html"
        },
        {
          "title": "Harris 等（2020），Array Programming with NumPy（Nature）",
          "url": "https://arxiv.org/abs/2006.10256"
        },
        {
          "title": "Stanford CS231n，Python Numpy Tutorial",
          "url": "https://cs231n.github.io/python-numpy-tutorial/"
        },
        {
          "title": "MIT，The Missing Semester of Your CS Education",
          "url": "https://missing.csail.mit.edu/"
        },
        {
          "title": "Pro Git（Git 官方图书）",
          "url": "https://git-scm.com/book/en/v2"
        },
        {
          "title": "Project Jupyter 官方文档",
          "url": "https://docs.jupyter.org/en/latest/"
        },
        {
          "title": "uv 官方文档",
          "url": "https://docs.astral.sh/uv/"
        },
        {
          "title": "Google Colab 常见问题（FAQ）",
          "url": "https://research.google.com/colaboratory/faq.html"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/math-ml/python-numpy-setup/",
      "markdown": "## 一句话回答\n\n学 AI 的编程基本功只有三样：**会写 Python、会用 NumPy 做数组计算、有一个干净可复现的开发环境**。这三样在“数学与编程”阶段的 [本单元](/learn/unit/u10-python) 里大约需要 12 小时，之后学 [PyTorch](/learn/pytorch-autograd)、调模型 API、做 RAG 都建立在它上面。\n\n## 第一步：够用的 Python\n\n[Python 官方教程](https://docs.python.org/3/tutorial/index.html) 是最权威的入门材料。读 AI 代码时最常遇到的是这几样：\n\n| 语法 | 在 AI 代码里常见的样子 |\n|---|---|\n| 列表 list | 一批样本、一串 token：`batch = [x1, x2, x3]` |\n| 字典 dict | 配置、API 请求体：`{\"model\": \"...\", \"messages\": [...]}` |\n| 函数与默认参数 | `def train(lr=1e-3, epochs=10): ...` |\n| 类 class | 模型定义：`class MyNet(nn.Module): ...` |\n| 列表推导式 | `lengths = [len(t) for t in texts]` |\n| 模块导入 | `import numpy as np` |\n\n建议的学法：先读官方教程第 3–9 章（流程控制、[数据结构](https://docs.python.org/3/tutorial/datastructures.html)、模块、类），然后直接做 [Kaggle Learn 的 Python 课](https://www.kaggle.com/learn/python)，在浏览器里边学边练。\n\n## 第二步：NumPy 与向量化\n\nNumPy 是 Python 数值计算的地基。它的核心对象 **ndarray** 是一块同类型的多维数组，每个数组都有形状 `shape` 和数据类型 `dtype`（[NumPy 入门](https://numpy.org/doc/stable/user/absolute_beginners.html)）。NumPy 论文把它称为整个科学 Python 生态的基础，其他数组库（包括深度学习框架的张量）都在模仿它的接口（[Harris 等，2020](https://arxiv.org/abs/2006.10256)）。\n\n**向量化**的意思是：不要在 Python 里逐个元素循环，而是对整个数组下一条指令。\n\n```python\nimport numpy as np\n\nx = np.random.rand(1_000_000)\n\n# 循环版：逐元素在 Python 解释器里执行\ny_loop = [v * 2 + 1 for v in x]\n\n# 向量化版：一条语句，在 NumPy 的编译代码里批量完成\ny_vec = x * 2 + 1\n```\n\n两种写法结果一样，但向量化版本把循环交给了 NumPy 内部的编译代码，省掉了解释器逐个元素的开销。你可以在 Jupyter 里用 `%timeit` 自己比一比。\n\n### 广播（broadcasting）\n\n形状不同的数组怎么相加？NumPy 的规则是：**从最后一维（最右边）开始往左逐维比较，两维相等或其中一个是 1，就算兼容**；不兼容就报错（[官方文档](https://numpy.org/doc/stable/user/basics.broadcasting.html)）。\n\n```python\nimages = np.random.rand(32, 28, 28)   # 32 张 28×28 的图\nmean = images.mean(axis=0)            # 形状 (28, 28)\ncentered = images - mean              # (32,28,28) 与 (28,28)：从右往左比，兼容\n```\n\n模型代码里随处可见这种写法：一批数据减去均值、加上偏置向量、按行做 softmax。\n\n### 一个小例子：只用 NumPy 做线性回归\n\n把前面的内容串起来，用 [梯度下降](/learn/algorithms/sgd) 拟合一条直线（[线性回归](/learn/algorithms/linear-regression)）。原理见 [机器是怎么学习的](/learn/ml-basics)。\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng(0)\nX = rng.random((200, 1))\ny = 3 * X[:, 0] + 2 + 0.1 * rng.standard_normal(200)\n\nw, b, lr = 0.0, 0.0, 0.5\nfor step in range(500):\n    pred = X[:, 0] * w + b          # 向量化预测\n    err = pred - y\n    grad_w = 2 * (err * X[:, 0]).mean()\n    grad_b = 2 * err.mean()\n    w -= lr * grad_w\n    b -= lr * grad_b\n\nprint(round(w, 2), round(b, 2))     # 接近 3 和 2\n```\n\n注意这里只有“训练步数”这一层循环，每一步内部对 200 个样本的计算全部是向量化的。下一课 [PyTorch 与自动求导](/learn/pytorch-autograd) 会把手写的 `grad_w`、`grad_b` 交给框架自动计算。\n\n## 第三步：开发环境\n\n### 虚拟环境\n\n不同项目依赖的库版本经常冲突。Python 自带的 `venv` 会为每个项目建一个独立目录，装进去的包默认和系统环境、其他虚拟环境隔离（[venv 文档](https://docs.python.org/3/library/venv.html)）：\n\n```bash\npython -m venv .venv\nsource .venv/bin/activate        # Windows：.venv\\Scripts\\activate\npip install numpy jupyter\n```\n\n也可以用 [uv](https://docs.astral.sh/uv/)，它把建环境、装包和锁定版本放在一个工具里，速度更快。\n\n### Git\n\n代码、实验配置和小数据集都应该放进 Git。入门读 [Pro Git](https://git-scm.com/book/en/v2) 前三章就够：`init`、`add`、`commit`、`branch`、`push`。MIT 的 [Missing Semester](https://missing.csail.mit.edu/) 课程把命令行、Shell 脚本、Git 和调试工具一起讲了，很适合补课。\n\n### Jupyter 与 Colab\n\n[Jupyter](https://docs.jupyter.org/en/latest/) Notebook 把代码、输出和说明文字放在一页里，适合探索数据和做实验。没有合适的电脑，就用 Google Colab，浏览器打开即可运行（[FAQ](https://research.google.com/colaboratory/faq.html)）。经验做法是：在 Notebook 里试出来，再把稳定的函数挪到 `.py` 文件里，方便复用和用 Git 比对改动。\n\n## 常见误区\n\n- **“先把 Python 全学完再学 AI”**：没必要。掌握上面表格里的语法，就可以边做项目边补。\n- **在 NumPy 里写三层 for 循环**：几乎总能改写成矩阵运算或广播，改写本身就是最好的练习。\n- **所有项目共用一个全局环境**：迟早遇到版本冲突，而且别人无法复现你的结果。\n- **形状不对就乱加 `reshape`**：先 `print(a.shape)`，按广播规则从右往左对齐，弄清楚每一维的含义。\n\n## 动手试试\n\n1. 在 [Kaggle Learn Python](https://www.kaggle.com/learn/python) 完成全部练习。\n2. 做 [numpy-100](https://github.com/rougier/numpy-100) 的前 50 题。\n3. 本单元项目：**不用循环**，只用 NumPy 对一批图片做归一化、做一次矩阵乘法、按行算 softmax，并用 `%timeit` 和循环版比较速度。\n4. 把项目放进一个新的虚拟环境和 Git 仓库，写一份 `requirements.txt`（或用 uv 生成锁文件），让别人能一键复现。\n\n想系统地过一遍，可以读 Stanford CS231n 的 [Python Numpy Tutorial](https://cs231n.github.io/python-numpy-tutorial/)，它用一页纸讲完了深度学习课程需要的 Python 和 NumPy。"
    }
  }
}