数据操作和预处理
数据操作
N维数组样例
- N维数组是机器学习和神经网络的主要数据结构
数据操作实现
import torch
我们使用pytorch框架,但我们导入的是torch
x = torch.arange(12)
demo1 = torch.arange(1,10)
demo2 = torch.range(1,10)
print(x)
print(demo1)
print(demo2)
print(demo1.dtype)
print(demo2.dtype)
'''最终的结果为:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])
tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
torch.int64
torch.float32'''
从上面的例子中,我们可以看到torch.arange()和torch.range()的区别。不过建议以后都用torch.arange(),因为torch.range()可能在今后的版本中被移除。
x = torch.arange(12)
print(x.shape)
print(x.numel())
print(x.reshape(2,6))
'''输出结果:
torch.Size([12])
12
tensor([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])'''
我们可以通过张量的 shape
属性来访问张量的形状 和张量中元素的总数,用numel()函数得到数组中值的数量。要改变一个张量的形状而不改变元素数量和元素值,可以调用 reshape
函数。
print(torch.zeros(3,4,5))
print(torch.ones(2,3,2))
print(torch.randn(2,2,2))
'''输出结果:
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., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 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.]]])
tensor([[[ 1.5315, -0.3653],
[-0.7024, -0.9643]],
[[ 0.0168, 0.7276],
[ 1.0024, -2.0303]]])'''
torch.zeros(),torch.ones(),torch.randn()输出的是全0,全1或者随机数的数组。
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])'''
torch.tensor是一个包含多个同类数据类型数据的多维矩阵。
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)
print(torch.exp(x))
'''输出结果:
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([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(X)
print(Y)
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.]])
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.]])'''
我们也可以把多个张量 连结(concatenate) 在一起,其中随着参数不同,方式也不同
print(X == Y)
'''输出结果:
tensor([[False, True, False, True],
[False, False, False, False],
[False, False, False, False]])'''
我们可以通过 逻辑运算符 构建二元张量
print(X.sum())
'''输出结果:
tensor(66.)'''
对张量中的所有元素进行求和会产生一个只有一个元素的张量
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]])'''
当两个数组的形状并不相同的时候,我们可以通过扩展数组的方法来实现相加、相减、相乘等操作,这种机制叫做广播(broadcasting)。
在上面的案例中,我们将a数组扩展成(3,2),第二列复制第一列的元素。将b数组扩展成(3,2),第2,3行复制第一行的元素,这样就可以进行加法操作。
print(X)
print(X[-1])
print(X[1:3])
print(X[:])
'''输出结果:
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 9., 7.],
[ 8., 9., 10., 11.]])
tensor([ 8., 9., 10., 11.])
tensor([[ 4., 5., 9., 7.],
[ 8., 9., 10., 11.]])
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 9., 7.],
[ 8., 9., 10., 11.]])'''
可以用 [-1]
选择最后一个元素,可以用 [1:3]
选择第二个和第三个元素,用[:]代表所有元素
X[1, 2] = 9
print(X)
X[0:2, :] = 12
print(X)
'''输出结果:
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.]])'''
c = 2.0
d = 2.0
print(id(c),id(d),id(2.0))
print('c == d:',c==d)
print('c is d:',c is d)#值相同,但地址不同
'''输出结果:
140232153204680 140232153204800 140232153204872
c == d: True
c is d: False'''
python中会为每个对象分配内存,哪怕他们的值完全相等。id(object)函数是返回对象object在其生命周期内位于内存中的地址,id函数的参数类型是一个对象。如下例子:c, d 和 2.0 地址不同,但值相等。
A = X.numpy()
B = torch.tensor(A)
print(type(A))
print(type(B))
'''输出结果:
<class 'numpy.ndarray'>
<class 'torch.Tensor'>'''
这里的numpy也是一种数组表示框架,比较常用。
a = torch.tensor([3.5])
print(a,a.item(),float(a),int(a))
'''输出结果:
tensor([3.5000]) 3.5 3.5 3'''
将大小为1的张量转换为 Python 标量
数据预处理
import os
os.makedirs(os.path.join('..', 'data'), exist_ok=True)
#os.makedirs(path,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')
import pandas as pd
data = pd.read_csv(data_file)#用于读取csv文件
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]
print(inputs)#第一列和第二列
print("\n")
print(outputs)#第三列
print("\n")
print(inputs.mean())#求平均值
print("\n")
inputs = inputs.fillna(inputs.mean())#用平均值代替原来缺失(非数字)部分
print(inputs)
'''输出结果:
NA Pave
0 2.0 NaN
1 4.0 NaN
2 NaN NaN
0 106000
1 178100
2 140000
Name: 127500, dtype: int64
NA 3.0
Pave NaN
dtype: float64
NA Pave
0 2.0 NaN
1 4.0 NaN
2 3.0 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'''
import torch
x, y = torch.tensor(inputs.values), torch.tensor(outputs.values)#用张量表示
print(x)
print(y)
'''tensor([[2., nan],
[4., nan],
[3., nan]], dtype=torch.float64)
tensor([106000, 178100, 140000])'''