PyTorch版深度学习
踏歌行 2024-12-14
语言
AI
# 准备工作
# Anaconda 版本管理
官网下载方式 (opens new window), powershell中
wget "https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe" -outfile "./Downloads/Miniconda3-latest-Windows-x86_64.exe"
打开windows内的应用anaconda prompt,创建环境
conda create --name d2l python=3.9 -y
激活环境:
conda activate d2l
conda info --env
看到所有python环境切换镜像
conda config --add channels http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch
# 学习pytorch版深度学习环境
pip install torch==1.12.0
pip install torchvision==0.13.0
pip install d2l==0.17.6
# 安装 D2L Notebook
以下方法,可以下载并打开《动手学深度学习PyTorch版》这本书彩色版本的电子档。 Jupyter与一般文档不同的是,可以直接运行代码和展示结果。
mkdir d2l-zh && cd d2l-zh
curl https://zh-v2.d2l.ai/d2l-zh-2.0.0.zip -o d2l-zh.zip
unzip d2l-zh.zip && rm d2l-zh.zip //windows内手动解压
cd pytorch
jupyter notebook
1
2
3
4
5
2
3
4
5
# 第一章 引言
# 1.2 机器学习中的关键组件
- 数据
- 模型
- 目标函数
- 优化算法
# 1.3 各种机器学习问题
# 1.3.1 监督学习
监督学习:擅长在给定输入特征的情况下预测标签
- 回归:有多少问题
- 分类:二项分类、多项分类
- 标注问题
- 搜索
- 推荐系统
- 序列学习:连续的输入,比如视频、音频、病人24h的情况,对话问题等等
# 1.3.2 无监督学习
不含有"目标"的学习为无监督学习
# 1.3.1 与环境互动
从环境中收集数据
# 1.3.1 强化学习
智能体(Agent)从环境中获取激励
# 1.7 特点
- 机器学习研究计算机系统如何利用经验(通常是数据)来提高完成特定任务的性能。
- 表示学习是机器学习的一类,其研究的重点是如何自动找到合适的数据表示方法。 深度学习是通过学习多层次的转换来进行多层次的表示学习。
# 第二章 预备知识
# 2.1 数据操作
# 数据操作
在Jupyter打开的本书Notebook tree中,新建 Notebook Python 3(ipykernel),来执行Python练习。
import torch
x = torch.arange(12)#创建行向量
print(x)
print(x.shape) #shape访问张量(沿每个轴的长度)的形状
print(x.numel())#元素总数
X = x.reshape(3, 4)#改变张量形状
print(X)
print(torch.zeros((2, 3, 4)))#创建特定形状,所有元素为0的张量
print(torch.ones((2, 3, 4)))#创建特定形状,所有元素为1的张量
print(torch.randn(3, 4))#创建特定形状,所有元素高斯分布随机采样的张量
print(torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]))
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 运算符
import torch
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
print (x + y)
print (x - y)
print (x * y)
print (x / y)
print (x ** y) # **运算符是求幂运算
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
print(X)
print(Y)
print(torch.cat((X, Y), dim=0))
print(torch.cat((X, Y), dim=1))
print(X==Y)#逻辑运算符来构建二元张量
Z= torch.tensor([1,2,3,4])
print(Z.sum())#所有元素求和,得到一个单元素张量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18