Machine Learning & Deep Learning & Reinforcement Learning
0. Reference
Learning Path Reference: Machine Learning Path
Main Story (Parallelism)
Stanford CS229 (Andrew Ng)
[!NOTE]
- Download / Save the notes of this course, read repeatedly.
- Solve the “Problem Sets”.
Dive into Deep Learning
Dive into Deep Learning — Dive into Deep Learning 1.0.3 documentation
Combination:
When learn some knowledge points in CS229, find them in the d2l, and implement in PyTorch.
Reference Books:
- Machine Learning, ISBN 9787302423287 (西瓜书)
- Deep Learning : Adaptive Computation and Machine Learning series, ISBN 9780262035613 (花书)
1. Machine Learning
2. Deep Learning
2.1 Preparation
It is planned to study with Dive into Deep Learning.
Dive into Deep Learning — Dive into Deep Learning 1.0.3 documentation
2.1.1 Install MiniConda
2.1.1.1 Install for Windows
I choose to install manually, so I download the graphical installer:
Check the 1st, 3rd item:
2.1.1.2 Configuration for GitBash
1 | /d/softwares/MiniConda/Scripts/conda init |
After initiation, the terminal displays:
1 | ==> For changes to take effect, close and re-open your current shell. <== |
However, when I restart the GitBash, the bash can’t find the command
conda, while the PowerShell can find it:
GitBash:
1
2
3test@□□ѩ□□□□ MINGW64 /e/Computer Science System Building
$ conda
bash: conda: command not foundPowerShell:
1
2(base) PS E:\Computer Science System Building> conda --version
conda 26.5.3
This because the conda init for windows writes some
configuration for PowerShell only.
So we need to write the configuration manually:
1 | echo ' |
Then restart the GitBash:
1 | test@□□ѩ□□□□ MINGW64 /e/Computer Science System Building |
2.1.2.3 Initialize a New Env
Accept new terms:
1 | conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main |
Create new env:
1 | conda create --name d2l python=3.9 -y |
Switch to new env:
1 | conda activate d2l |
2.1.2 Install a Deep Learning Framework
Determine to install PyTorch with CUDA version 12.6 (remember to switch the env to d2l) :
1 | python -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126 |
Check:
1 | $ python -c "import torch; print(torch.cuda.is_available()); print(torch.cuda.get_device_name(0))" |
2.1.2.1 Ideal Installation of d2l package
Install d2l package:
1 | python -m pip install d2l |
If there’s an error when you install d2l due to the high version of python (like python 13.x):
1 | $ python -m pip install d2l |
2.1.2.2 Actual Installation
I run those commands to avoid:
1 | python -m pip install d2l --no-deps |
there are some warnings that can be ignored:
1 | Installing collected packages: webencodings, pure-eval, fastjsonschema, widgetsnbextension, websocket-client, webcolors, wcwidth, urllib3, uri-template, tzdata, traitlets, tornado, tinycss2, soupsieve, six, send2trash, rpds-py, rfc3986-validator, pyzmq, pyyaml, pywinpty, python-json-logger, pyparsing, pygments, pycparser, psutil, prometheus-client, platformdirs, parso, pandocfilters, nest-asyncio2, mistune, lark, kiwisolver, jupyterlab_widgets, jupyterlab-pygments, jsonpointer, json5, idna, h11, fqdn, fonttools, executing, defusedxml, decorator, debugpy, cycler, contourpy, comm, colorama, charset_normalizer, certifi, bleach, babel, attrs, async-lru, asttokens, terminado, stack_data, rfc3987-syntax, rfc3339-validator, requests, referencing, python-dateutil, prompt_toolkit, matplotlib-inline, jupyter-core, jedi, ipython-pygments-lexers, httpcore, cffi, beautifulsoup4, anyio, pandas, matplotlib, jupyter-server-terminals, jupyter-client, jupyter-builder, jsonschema-specifications, ipython, httpx, arrow, argon2-cffi-bindings, jsonschema, isoduration, ipywidgets, ipykernel, argon2-cffi, nbformat, jupyter-console, nbclient, jupyter-events, nbconvert, jupyter-server, notebook-shim, jupyterlab-server, jupyter-lsp, jupyterlab, notebook, jupyter |
2.1.3 Open the Notebook
1
2
3mkdir d2l-en && cd d2l-en
curl https://d2l.ai/d2l-en-1.0.3.zip -o d2l-en.zip
unzip d2l-en.zip && rm d2l-en.zipEach time you should activate the env and run :
1
2
3conda activate d2l
cd pytorch
jupyter notebookThen, a progress will start on your port: http://localhost:8888 You can an run the code for each section of the book.
Whenever you open a new command line window, you will need to execute
conda activate d2lto activate the runtime environment before running the D2L notebooks, or updating your packages (either the deep learning framework or thed2lpackage). To exit the environment, runconda deactivate.
2.1.4 Notational Conventions
Numerical Objects
- x: a scalar
- x: a vector
- X: a matrix
- X: a general tensor
- I: the identity matrix (of some given dimension), i.e., a square matrix with 1 on all diagonal entries and 0 on all off-diagonals
- xi, [x]i: the ith element of vector x
- xij, xi, j, [X]ij, [X]i, j: the element of matrix X at row i and column j.
Set Theory
- 𝒳: a set
- ℤ: the set of integers
- ℤ+: the set of positive integers
- ℝ: the set of real numbers
- ℝn: the set of n-dimensional vectors of real numbers
- ℝa × b: The set of matrices of real numbers with a rows and b columns
- |𝒳|: cardinality (number of elements) of set 𝒳
- 𝒜 ∪ ℬ: union of sets 𝒜 and ℬ
- 𝒜 ∩ ℬ: intersection of sets 𝒜 and ℬ
- 𝒜 \ ℬ: set subtraction of ℬ from 𝒜 (contains only those elements of 𝒜 that do not belong to ℬ)
Functions and Operators - f(⋅): a function - log (⋅): the natural logarithm (base e) - log2(⋅): logarithm to base 2 - exp (⋅): the exponential function - 1(⋅): the indicator function; evaluates to 1 if the boolean argument is true, and 0 otherwise - 1𝒳(z): the set-membership indicator function; evaluates to 1 if the element z belongs to the set 𝒳 and 0 otherwise - (⋅)⊤: transpose of a vector or a matrix - X−1: inverse of matrix X - ⊙: Hadamard (elementwise) product - [⋅, ⋅]: concatenation - ∥ ⋅ ∥p: ℓp norm - ∥⋅∥: ℓ2 norm - ⟨x, y⟩: inner (dot) product of vectors x and y - ∑: summation over a collection of elements - ∏: product over a collection of elements - $\stackrel{\text{def}}{=}$: an equality asserted as a definition of the symbol on the left-hand side
Calculus - $\frac{dy}{dx}$: derivative of y with respect to x - $\frac{\partial y}{\partial x}$: partial derivative of y with respect to x - ∇xy: gradient of y with respect to x - ∫abf(x) dx: definite integral of f from a to b with respect to x - ∫f(x) dx: indefinite integral of f with respect to x
Probability and Information Theory - X: a random variable - P: a probability distribution - X ∼ P: the random variable X follows distribution P - P(X = x): the probability assigned to the event where random variable X takes value x - P(X ∣ Y): the conditional probability distribution of X given Y - p(⋅): a probability density function (PDF) associated with distribution P - E[X]: expectation of a random variable X - X ⟂ Y: random variables X and Y are independent - X ⟂ Y ∣ Z: random variables X and Y are conditionally independent given Z - σX: standard deviation of random variable X - Var(X): variance of random variable X, equal to σX2 - Cov(X, Y): covariance of random variables X and Y - ρ(X, Y): the Pearson correlation coefficient between X and Y, equals $\frac{\text{Cov}(X,Y)}{\sigma_X \sigma_Y}$ - H(X): entropy of random variable X - DKL(P∥Q): the KL-divergence (or relative entropy) from distribution Q to distribution P
2.2 Preliminaries
To prepare for your dive into deep learning, we will need a few survival skills:
- techniques for storing and manipulating data;
- libraries for ingesting and preprocessing data from a variety of sources;
- knowledge of the basic linear algebraic operations that we apply to high-dimensional data elements;
- just enough calculus to determine which direction to adjust each parameter in order to decrease the loss function;
- the ability to automatically compute derivatives so that you can forget much of the calculus you just learned;
- some basic fluency in probability, our primary language for reasoning under uncertainty.
- some aptitude for finding answers in the official documentation when you get stuck.
2.2.1 Data Manipulation
Generally, there are two important things we need to do with data:
- acquire them
- process them once they are inside the computer
There is no point in acquiring data without some way to store it, so to start, let’s get our hands dirty with n-dimensional arrays, which we also call tensors.
If you already know the NumPy scientific computing
package, this will be a breeze. For all modern deep learning frameworks,
the tensor class (ndarray in
MXNet, Tensor in PyTorch and
TensorFlow) resembles NumPy’s ndarray,
with a few killer features added.
First, the tensor class supports automatic differentiation.
Second, it leverages GPUs to accelerate numerical computation, whereas NumPy only runs on CPUs.
These properties make neural networks both easy to code and fast to run.
2.2.1.1 Start with Tensor
A tensor represents a (possibly multidimensional) array of numerical values.
In the one-dimensional case, i.e., when only one axis is needed for the data, a tensor is called a vector. With two axes, a tensor is called a matrix.
With K > 2 axes, we drop the specialized names and just refer to the object as a
$ K^{th}-order$ tensor.
PyTorch provides a variety of functions for creating new tensors prepopulated with values.
For example, by invoking arange(n), we can create a
vector of evenly spaced values, starting at 0 (included)
and ending at n (not included). By default, the interval
size is 1.
Unless otherwise specified, new tensors are stored in main memory and designated for CPU-based computation.
1 | import torch |
1 | tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.]) |
Each of these values is called an element of the tensor. The
tensor x contains 12 elements. We can inspect the total
number of elements in a tensor via its numel method.
1 | print("nums of elements is:", x.numel()) |
1 | nums of elements is: 12 |
We can access a tensor’s shape (the length along each axis)
by inspecting its shape attribute. Because we are dealing
with a vector here, the shape contains just a single
element and is identical to the size.
1 | print("shape of x is:", x.shape) |
1 | shape of x is: torch.Size([12]) |
We can change the shape of a tensor without altering its size or
values, by invoking reshape.
For example, we can transform our vector x whose shape
is (12,) to a matrix X with shape (3, 4).
This new tensor retains all elements but reconfigures them into a
matrix. Notice that the elements of our vector are laid out one row at a
time and thus x[3] == X[0, 3] (3rd element in x equals to
x[row 0, column 3]).
1 | print ("reshape x to 3 rows and 4 columns") |
1 | x[3] = tensor(3.) |