动手学习深度学习-深度学习基础

本文章仅为本人在学习过程中的记录笔记,如有侵权,请联系。

李沐大神的课程地址:https://courses.d2l.ai/zh-v2/

3.20课程

深度学习介绍:

在这里插入图片描述
在这里插入图片描述

数据操作

首先,我们导入 torch。

import torch


张量表示一个数值组成的数组,这个数组可能有多个维度

x = torch.arange(12)
x
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

我们可以通过张量的 shape 属性来访问张量的 形状 和张量中元素的总数

x.shape
torch.Size([12])
x.numel()
12

要改变一个张量的形状而不改变元素数量和元素值,我们可以调用 reshape 函数。

x = x.reshape(3, 4)
x
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])

使用全0、全1、其他常量或者从特定分布中随机采样的数字

torch.zeros((2, 3, 4))
tensor([[[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]],

        [[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]])
torch.ones((2, 3, 4))
tensor([[[1., 1., 1., 1.],
         [1., 1., 1., 1.],
         [1., 1., 1., 1.]],

        [[1., 1., 1., 1.],
         [1., 1., 1., 1.],
         [1., 1., 1., 1.]]])
torch.randn(3, 4)
tensor([[ 1.5592,  0.7887, -1.0770, -0.2182],
        [ 0.6342, -0.7517, -0.0655,  0.3767],
        [ 0.3668, -1.3558, -0.4728, -0.6023]])

通过提供包含数值的 Python 列表(或嵌套列表)来为所需张量中的每个元素赋予确定值

torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]).shape
torch.Size([3, 4])

常见的标准算术运算符(+、-、*、/ 和 **)都可以被升级为按元素运算:

x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x**y
(tensor([ 3.,  4.,  6., 10.]),
 tensor([-1.,  0.,  2.,  6.]),
 tensor([ 2.,  4.,  8., 16.]),
 tensor([0.5000, 1.0000, 2.0000, 4.0000]),
 tensor([ 1.,  4., 16., 64.]))

按按元素方式应用更多的计算:

torch.exp(x)
tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])

我们也可以把多个张量连结在一起

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]])
torch.cat((x, y), dim=0), torch.cat((x, y), dim=1) 
(tensor([[ 0.,  1.,  2.,  3.],
         [ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.],
         [ 2.,  1.,  4.,  3.],
         [ 1.,  2.,  3.,  4.],
         [ 4.,  3.,  2.,  1.]]),
 tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
         [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
         [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]]))

通过 逻辑运算符 构建二元张量

print(x,'\n', y)
x == y
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]]) 
 tensor([[2., 1., 4., 3.],
        [1., 2., 3., 4.],
        [4., 3., 2., 1.]])





tensor([[False,  True, False,  True],
        [False, False, False, False],
        [False, False, False, False]])

对张量中的所有元素进行求和会产生一个只有一个元素的张量。

x.sum()
tensor(66.)

即使形状不同,我们仍然可以通过调用 广播机制 (broadcasting mechanism) 来执行按元素操作

a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
a, b
(tensor([[0],
         [1],
         [2]]),
 tensor([[0, 1]]))
a + b
tensor([[0, 1],
        [1, 2],
        [2, 3]])

