动手学深度学习(一)—— 数据操作及预处理
·
一.数据操作
首先,我们导入torch。请注意虽然被称为Pytorch,但是我们应该导入torch,而不是pytorch
import torch
张量表示一个数值组成的数组,这个数组可能有多个维度
x = torch.arange(12)
print(x)
'''
输出结果:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
'''
我们可以通过张量的shape属性来访问张量的形状和张量的元素总数
print(x.shape)
print(x.numel())
'''
输出结果:
torch.Size([12])
12
'''
要改变一个张量的形状而不改变元素数量和元素值,我们可以调用reshape函数
X = x.reshape(3,4)
print(X)
'''
输出结果:
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
'''
使用全0、全1、其他常量或者从特定分布中随机采样的数字
print(torch.zeros((2,3,4)))
print(torch.ones((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.]]])
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.]]])
'''
通过提供包含数值的Python列表(或者嵌套列表)来为所需张量中每个元素赋予确定值
print(torch.tensor([[2,1,4,3],[1,2,3,4],[4,3,2,1]]))
print(torch.tensor([[2,1,4,3],[1,2,3,4],[4,3,2,1]]).shape)
'''
输出结果:
tensor([[2, 1, 4, 3],
[1, 2, 3, 4],
[4, 3, 2, 1]])
torch.Size([3, 4])
'''
常见的标准算术运算符(+、-、/和*)都可以被升级为按元素运算
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)
'''
输出结果:
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.])
'''
按元素方式应用更多的计算
print(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]])
print(torch.cat((X,Y),dim=0)) ##竖着叠加
print(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 == y)
'''
输出结果:
tensor([[False, True, False, True],
[False, False, False, False],
[False, False, False, False]])
'''
对张量中的所有元素进行求和会产生一个只有一个元素的张量
print(X.sum())
'''
输出结果:
tensor(66)
'''
即使形状不同,我们仍然可以通过调用广播机制(broadcasting mechanism)来执行按元素操作
a = torch.arange(3).reshape((3,1))
b = torch.arange(2).reshape((1,2))
print(a)
print(b)
print(a+b)
'''
输出结果:
tensor([[0],
[1],
[2]])
tensor([[0, 1]])
tensor([[0, 1],
[1, 2],
[2, 3]])
'''
可以用[-1]选择最后一个元素,可以用[1:3]选择第二个和第三个元素
print(X[-1])
print(X[1:3])
'''
输出结果:
tensor([ 8., 9., 10., 11.])
tensor([[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
'''
除读取外,我们还可以通过指定索引来将元素写入矩阵
X[1,2] = 9
print(X)
'''
输出结果:
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]])
'''
运行一些操作可能会导致为新结果分配内存
before = id(Y)
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): 2107596130968
id(Z): 2107596130968
'''
如果在后续计算中没有重复使用x,我们也可以使用X[:] = X + Y或者X += Y来减少内存开销
before = id(X)
X += Y
id(X) == before
'''
输出结果:
True
'''
转换为Numpy张量
A = X.numpy()
B = torch.tensor(A)
print(type(A))
print(type(B))
'''
输出结果:
numpy.ndarray
torch.Tensor
'''
将大小为1的张量转换为Python标量
a = torch.tensor([3.5])
print(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')
f.write('2,NA,106000\n')
f.write('4,NA,178100\n')
f.write('NA,NA,140000\n')
从创建的csv文件中加载原始数据集
import pandas as pd
data = pd.read_csv(data_file)
print(data)
'''
输出结果:
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]
inputs = inputs.fillna(inputs.mean())
print(inputs)
'''
输出结果:
NumRooms Alley
0 3.0 Pave
1 2.0 NaN
2 4.0 NaN
3 3.0 NaN
'''
对于inputs中的类别或离散值,我们将“Nan”视为一个类别
## pandas中的get_dummies方法:将Alley这一列做one-hot编码
inputs = pd.get_dummies(inputs,dummy_na=True)
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)
## 对于深度学习而言,一般使用32位浮点数,64位浮点数过慢
print(x,y)
'''
输出结果:
tensor([[3., 1., 0.],
[2., 0., 1.],
[4., 0., 1.],
[3., 0., 1.]], dtype=torch.float64) tensor([127500, 106000, 178100, 140000])
'''
三.数据相关QA
1.reshape函数与view函数的区别:
二者没有本质上区别, reshape一个数组并没有没有改变地址,修改reshape后的数组,原数组也会改变
import torch
a = torch.arange(12)
b = a.reshape((3,4))
b[:] = 2
print(a)
'''
输出结果:
tensor([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
'''
2.torch和array有什么区别
tensor是一个数学上的概念,张量,数学上明确定义,array是一个计算机上的概念,数组,没有数学上定义,tensorflow和pytorch重载了数学上“张量的概念”,实质上,tesnor和array没有本质上区别
3.有图形化的torch编程方案吗?
用二维数学表达计算多元数据,感觉效率不高,没有太多可视化的工具
4.新分配了的y内存,之前y所对应的内存会释放吗?
如果这个内存没有被其他地方使用,Python会自动帮你释放内存
5.可以用jax代替numpy吗?
jax没有那么成熟,不建议使用
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)