李沐53_语言模型——自学笔记

语言模型

1.预测文本序列出现的概率

2.应用在做预训练模型

3.生成文本,给定前面几个词,不断生成后续文本

4.判断多个序列中哪个更常见

真实数据集的统计

《时光机器》数据集构建词表, 并打印前10个最常用的(频率最高的)单词。

!pip install --upgrade d2l==0.17.5  #d2l需要更新
Collecting d2l==0.17.5Downloading d2l-0.17.5-py3-none-any.whl (82 kB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m82.4/82.4 kB[0m [31m1.5 MB/s[0m eta [36m0:00:00[0m
[?25hRequirement already satisfied: jupyter==1.0.0 in /usr/local/lib/python3.10/dist-packages (from d2l==0.17.5) (1.0.0)
Collecting numpy==1.21.5 (from d2l==0.17.5)Downloading numpy-1.21.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (15.9 MB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m15.9/15.9 MB[0m [31m46.8 MB/s[0m eta [36m0:00:00[0m
[?25hCollecting matplotlib==3.5.1 (from d2l==0.17.5)Downloading matplotlib-3.5.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.9 MB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m11.9/11.9 MB[0m [31m29.2 MB/s[0m eta [36m0:00:00[0m
[?25hCollecting requests==2.25.1 (from d2l==0.17.5)Downloading requests-2.25.1-py2.py3-none-any.whl (61 kB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m61.2/61.2 kB[0m [31m5.7 MB/s[0m eta [36m0:00:00[0m
[?25hCollecting pandas==1.2.4 (from d2l==0.17.5)Downloading pandas-1.2.4.tar.gz (5.5 MB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m5.5/5.5 MB[0m [31m45.1 MB/s[0m eta [36m0:00:00[0m
[?25h  Installing build dependencies ... [?25l[?25hdoneGetting requirements to build wheel ... [?25l[?25hdonePreparing metadata (pyproject.toml) ... [?25l[?25hdone
Requirement already satisfied: notebook in /usr/local/lib/python3.10/dist-packages (from jupyter==1.0.0->d2l==0.17.5) (6.5.5)
Requirement already satisfied: qtconsole in /usr/local/lib/python3.10/dist-packages (from jupyter==1.0.0->d2l==0.17.5) (5.5.1)
Requirement already satisfied: jupyter-console in /usr/local/lib/python3.10/dist-packages (from jupyter==1.0.0->d2l==0.17.5) (6.1.0)
Requirement already satisfied: nbconvert in /usr/local/lib/python3.10/dist-packages (from jupyter==1.0.0->d2l==0.17.5) (6.5.4)
Requirement already satisfied: ipykernel in /usr/local/lib/python3.10/dist-packages (from jupyter==1.0.0->d2l==0.17.5) (5.5.6)
Requirement already satisfied: ipywidgets in /usr/local/lib/python3.10/dist-packages (from jupyter==1.0.0->d2l==0.17.5) (7.7.1)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.10/dist-packages (from matplotlib==3.5.1->d2l==0.17.5) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.10/dist-packages (from matplotlib==3.5.1->d2l==0.17.5) (4.51.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.10/dist-packages (from matplotlib==3.5.1->d2l==0.17.5) (1.4.5)
Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from matplotlib==3.5.1->d2l==0.17.5) (24.0)
Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.10/dist-packages (from matplotlib==3.5.1->d2l==0.17.5) (9.4.0)
Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.10/dist-packages (from matplotlib==3.5.1->d2l==0.17.5) (3.1.2)
Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.10/dist-packages (from matplotlib==3.5.1->d2l==0.17.5) (2.8.2)
Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.10/dist-packages (from pandas==1.2.4->d2l==0.17.5) (2023.4)
Collecting chardet<5,>=3.0.2 (from requests==2.25.1->d2l==0.17.5)Downloading chardet-4.0.0-py2.py3-none-any.whl (178 kB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m178.7/178.7 kB[0m [31m24.5 MB/s[0m eta [36m0:00:00[0m
[?25hCollecting idna<3,>=2.5 (from requests==2.25.1->d2l==0.17.5)Downloading idna-2.10-py2.py3-none-any.whl (58 kB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m58.8/58.8 kB[0m [31m8.9 MB/s[0m eta [36m0:00:00[0m
[?25hCollecting urllib3<1.27,>=1.21.1 (from requests==2.25.1->d2l==0.17.5)Downloading urllib3-1.26.18-py2.py3-none-any.whl (143 kB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m143.8/143.8 kB[0m [31m21.2 MB/s[0m eta [36m0:00:00[0m
[?25hRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests==2.25.1->d2l==0.17.5) (2024.2.2)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.7->matplotlib==3.5.1->d2l==0.17.5) (1.16.0)
Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.10/dist-packages (from ipykernel->jupyter==1.0.0->d2l==0.17.5) (0.2.0)
Requirement already satisfied: ipython>=5.0.0 in /usr/local/lib/python3.10/dist-packages (from ipykernel->jupyter==1.0.0->d2l==0.17.5) (7.34.0)
Requirement already satisfied: traitlets>=4.1.0 in /usr/local/lib/python3.10/dist-packages (from ipykernel->jupyter==1.0.0->d2l==0.17.5) (5.7.1)
Requirement already satisfied: jupyter-client in /usr/local/lib/python3.10/dist-packages (from ipykernel->jupyter==1.0.0->d2l==0.17.5) (6.1.12)
Requirement already satisfied: tornado>=4.2 in /usr/local/lib/python3.10/dist-packages (from ipykernel->jupyter==1.0.0->d2l==0.17.5) (6.3.3)
Requirement already satisfied: widgetsnbextension~=3.6.0 in /usr/local/lib/python3.10/dist-packages (from ipywidgets->jupyter==1.0.0->d2l==0.17.5) (3.6.6)
Requirement already satisfied: jupyterlab-widgets>=1.0.0 in /usr/local/lib/python3.10/dist-packages (from ipywidgets->jupyter==1.0.0->d2l==0.17.5) (3.0.10)
Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /usr/local/lib/python3.10/dist-packages (from jupyter-console->jupyter==1.0.0->d2l==0.17.5) (3.0.43)
Requirement already satisfied: pygments in /usr/local/lib/python3.10/dist-packages (from jupyter-console->jupyter==1.0.0->d2l==0.17.5) (2.16.1)
Requirement already satisfied: lxml in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (4.9.4)
Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (4.12.3)
Requirement already satisfied: bleach in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (6.1.0)
Requirement already satisfied: defusedxml in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (0.7.1)
Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (0.4)
Requirement already satisfied: jinja2>=3.0 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (3.1.3)
Requirement already satisfied: jupyter-core>=4.7 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (5.7.2)
Requirement already satisfied: jupyterlab-pygments in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (0.3.0)
Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (2.1.5)
Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (0.8.4)
Requirement already satisfied: nbclient>=0.5.0 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (0.10.0)
Requirement already satisfied: nbformat>=5.1 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (5.10.4)
Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (1.5.1)
Requirement already satisfied: tinycss2 in /usr/local/lib/python3.10/dist-packages (from nbconvert->jupyter==1.0.0->d2l==0.17.5) (1.2.1)
Requirement already satisfied: pyzmq<25,>=17 in /usr/local/lib/python3.10/dist-packages (from notebook->jupyter==1.0.0->d2l==0.17.5) (23.2.1)
Requirement already satisfied: argon2-cffi in /usr/local/lib/python3.10/dist-packages (from notebook->jupyter==1.0.0->d2l==0.17.5) (23.1.0)
Requirement already satisfied: nest-asyncio>=1.5 in /usr/local/lib/python3.10/dist-packages (from notebook->jupyter==1.0.0->d2l==0.17.5) (1.6.0)
Requirement already satisfied: Send2Trash>=1.8.0 in /usr/local/lib/python3.10/dist-packages (from notebook->jupyter==1.0.0->d2l==0.17.5) (1.8.3)
Requirement already satisfied: terminado>=0.8.3 in /usr/local/lib/python3.10/dist-packages (from notebook->jupyter==1.0.0->d2l==0.17.5) (0.18.1)
Requirement already satisfied: prometheus-client in /usr/local/lib/python3.10/dist-packages (from notebook->jupyter==1.0.0->d2l==0.17.5) (0.20.0)
Requirement already satisfied: nbclassic>=0.4.7 in /usr/local/lib/python3.10/dist-packages (from notebook->jupyter==1.0.0->d2l==0.17.5) (1.0.0)
Requirement already satisfied: qtpy>=2.4.0 in /usr/local/lib/python3.10/dist-packages (from qtconsole->jupyter==1.0.0->d2l==0.17.5) (2.4.1)
Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.10/dist-packages (from ipython>=5.0.0->ipykernel->jupyter==1.0.0->d2l==0.17.5) (67.7.2)
Requirement already satisfied: jedi>=0.16 in /usr/local/lib/python3.10/dist-packages (from ipython>=5.0.0->ipykernel->jupyter==1.0.0->d2l==0.17.5) (0.19.1)
Requirement already satisfied: decorator in /usr/local/lib/python3.10/dist-packages (from ipython>=5.0.0->ipykernel->jupyter==1.0.0->d2l==0.17.5) (4.4.2)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.10/dist-packages (from ipython>=5.0.0->ipykernel->jupyter==1.0.0->d2l==0.17.5) (0.7.5)
Requirement already satisfied: backcall in /usr/local/lib/python3.10/dist-packages (from ipython>=5.0.0->ipykernel->jupyter==1.0.0->d2l==0.17.5) (0.2.0)
Requirement already satisfied: matplotlib-inline in /usr/local/lib/python3.10/dist-packages (from ipython>=5.0.0->ipykernel->jupyter==1.0.0->d2l==0.17.5) (0.1.7)
Requirement already satisfied: pexpect>4.3 in /usr/local/lib/python3.10/dist-packages (from ipython>=5.0.0->ipykernel->jupyter==1.0.0->d2l==0.17.5) (4.9.0)
Requirement already satisfied: platformdirs>=2.5 in /usr/local/lib/python3.10/dist-packages (from jupyter-core>=4.7->nbconvert->jupyter==1.0.0->d2l==0.17.5) (4.2.0)
Requirement already satisfied: jupyter-server>=1.8 in /usr/local/lib/python3.10/dist-packages (from nbclassic>=0.4.7->notebook->jupyter==1.0.0->d2l==0.17.5) (1.24.0)
Requirement already satisfied: notebook-shim>=0.2.3 in /usr/local/lib/python3.10/dist-packages (from nbclassic>=0.4.7->notebook->jupyter==1.0.0->d2l==0.17.5) (0.2.4)
Requirement already satisfied: fastjsonschema>=2.15 in /usr/local/lib/python3.10/dist-packages (from nbformat>=5.1->nbconvert->jupyter==1.0.0->d2l==0.17.5) (2.19.1)
Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.10/dist-packages (from nbformat>=5.1->nbconvert->jupyter==1.0.0->d2l==0.17.5) (4.19.2)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.10/dist-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->jupyter-console->jupyter==1.0.0->d2l==0.17.5) (0.2.13)
Requirement already satisfied: ptyprocess in /usr/local/lib/python3.10/dist-packages (from terminado>=0.8.3->notebook->jupyter==1.0.0->d2l==0.17.5) (0.7.0)
Requirement already satisfied: argon2-cffi-bindings in /usr/local/lib/python3.10/dist-packages (from argon2-cffi->notebook->jupyter==1.0.0->d2l==0.17.5) (21.2.0)
Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.10/dist-packages (from beautifulsoup4->nbconvert->jupyter==1.0.0->d2l==0.17.5) (2.5)
Requirement already satisfied: webencodings in /usr/local/lib/python3.10/dist-packages (from bleach->nbconvert->jupyter==1.0.0->d2l==0.17.5) (0.5.1)
Requirement already satisfied: parso<0.9.0,>=0.8.3 in /usr/local/lib/python3.10/dist-packages (from jedi>=0.16->ipython>=5.0.0->ipykernel->jupyter==1.0.0->d2l==0.17.5) (0.8.4)
Requirement already satisfied: attrs>=22.2.0 in /usr/local/lib/python3.10/dist-packages (from jsonschema>=2.6->nbformat>=5.1->nbconvert->jupyter==1.0.0->d2l==0.17.5) (23.2.0)
Requirement already satisfied: jsonschema-specifications>=2023.03.6 in /usr/local/lib/python3.10/dist-packages (from jsonschema>=2.6->nbformat>=5.1->nbconvert->jupyter==1.0.0->d2l==0.17.5) (2023.12.1)
Requirement already satisfied: referencing>=0.28.4 in /usr/local/lib/python3.10/dist-packages (from jsonschema>=2.6->nbformat>=5.1->nbconvert->jupyter==1.0.0->d2l==0.17.5) (0.34.0)
Requirement already satisfied: rpds-py>=0.7.1 in /usr/local/lib/python3.10/dist-packages (from jsonschema>=2.6->nbformat>=5.1->nbconvert->jupyter==1.0.0->d2l==0.17.5) (0.18.0)
Requirement already satisfied: anyio<4,>=3.1.0 in /usr/local/lib/python3.10/dist-packages (from jupyter-server>=1.8->nbclassic>=0.4.7->notebook->jupyter==1.0.0->d2l==0.17.5) (3.7.1)
Requirement already satisfied: websocket-client in /usr/local/lib/python3.10/dist-packages (from jupyter-server>=1.8->nbclassic>=0.4.7->notebook->jupyter==1.0.0->d2l==0.17.5) (1.7.0)
Requirement already satisfied: cffi>=1.0.1 in /usr/local/lib/python3.10/dist-packages (from argon2-cffi-bindings->argon2-cffi->notebook->jupyter==1.0.0->d2l==0.17.5) (1.16.0)
Requirement already satisfied: sniffio>=1.1 in /usr/local/lib/python3.10/dist-packages (from anyio<4,>=3.1.0->jupyter-server>=1.8->nbclassic>=0.4.7->notebook->jupyter==1.0.0->d2l==0.17.5) (1.3.1)
Requirement already satisfied: exceptiongroup in /usr/local/lib/python3.10/dist-packages (from anyio<4,>=3.1.0->jupyter-server>=1.8->nbclassic>=0.4.7->notebook->jupyter==1.0.0->d2l==0.17.5) (1.2.0)
Requirement already satisfied: pycparser in /usr/local/lib/python3.10/dist-packages (from cffi>=1.0.1->argon2-cffi-bindings->argon2-cffi->notebook->jupyter==1.0.0->d2l==0.17.5) (2.22)
Building wheels for collected packages: pandasBuilding wheel for pandas (pyproject.toml) ... [?25l[?25hdoneCreated wheel for pandas: filename=pandas-1.2.4-cp310-cp310-linux_x86_64.whl size=34333057 sha256=9fc84123762ca7690bf9255b36611a3a874d4ad9f175184ec1debcbe80364d4cStored in directory: /root/.cache/pip/wheels/1b/10/28/2a37b26cf3e4dc59d82430e3812f8571518d2c1d81c288af98
Successfully built pandas
Installing collected packages: urllib3, numpy, idna, chardet, requests, pandas, matplotlib, d2lAttempting uninstall: urllib3Found existing installation: urllib3 2.0.7Uninstalling urllib3-2.0.7:Successfully uninstalled urllib3-2.0.7Attempting uninstall: numpyFound existing installation: numpy 1.25.2Uninstalling numpy-1.25.2:Successfully uninstalled numpy-1.25.2Attempting uninstall: idnaFound existing installation: idna 3.7Uninstalling idna-3.7:Successfully uninstalled idna-3.7Attempting uninstall: chardetFound existing installation: chardet 5.2.0Uninstalling chardet-5.2.0:Successfully uninstalled chardet-5.2.0Attempting uninstall: requestsFound existing installation: requests 2.31.0Uninstalling requests-2.31.0:Successfully uninstalled requests-2.31.0Attempting uninstall: pandasFound existing installation: pandas 2.0.3Uninstalling pandas-2.0.3:Successfully uninstalled pandas-2.0.3Attempting uninstall: matplotlibFound existing installation: matplotlib 3.7.1Uninstalling matplotlib-3.7.1:Successfully uninstalled matplotlib-3.7.1Attempting uninstall: d2lFound existing installation: d2l 1.0.0a0Uninstalling d2l-1.0.0a0:Successfully uninstalled d2l-1.0.0a0
[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
arviz 0.15.1 requires pandas>=1.3.0, but you have pandas 1.2.4 which is incompatible.
bigframes 1.2.0 requires matplotlib>=3.7.1, but you have matplotlib 3.5.1 which is incompatible.
bigframes 1.2.0 requires pandas>=1.5.0, but you have pandas 1.2.4 which is incompatible.
bigframes 1.2.0 requires requests>=2.27.1, but you have requests 2.25.1 which is incompatible.
chex 0.1.86 requires numpy>=1.24.1, but you have numpy 1.21.5 which is incompatible.
flax 0.8.2 requires numpy>=1.22, but you have numpy 1.21.5 which is incompatible.
google-colab 1.0.0 requires pandas==2.0.3, but you have pandas 1.2.4 which is incompatible.
google-colab 1.0.0 requires requests==2.31.0, but you have requests 2.25.1 which is incompatible.
ibis-framework 8.0.0 requires pandas<3,>=1.2.5, but you have pandas 1.2.4 which is incompatible.
jax 0.4.26 requires numpy>=1.22, but you have numpy 1.21.5 which is incompatible.
jaxlib 0.4.26+cuda12.cudnn89 requires numpy>=1.22, but you have numpy 1.21.5 which is incompatible.
mizani 0.9.3 requires pandas>=1.3.5, but you have pandas 1.2.4 which is incompatible.
numba 0.58.1 requires numpy<1.27,>=1.22, but you have numpy 1.21.5 which is incompatible.
pandas-stubs 2.0.3.230814 requires numpy>=1.25.0; python_version >= "3.9", but you have numpy 1.21.5 which is incompatible.
plotnine 0.12.4 requires matplotlib>=3.6.0, but you have matplotlib 3.5.1 which is incompatible.
plotnine 0.12.4 requires numpy>=1.23.0, but you have numpy 1.21.5 which is incompatible.
plotnine 0.12.4 requires pandas>=1.5.0, but you have pandas 1.2.4 which is incompatible.
pywavelets 1.6.0 requires numpy<3,>=1.22.4, but you have numpy 1.21.5 which is incompatible.
scipy 1.11.4 requires numpy<1.28.0,>=1.21.6, but you have numpy 1.21.5 which is incompatible.
tensorflow 2.15.0 requires numpy<2.0.0,>=1.23.5, but you have numpy 1.21.5 which is incompatible.
tweepy 4.14.0 requires requests<3,>=2.27.0, but you have requests 2.25.1 which is incompatible.
xarray 2023.7.0 requires pandas>=1.4, but you have pandas 1.2.4 which is incompatible.
xarray-einstats 0.7.0 requires numpy>=1.22, but you have numpy 1.21.5 which is incompatible.
yfinance 0.2.38 requires pandas>=1.3.0, but you have pandas 1.2.4 which is incompatible.
yfinance 0.2.38 requires requests>=2.31, but you have requests 2.25.1 which is incompatible.[0m[31m
[0mSuccessfully installed chardet-4.0.0 d2l-0.17.5 idna-2.10 matplotlib-3.5.1 numpy-1.21.5 pandas-1.2.4 requests-2.25.1 urllib3-1.26.18
import random
import torch
from d2l import torch as d2ltokens = d2l.tokenize(d2l.read_time_machine())
# 因为每个文本行不一定是一个句子或一个段落,因此我们把所有文本行拼接到一起
corpus = [token for line in tokens for token in line]
vocab = d2l.Vocab(corpus)
vocab.token_freqs[:10]
[('the', 2261),('i', 1267),('and', 1245),('of', 1155),('a', 816),('to', 695),('was', 552),('in', 541),('that', 443),('my', 440)]

这些词很无聊,通常被称为停用词(stop words),因此可以被过滤掉。

词频衰减的速度相当地快。 例如,最常用单词的词频对比,第10个还不到第1个的
1/5。 为了更好地理解,我们可以画出的词频图:

词频图

freqs = [freq for token, freq in vocab.token_freqs]
d2l.plot(freqs, xlabel='token: x', ylabel='frequency: n(x)',xscale='log', yscale='log')

在这里插入图片描述

二元语法的频率是否与一元语法的频率表现出相同的行为方式?

bigram_tokens = [pair for pair in zip(corpus[:-1], corpus[1:])]
bigram_vocab = d2l.Vocab(bigram_tokens)
bigram_vocab.token_freqs[:10]
[(('of', 'the'), 309),(('in', 'the'), 169),(('i', 'had'), 130),(('i', 'was'), 112),(('and', 'the'), 109),(('the', 'time'), 102),(('it', 'was'), 99),(('to', 'the'), 85),(('as', 'i'), 78),(('of', 'a'), 73)]

在十个最频繁的词对中,有九个是由两个停用词组成的, 只有一个与“the time”有关。 我们再进一步看看三元语法的频率是否表现出相同的行为方式?

trigram_tokens = [triple for triple in zip(corpus[:-2], corpus[1:-1], corpus[2:])]
trigram_vocab = d2l.Vocab(trigram_tokens)
trigram_vocab.token_freqs[:10]
[(('the', 'time', 'traveller'), 59),(('the', 'time', 'machine'), 30),(('the', 'medical', 'man'), 24),(('it', 'seemed', 'to'), 16),(('it', 'was', 'a'), 15),(('here', 'and', 'there'), 15),(('seemed', 'to', 'me'), 14),(('i', 'did', 'not'), 14),(('i', 'saw', 'the'), 13),(('i', 'began', 'to'), 13)]

直观地对比三种模型中的词元频率:一元语法、二元语法和三元语法。

bigram_freqs = [freq for token, freq in bigram_vocab.token_freqs]
trigram_freqs = [freq for token, freq in trigram_vocab.token_freqs]
d2l.plot([freqs, bigram_freqs, trigram_freqs], xlabel='token: x',ylabel='frequency: n(x)', xscale='log', yscale='log',legend=['unigram', 'bigram', 'trigram'])

在这里插入图片描述

随机采样

每次可以从数据中随机生成一个小批量。 在这里,参数batch_size指定了每个小批量中子序列样本的数目, 参数num_steps是每个子序列中预定义的时间步数。

def seq_data_iter_random(corpus, batch_size, num_steps):"""使用随机抽样生成一个小批量子序列"""# 从随机偏移量开始对序列进行分区,随机范围包括num_steps-1corpus = corpus[random.randint(0, num_steps - 1):]# 减去1,是因为我们需要考虑标签num_subseqs = (len(corpus) - 1) // num_steps# 长度为num_steps的子序列的起始索引initial_indices = list(range(0, num_subseqs * num_steps, num_steps))# 在随机抽样的迭代过程中,# 来自两个相邻的、随机的、小批量中的子序列不一定在原始序列上相邻random.shuffle(initial_indices)def data(pos):# 返回从pos位置开始的长度为num_steps的序列return corpus[pos: pos + num_steps]num_batches = num_subseqs // batch_sizefor i in range(0, batch_size * num_batches, batch_size):# 在这里,initial_indices包含子序列的随机起始索引initial_indices_per_batch = initial_indices[i: i + batch_size]X = [data(j) for j in initial_indices_per_batch]Y = [data(j + 1) for j in initial_indices_per_batch]yield torch.tensor(X), torch.tensor(Y)

生成一个从0到34的序列。 假设批量大小为2,时间步数为5,这意味着可以生成6个“特征标签”子序列对。 如果设置小批量大小为2,我们只能得到3个小批量。

my_seq = list(range(35))
for X, Y in seq_data_iter_random(my_seq, batch_size=2, num_steps=5):print('X: ', X, '\nY:', Y)
X:  tensor([[23, 24, 25, 26, 27],[ 8,  9, 10, 11, 12]]) 
Y: tensor([[24, 25, 26, 27, 28],[ 9, 10, 11, 12, 13]])
X:  tensor([[13, 14, 15, 16, 17],[ 3,  4,  5,  6,  7]]) 
Y: tensor([[14, 15, 16, 17, 18],[ 4,  5,  6,  7,  8]])
X:  tensor([[18, 19, 20, 21, 22],[28, 29, 30, 31, 32]]) 
Y: tensor([[19, 20, 21, 22, 23],[29, 30, 31, 32, 33]])

顺序分区

在迭代过程中,除了对原始序列可以随机抽样外, 我们还可以保证两个相邻的小批量中的子序列在原始序列上也是相邻的。 这种策略在基于小批量的迭代过程中保留了拆分的子序列的顺序,因此称为顺序分区。

def seq_data_iter_sequential(corpus, batch_size, num_steps):"""使用顺序分区生成一个小批量子序列"""# 从随机偏移量开始划分序列offset = random.randint(0, num_steps)num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_sizeXs = torch.tensor(corpus[offset: offset + num_tokens])Ys = torch.tensor(corpus[offset + 1: offset + 1 + num_tokens])Xs, Ys = Xs.reshape(batch_size, -1), Ys.reshape(batch_size, -1)num_batches = Xs.shape[1] // num_stepsfor i in range(0, num_steps * num_batches, num_steps):X = Xs[:, i: i + num_steps]Y = Ys[:, i: i + num_steps]yield X, Y

基于相同的设置,通过顺序分区读取每个小批量的子序列的特征X和标签Y。 通过将它们打印出来可以发现: 迭代期间来自两个相邻的小批量中的子序列在原始序列中确实是相邻的。

for X, Y in seq_data_iter_sequential(my_seq, batch_size=2, num_steps=5):print('X: ', X, '\nY:', Y)
X:  tensor([[ 1,  2,  3,  4,  5],[17, 18, 19, 20, 21]]) 
Y: tensor([[ 2,  3,  4,  5,  6],[18, 19, 20, 21, 22]])
X:  tensor([[ 6,  7,  8,  9, 10],[22, 23, 24, 25, 26]]) 
Y: tensor([[ 7,  8,  9, 10, 11],[23, 24, 25, 26, 27]])
X:  tensor([[11, 12, 13, 14, 15],[27, 28, 29, 30, 31]]) 
Y: tensor([[12, 13, 14, 15, 16],[28, 29, 30, 31, 32]])

将上面的两个采样函数包装到一个类中, 以便稍后可以将其用作数据迭代器.

class SeqDataLoader:"""加载序列数据的迭代器"""def __init__(self, batch_size, num_steps, use_random_iter, max_tokens):if use_random_iter:self.data_iter_fn = d2l.seq_data_iter_randomelse:self.data_iter_fn = d2l.seq_data_iter_sequentialself.corpus, self.vocab = d2l.load_corpus_time_machine(max_tokens)self.batch_size, self.num_steps = batch_size, num_stepsdef __iter__(self):return self.data_iter_fn(self.corpus, self.batch_size, self.num_steps)

定义了一个函数load_data_time_machine, 它同时返回数据迭代器和词表, 因此可以与其他带有load_data前缀的函数类似使用

def load_data_time_machine(batch_size, num_steps,use_random_iter=False, max_tokens=10000):"""返回时光机器数据集的迭代器和词表"""data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter, max_tokens)return data_iter, data_iter.vocab

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/482.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C语言 | 动态内存管理

目录&#xff1a; 1. 为什么要有动态内存分配 2. malloc和free 3. calloc和realloc 4. 常见的动态内存的错误 5. 动态内存经典笔试题分析 6. 柔性数组 1. 为什么要有动态内存分配 我们已经掌握的内存开辟方式有&#xff1a; int val 20; //在栈空间上开辟四个字节 cha…

一篇文章搞定Jenkins自动化部署JDK17+SpringBoot3.X+新版AlibabaCloud打包Docker镜像推送私有镜像仓库

&#x1f680; 作者 &#xff1a;“二当家-小D” &#x1f680; 博主简介&#xff1a;⭐前荔枝FM架构师、阿里资深工程师||曾任职于阿里巴巴担任多个项目负责人&#xff0c;8年开发架构经验&#xff0c;精通java,擅长分布式高并发架构,自动化压力测试&#xff0c;微服务容器化k…

-内核编译-01

挂载根文件系统 1搭建【nfs】 1.1PC端配置 nfs&#xff1a;网络服务器 【sudo /etc/init.d/nfs-kernel-server restart】 【sudo /etc/init.d/nfs-kernel-server status】 【sudo netstat -anp|less】 1重启【nfs】网络服务方法2&#xff1a;查看日志 修改配置文件 进入…

无线通信基本原理笔记

通信&#xff1a;人与人或人与自然之间通过某种行为或媒介进行的信息交流与传递。 通信模型&#xff1a;信源→发送设备→信道&#xff08;↑噪声&#xff09;→接收设备→信宿 调制&#xff1a;把基带信号变换成适合在信道中传输的信号的技术。通过改变高频载波的幅度、相位…

计算机网络基础1--基础概念

1. IP地址 1.1 IPv4地址 分为网络号和主机号 地址块的第一个地址和最后一个地址通常不使用。 广播地址为主机号全取1的情况。 2. 常用报文格式 2.0 ethernet协议 2.1 arp协议 2.2 ip协议 2.3 tcp协议 2.4 udp协议 2.5 icmp协议

LeetCode-2007. 从双倍数组中还原原数组【贪心 数组 哈希表 排序】

LeetCode-2007. 从双倍数组中还原原数组【贪心 数组 哈希表 排序】 题目描述&#xff1a;解题思路一&#xff1a;排序 哈希表解题思路二&#xff1a;排序 队列解题思路三&#xff1a;消消乐 题目描述&#xff1a; 一个整数数组 original 可以转变成一个 双倍 数组 changed &…

java文件夹文件比较工具

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set;public class FolderFileNames {public static void main(String[] args) {// 假设您要读取的文件夹路径是 &q…

maridb双数据源联查解决方案:联合存储引擎(Federated Storage Engine)

本地MySQL数据库要访问远程MySQL数据库的表中的数据, 必须通过FEDERATED存储引擎来实现. 有点类似Oracle中的数据库链接(DBLINK)。使用FEDERATED存储引擎的表,本地只存储表的结构信息,数据都存放在远程数据库上,查询时通过建表时指定的连接符去获取远程库的数据返回到本地。操作…

PCA(Principal Component Analysis,主成分分析)与矩阵X的协方差矩阵之间的联系

PCA&#xff08;Principal Component Analysis&#xff0c;主成分分析&#xff09;是一种常用的降维技术&#xff0c;用于将高维数据集投影到低维空间中。在PCA中&#xff0c;投影方程将原始特征向量 ( x 1 , x 2 , … , x p ) (x_1, x_2, \ldots, x_p) (x1​,x2​,…,xp​)映射…

Linux 网络编程项目--简易ftp

主要代码 config.h #define LS 0 #define GET 1 #define PWD 2#define IFGO 3#define LCD 4 #define LLS 5 #define CD 6 #define PUT 7#define QUIT 8 #define DOFILE 9struct Msg {int type;char data[1024];char secondBuf[128]; }; 服务器: #i…

【天软行业全景画像】报告第8期

行业全景画像因子 报告概要&#xff1a;传媒、环保、机械设备行业的拥挤度较高&#xff0c;实际投资交易应注意&#xff1b;煤炭、银行、石油石化行业动量较强&#xff0c;医药生物、综合、计算机行业动量较弱&#xff0c;业绩整体表现较差&#xff1b;食品饮料、公用事业行业景…

书生·浦语大模型实战营(第二期):XTuner 微调 LLM

目录 Finetune简介两种Finetune范式一条数据的一生标准格式数据添加对话模板两种finetune的loss计算 LoRA&QLoRA XTunerXTuner简介XTuner快速上手安装&训练配置模板对话工具数据处理数据集映射函数 InternLM2 1.8B模型多模态LLM给LLM装上电子眼&#xff1a;多模态LLM原…

技术速递|为 .NET iOS 和 .NET MAUI 应用程序添加 Apple 隐私清单支持

作者&#xff1a;Gerald Versluis 排版&#xff1a;Alan Wang Apple 正在推出一项隐私政策&#xff0c;将隐私清单文件包含在针对 App Store 上的 iOS、iPadOS 和 tvOS 平台的新应用程序和更新应用程序中。请注意&#xff0c;至少目前 macOS 应用程序被排除在外。 隐私清单文件…

死磕GMSSL通信-C/C++系列(一)

死磕GMSSL通信-C/C++系列(一) 最近再做国密通信的项目开发,以为国密也就简单的集成一个库就可以完事了,没想到能有这么多坑。遂写下文章,避免重复踩坑。以下国密通信的坑有以下场景 1、使用GMSSL guanzhi/GmSSL进行通信 2、使用加密套件SM2-WITH-SMS4-SM3 使用心得 ​…

【个人博客搭建】(3)添加SqlSugar ORM 以及Json配置文件读取

1、安装sqlsugar。在models下的依赖项那右击选择管理Nuget程序包&#xff0c;输入sqlsugarcore&#xff08;因为我们用的是netcore&#xff0c;而不是net famework所以也对应sqlsugarcore&#xff09;&#xff0c;出来的第一个就是了&#xff0c;然后点击选择版本&#xff0c;一…

ABAP 提示框 汇总

文章目录 前言 1.POPUP_TO_DISPLAY_TEXT 2.POPUP_TO_CONFIRM 3.G_DISPLAY_SELECTION_DYNPRO 4.REUSE_ALV_POPUP_TO_SELECT 5.POPUP_TO_DECIDE_LIST 6.POPUP_WITH_TABLE_DISPLAY_OK 7.BKK_POPUP_DISPLAY_LIST 8. POPUP_TO_CONFIRM_WITH_MESSAGE 9.POPUP_TO_CONFIRM 1…

MinIO + Prometheus + Grafana docker部署

文章目录 说明MinIO简介MinIO 容器化部署Prometheus服务地址配置方法一&#xff1a;先部署后修改方法二&#xff1a;部署时修改compose文件&#xff08;未验证&#xff09; MinIO Access Key配置Prometheus 容器化部署MinIO 生成抓取配置修改Prometheus配置文件Grafana 容器化部…

python3.poc。sqlmapTamperPocsuite

目的&#xff0c;掌握工具的api接口&#xff0c;框架工具二次开发 ---sqlmap的api接口&#xff1a;https://www.freebuf.com/articles/web/204875.html 应用&#xff1a;配合前期信息收集的到可能存在注入点的地方&#xff0c;批量化的去扫描 #开发当前项目过程&#xff1a…

YOLOv8改进 | Conv篇 | CVPR2024最新DynamicConv替换下采样(包含C2f创新改进,解决低FLOPs陷阱)

一、本文介绍 本文给大家带来的改进机制是CVPR2024的最新改进机制DynamicConv其是CVPR2024的最新改进机制,这个论文中介绍了一个名为ParameterNet的新型设计原则,它旨在在大规模视觉预训练模型中增加参数数量,同时尽量不增加浮点运算(FLOPs),所以本文的DynamicConv被提出…

书生·浦语大模型全链路开源体系-第6课

书生浦语大模型全链路开源体系-第6课 书生浦语大模型全链路开源体系-第6课相关资源Lagent & AgentLego 智能体应用搭建环境准备创建虚拟环境安装LMDeploy安装 Lagent安装 AgentLego Lagent 轻量级智能体框架使用 LMDeploy 部署启动并使用 Lagent Web Demo使用自定义工具获取…