可以用 [-1] 选择最后一个元素,可以用 [1:3] 选择第二个和第三个元素`

x[-1], x[1:3]
(tensor([ 8.,  9., 10., 11.]),
 tensor([[ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.]]))

除读取外,我们还可以通过指定索引来将元素写入矩阵。

print(x)
x[1, 2] = 9
print(x)
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]])
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  9.,  7.],
        [ 8.,  9., 10., 11.]])

为多个元素赋值相同的值,我们只需要索引所有元素,然后为它们赋值。

x[0:2, :] = 12
print(x)
tensor([[12., 12., 12., 12.],
        [12., 12., 12., 12.],
        [ 8.,  9., 10., 11.]])
tensor([[12., 12., 12., 12.],
        [12., 12., 12., 12.],
        [ 8.,  9., 10., 11.]])

运行一些操作可能会导致为新结果分配内存

before = id(y) # id 内存地址
y = y + x
id(y) == before
False

执行原地操作

z = torch.zeros_like(y)
print('id(z):', id(z))
z[:] = x + y
print('id(z):', id(z))
id(z): 2029580244960
id(z): 2029580244960

如果在后续计算中没有重复使用 X,我们也可以使用 X[:] = X + Y 或 X += Y 来减少操作的内存开销。

before = id(x)
x += y
id(x) == before
True

转换为 NumPy 张量

a =  x.numpy()
b = torch.tensor(a)

type(a), type(b)
(numpy.ndarray, torch.Tensor)

将大小为1的张量转换为 Python 标量

a = torch.tensor([3.5])
a, a.item(), float(a), int(a)
(tensor([3.5000]), 3.5, 3.5, 3)

数据预处理

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

创建一个人工数据集,并存储在csv(逗号分隔值)文件

import os

os.makedirs(os.path.join('..', 'data'), exist_ok=True)
data_file = os.path.join('..', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
    f.write('NumRooms,Alley,Price\n')  # 列名
    f.write('NA,Pave,127500\n')  # 每行表示一个数据样本 NA:未知数
    f.write('2,NA,106000\n')
    f.write('4,NA,178100\n')
    f.write('NA,NA,140000\n')
import pandas as pd

data = pd.read_csv(data_file)#读取csv文件
print(data)
data
   NumRooms Alley   Price
0       NaN  Pave  127500
1       2.0   NaN  106000
2       4.0   NaN  178100
3       NaN   NaN  140000
NumRooms Alley Price
0 NaN Pave 127500
1 2.0 NaN 106000
2 4.0 NaN 178100
3 NaN NaN 140000

为了处理缺失的数据,典型的方法包括 插值 和 删除, 这里,我们将考虑插值

inputs, outputs = data.iloc[:, 0:2], data.iloc[:, 2] # 将数据切分成两部分
print(inputs,'\n',outputs)
inputs = inputs.fillna(inputs.mean())

print(inputs)
   NumRooms Alley
0       NaN  Pave
1       2.0   NaN
2       4.0   NaN
3       NaN   NaN 
 0    127500
1    106000
2    178100
3    140000
Name: Price, dtype: int64
   NumRooms Alley
0       3.0  Pave
1       2.0   NaN
2       4.0   NaN
3       3.0   NaN

对于 inputs 中的类别值或离散值,我们将 “NaN” 视为一个类别。

inputs = pd.get_dummies(inputs, dummy_na=True) #one-hot编码
print(inputs)
   NumRooms  Alley_Pave  Alley_nan
0       3.0           1          0
1       2.0           0          1
2       4.0           0          1
3       3.0           0          1

现在 inputs 和 outputs 中的所有条目都是数值类型,它们可以转换为张量格式:

import torch

x, y = torch.tensor(inputs.values), torch.tensor(outputs.values)
x, y
(tensor([[3., 1., 0.],
         [2., 0., 1.],
         [4., 0., 1.],
         [3., 0., 1.]], dtype=torch.float64),
 tensor([127500, 106000, 178100, 140000]))

reshape与view:

a = torch.arange(12)
b = a.reshape((3, 4))
print(a)
b[:]=2
print(a)
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
tensor([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
a = torch.arange(12)
b = a.view((3, 4))
print(a)
b[:]=2
print(a)
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
tensor([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

3.21课程

线性代数

标量由只有一个元素的张量表示

import torch

x = torch.tensor([3.0])
y = torch.tensor([2.0])

x + y, x * y, x/y, x**y
(tensor([5.]), tensor([6.]), tensor([1.5000]), tensor([9.]))

可以将向量视为标量值组成的列表:

x = torch.arange(4)
x
tensor([0, 1, 2, 3])

通过张量的索引来访问任一元素:

x[3]
tensor(3)

访问张量的长度:

len(x)
4

只有一个轴的张量,形状只有一个元素:

x.shape
torch.Size([4])

通过指定两个分量m 和 n来创建一个形状为m×n 的矩阵:

a = torch.arange(20).reshape((5, 4))
a
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15],
        [16, 17, 18, 19]])

矩阵的转置:

a.T
tensor([[ 0,  4,  8, 12, 16],
        [ 1,  5,  9, 13, 17],
        [ 2,  6, 10, 14, 18],
        [ 3,  7, 11, 15, 19]])

对称矩阵(symmetric matrix) A 等于其转置:A= A ⊤ A^⊤ A

b = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
b
tensor([[1, 2, 3],
        [2, 0, 4],
        [3, 4, 5]])
b == b.T
tensor([[True, True, True],
        [True, True, True],
        [True, True, True]])

就像向量是标量的推广,矩阵是向量的推广一样,我们可以构建具有更多轴的数据结构:

x = torch.arange(24).reshape((2, 3, 4))
x
tensor([[[ 0,  1,  2,  3],
         [ 4,  5,  6,  7],
         [ 8,  9, 10, 11]],

        [[12, 13, 14, 15],
         [16, 17, 18, 19],
         [20, 21, 22, 23]]])

给定具有相同形状的任何两个张量,任何按元素二元运算的结果都将是相同形状的张量:

A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
B = A.clone() # 通过分配新的内存, 将A的一个副本分配给B

A , A + B
(tensor([[ 0.,  1.,  2.,  3.],
         [ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.],
         [12., 13., 14., 15.],
         [16., 17., 18., 19.]]),
 tensor([[ 0.,  2.,  4.,  6.],
         [ 8., 10., 12., 14.],
         [16., 18., 20., 22.],
         [24., 26., 28., 30.],
         [32., 34., 36., 38.]]))

两个矩阵的按元素乘法称为 哈达玛积(Hadamard product)(数学符号 ⊙):

A * B
tensor([[  0.,   1.,   4.,   9.],
        [ 16.,  25.,  36.,  49.],
        [ 64.,  81., 100., 121.],
        [144., 169., 196., 225.],
        [256., 289., 324., 361.]])
a = 2
X = torch.arange(24).reshape(2, 3, 4)
a + X , (a * X).shape 
(tensor([[[ 2,  3,  4,  5],
          [ 6,  7,  8,  9],
          [10, 11, 12, 13]],
 
         [[14, 15, 16, 17],
          [18, 19, 20, 21],
          [22, 23, 24, 25]]]),
 torch.Size([2, 3, 4]))

计算其元素的和

x  = torch.arange(4, dtype=torch.float32)
x, x.sum()
(tensor([0., 1., 2., 3.]), tensor(6.))

表示任意形状张量的元素和

print(A)
A.shape, A.sum()
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.],
        [12., 13., 14., 15.],
        [16., 17., 18., 19.]])





(torch.Size([5, 4]), tensor(190.))

指定求和汇总张量的轴

A_sum_axis0 = A.sum(axis=0)#axis=0 计算列
A_sum_axis0, A_sum_axis0.shape
(tensor([40., 45., 50., 55.]), torch.Size([4]))
A_sum_axis1 = A.sum(axis=1)#axis=1 计算行
A_sum_axis1, A_sum_axis1.shape
(tensor([ 6., 22., 38., 54., 70.]), torch.Size([5]))
A.sum(), A.sum(axis=[0,1])
(tensor(190.), tensor(190.))

一个与求和相关的量是 平均值(mean或average):

A.mean(), A.sum() / A.numel()
(tensor(9.5000), tensor(9.5000))
A.mean(axis=0), A.sum(axis=0) / A.shape[0]
(tensor([ 8.,  9., 10., 11.]), tensor([ 8.,  9., 10., 11.]))

计算总和或均值时保持轴数不变

sum_A = A.sum
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值