李沐《动手学深度学习》课程笔记:03 安装、04 数据操作
·
目录
03 安装

(安装过程约等于劝退过程,我用的是windows装的pytorch,所以没有受到困扰。。。)
04 数据操作
1.数据操作
N维数组是机器学习和神经网络的主要数据结构


创建数组需要:
1.形状 :例如3*4矩阵
2.每个元素的数据类型:例如32位浮点数
3.每个元素的值,例如全是0,或者随机数

访问元素:

2.数据操作实现
张量表示一个数值组成的数组,这个数组可能有多个维度。
import torch
# 创建一个元素为0~11连续值的向量
x = torch.arange(12)
# 打印其形状
print(x.shape)
# 返回元素个数
print(x.numel())
# 改变形状,使其变成一个3行4列的矩阵
X = x.reshape(3, 4)
print(X)
# 创建一个元素全为0的张量
x = torch.zeros((2, 3, 4))
print(x)
# 创建一个元素全为1的张量
x = torch.ones((2, 3, 4))
print(x)
# 创建指定含有元素的张量
x = torch.tensor([[1, 2, 3, 4], [4, 3, 2, 1], [2, 3, 4, 2]])
print(x.shape)
# 进行两个张量之间的运算
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
print(x+y, x-y, x*y, x/y, 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)
# 求和
print(x.sum())
# 广播机制
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
print(a)
print(b)
print(a + b)
# 打印某些元素
print(x[-1])
print(x[1:3])
x[1, 2] = 9
print(x)
x[0:2, :] = 12
print(x)
# 保持元素的存储空间不变
before = id(y)
y = y + x
print(id(y) == before)
z = torch.zeros_like(y)
print('id(z):', id(z))
z[:] = x + y
print('id(z):', id(z))
before = id(x)
x += y
print(id(x) == before)
torch.Size([12])
12
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
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.]]])
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.Size([3, 4])
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.])
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([[ 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.]])
tensor([[False, True, False, True],
[False, False, False, False],
[False, False, False, False]])
tensor(66.)
tensor([[0],
[1],
[2]])
tensor([[0, 1]])
tensor([[0, 1],
[1, 2],
[2, 3]])
tensor([ 8., 9., 10., 11.])
tensor([[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 9., 7.],
[ 8., 9., 10., 11.]])
tensor([[12., 12., 12., 12.],
[12., 12., 12., 12.],
[ 8., 9., 10., 11.]])
False
id(z): 1600446271136
id(z): 1600446271136
True
<class 'numpy.ndarray'>
<class 'torch.Tensor'>
3.5
3.5
3
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)