<jupyter_start><jupyter_text>PyTorch 在这节课中，我们将学习PyTorch，它是一个用于构建动态神经网络的学习库。我们将在本课程中了解其基础知识，以及如何创建和使用张量（Tensor），而我们将在下一课中使用它制作模型。  Tensor 基础知识<jupyter_code># 安装PyTorch库
!pip3 install torch<jupyter_output>Collecting torch
[?25l  Downloading https://files.pythonhosted.org/packages/7e/60/66415660aa46b23b5e1b72bc762e816736ce8d7260213e22365af51e8f9c/torch-1.0.0-cp36-cp36m-manylinux1_x86_64.whl (591.8MB)
[K    100% |████████████████████████████████| 591.8MB 28kB/s 
tcmalloc: large alloc 1073750016 bytes == 0x61f04000 @  0x7f61a90372a4 0x591a07 0x5b5d56 0x502e9a 0x506859 0x502209 0x502f3d 0x506859 0x504c28 0x502540 0x502f3d 0x506859 0x504c28 0x502540 0x502f3d 0x506859 0x504c28 0x502540 0x502f3d 0x507641 0x502209 0x502f3d 0x506859 0x504c28 0x502540 0x502f3d 0x507641 0x504c28 0x502540 0x502f3d 0x507641
[?25hInstalling collected packages: torch
Successfully installed torch-1.0.0<jupyter_text>>  注意：上述安装PyTorch的方式与官网并不一致，因为这里是基于Colab云端安装的，而大家一般是使用pip或者conda来安装PyTorch。具体安装教程参考：https://pytorch.org/<jupyter_code>import numpy as np
import torch
# 创建一个张量
x = torch.Tensor(3, 4)
print("Type: {}".format(x.type()))
print("Size: {}".format(x.shape))
print("Values: \n{}".format(x))
# 创建一个随机张量
x = torch.randn(2, 3) # torch.randn对应于正态分布，而rand(2,3)对应于均匀分布
print (x)
# 0和1张量
x = torch.zeros(2, 3)
print (x)
x = torch.ones(2, 3)
print (x)
# 列表（List） → 张量
x = torch.Tensor([[1, 2, 3],[4, 5, 6]])
print("Size: {}".format(x.shape)) 
print("Values: \n{}".format(x))
# NumPy 数组 → 张量
x = torch.from_numpy(np.random.rand(2, 3))
print("Size: {}".format(x.shape)) 
print("Values: \n{}".format(x))
# 改变张量类型（张量默认为float类型）
x = torch.Tensor(3, 4)
print("Type: {}".format(x.type()))
x = x.long()
print("Type: {}".format(x.type()))<jupyter_output>Type: torch.FloatTensor
Type: torch.LongTensor<jupyter_text>Tensor 运算<jupyter_code># 加法
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = x + y
print("Size: {}".format(z.shape)) 
print("Values: \n{}".format(z))
# 向量点积
x = torch.randn(2, 3)
y = torch.randn(3, 2)
z = torch.mm(x, y)
print("Size: {}".format(z.shape)) 
print("Values: \n{}".format(z))
# 转置
x = torch.randn(2, 3)
print("Size: {}".format(x.shape)) 
print("Values: \n{}".format(x))
y = torch.t(x)
print("Size: {}".format(y.shape)) 
print("Values: \n{}".format(y))
# Reshape
z = x.view(3, 2)
print("Size: {}".format(z.shape)) 
print("Values: \n{}".format(z))
# reshaping的危险（意外后果）
x = torch.tensor([
    [[1,1,1,1], [2,2,2,2], [3,3,3,3]],
    [[10,10,10,10], [20,20,20,20], [30,30,30,30]]
])
print("Size: {}".format(x.shape)) 
print("Values: \n{}\n".format(x))
a = x.view(x.size(1), -1)
print("Size: {}".format(a.shape)) 
print("Values: \n{}\n".format(a))
b = x.transpose(0,1).contiguous()
print("Size: {}".format(b.shape)) 
print("Values: \n{}\n".format(b))
c = b.view(b.size(0), -1)
print("Size: {}".format(c.shape)) 
print("Values: \n{}".format(c))
# 维度操作
x = torch.randn(2, 3)
print("Values: \n{}".format(x))
y = torch.sum(x, dim=0) # 为每列添加各行叠加的值
print("Values: \n{}".format(y))
z = torch.sum(x, dim=1) # 为每行添加各列叠加的值
print("Values: \n{}".format(z))<jupyter_output>Values: 
tensor([[-2.2913,  0.1027, -0.3427],
        [ 0.7189,  0.4223, -0.0364]])
Values: 
tensor([-1.5724,  0.5250, -0.3791])
Values: 
tensor([-2.5313,  1.1048])<jupyter_text>索引，切片和级联<jupyter_code>x = torch.randn(3, 4)
print("x: \n{}".format(x))
print ("x[:1]: \n{}".format(x[:1]))
print ("x[:1, 1:3]: \n{}".format(x[:1, 1:3]))
# 选择维度索引
x = torch.randn(2, 3)
print("Values: \n{}".format(x))
col_indices = torch.LongTensor([0, 2])
chosen = torch.index_select(x, dim=1, index=col_indices) # 第0和第2列的值
print("Values: \n{}".format(chosen)) 
row_indices = torch.LongTensor([0, 1])
chosen = x[row_indices, col_indices] # 来自（0,0）和（2,1）的值
print("Values: \n{}".format(chosen)) 
# 级联
x = torch.randn(2, 3)
print("Values: \n{}".format(x))
y = torch.cat([x, x], dim=0) # 按行堆叠（dim = 1按列堆叠）
print("Values: \n{}".format(y))<jupyter_output>Values: 
tensor([[-0.4772,  0.7716,  2.2474],
        [ 1.3227, -0.4346,  1.1521]])
Values: 
tensor([[-0.4772,  0.7716,  2.2474],
        [ 1.3227, -0.4346,  1.1521],
        [-0.4772,  0.7716,  2.2474],
        [ 1.3227, -0.4346,  1.1521]])<jupyter_text>梯度<jupyter_code># 带有gradient bookkeeping的张量
x = torch.rand(3, 4, requires_grad=True)
y = 3*x + 2
z = y.mean()
z.backward() # z是标量
print("Values: \n{}".format(x))
print("x.grad: \n", x.grad)<jupyter_output>Values: 
tensor([[0.9651, 0.9546, 0.2183, 0.5656],
        [0.2327, 0.4397, 0.7654, 0.8600],
        [0.5148, 0.8122, 0.1790, 0.7555]], requires_grad=True)
x.grad: 
 tensor([[0.2500, 0.2500, 0.2500, 0.2500],
        [0.2500, 0.2500, 0.2500, 0.2500],
        [0.2500, 0.2500, 0.2500, 0.2500]])<jupyter_text>* $ y = 3x + 2 $* $ z = \sum{y}/N $* $ \frac{\partial(z)}{\partial(x)} = \frac{\partial(z)}{\partial(y)} \frac{\partial(z)}{\partial(x)} = \frac{1}{N} * 3 = \frac{1}{12} * 3 = 0.25 $  CUDA 张量<jupyter_code># CUDA可用吗？
print (torch.cuda.is_available())<jupyter_output>True<jupyter_text>如果上面的代码返回False，那么请转到菜单栏上的`Runtime`→`Change runtime type`并在`Hardware accelerator`下选择`GPU`。<jupyter_code># 创建一个CPU版的0张量
x = torch.Tensor(3, 4).to("cpu")
print("Type: {}".format(x.type()))
# 创建一个CUDA版的0张量
x = torch.Tensor(3, 4).to("cuda")
print("Type: {}".format(x.type()))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.23291866028708133, 'fraction_numerical': 0.13110047846889952, 'mean_word_length': 5.191943127962086, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 24, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '172407', 'license': 'MIT', 'n_tokens_mistral': 3033, 'n_tokens_neox': 2725, 'n_words': 394, 'path': 'notebooks/07_PyTorch.ipynb', 'repo_name': 'digbangbang/practicalAI-cn', 'size': '5225'}